text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace SnakeMultiplayer.Services;
public interface IGameServerService
{
string AddPlayerToLobby(string lobby, string player);
string CanJoin(string lobbyName, string playerName);
void EndGame(string lobby);
ILobbyService GetLobbyService(string lobby);
List<Tuple<string, string>> GetLobbyStatus();
bool LobbyExists(string lobbyName);
bool PlayerExists(string lobbyName, string playerName);
void RemoveLobby(string lobby);
bool TryCreateLobby(string lobbyName, string hostPlayerName, IGameServerService service);
}
/// <summary>
/// Gives abstraction layer to web socket based communication:
/// Distributes incoming messages to relevant lobbies and
/// forwads messages from lobbies to web sockets
/// </summary>
public class GameServerService : IGameServerService
{
//TODO: Move to constants
public static Regex ValidStringRegex = new(@"^[a-zA-Z0-9]+[a-zA-Z0-9\s_]*[a-zA-Z0-9]+$");
readonly int MaxPlayersInLobby = 4;
readonly ConcurrentDictionary<string, LobbyService> lobbies = new();
public string AddPlayerToLobby(string lobby, string player)
{
try
{
return lobbies[lobby].AddPlayer(player);
}
catch (Exception ex)
{
return ex.Message;
}
}
public bool TryCreateLobby(string lobbyName, string hostPlayerName, IGameServerService service)
=> lobbies.TryAdd(lobbyName, new LobbyService(lobbyName, hostPlayerName, MaxPlayersInLobby));
public string CanJoin(string lobbyName, string playerName) =>
!lobbies.TryGetValue(lobbyName, out var lobby)
? $"Lobby {lobbyName} does not exist. Please try a different name"
: lobby.CanJoin(playerName);
public bool LobbyExists(string lobbyName) => lobbies.ContainsKey(lobbyName);
public bool PlayerExists(string lobbyName, string playerName) =>
lobbies.TryGetValue(lobbyName, out var lobby)
? lobby.PlayerExists(playerName)
: throw new EntryPointNotFoundException($"Lobby {lobbyName} does not exists");
public void EndGame(string lobby)
{
if (lobbies.TryGetValue(lobby, out var lobbyService))
lobbyService.EndGame();
}
public void RemoveLobby(string lobby)
{
if (lobby == null)
throw new ArgumentNullException(nameof(lobby), "Tried to remove null lobby from lobby dictionary");
_ = lobbies.TryRemove(lobby, out _);
}
public List<Tuple<string, string>> GetLobbyStatus()
{
var lobbyList = new List<Tuple<string, string>>(lobbies.Count);
foreach (var pair in lobbies)
{
lobbyList.Add(new Tuple<string, string>(pair.Key, pair.Value.GetPlayerCount().ToString()));
}
return lobbyList;
}
public ILobbyService GetLobbyService(string lobby) => lobbies[lobby];
} |
using OrchardCore.Modules.Manifest;
[assembly: Module(
Name = "Grouping Fields",
Author = "National Careers Service",
Website = "https://dfc-dev-stax-editor-as.azurewebsites.net",
Version = "0.0.1",
Description = "Enables custom Tab / Accordion fields for turning content parts into tabs or accordions.",
Category = "Content Management",
Dependencies = new[] { "OrchardCore.Contents", "OrchardCore.ContentTypes", "OrchardCore.ResourceManagement" }
)]
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Thingy.WebServerLite.Api;
namespace Thingy.WebServerLite
{
public class ViewResult : IViewResult
{
public string Content { get; set; }
public string ContentType { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Chess.Data.Enum;
namespace Chess.Data.Entities
{
public abstract class ChessPiece : IPiece, IModifiable
{
[Key]
public int ChessPieceId { get; set; }
public long GameId { get; set; }
public int MoveCount { get; set; }
public bool Alive { get; set; }
public int? CurrentRow { get; set; }
public int? CurrentColumn { get; set; }
public int ScoreValue { get; set; }
public int ActionValue { get; set; } //this may be used to help the CPU attack with weaker pieces later on?
public int AttackValue { get; set; }
public int DefenseValue { get; set; }
public Team Team { get; set; }
public PieceType PieceType { get; set; }
public PieceType GetPieceType()
{
return PieceType;
}
protected ChessPiece GetAttacker(Square[][] board, Move move)
{
return board[move.StartRow][move.StartColumn].ChessPiece;
}
protected Team GetOppositeTeam()
{
if (Team == Team.Light)
return Team.Dark;
return Team.Light;
}
protected ChessPiece GetDestinationPiece(Square[][] board, Move move)
{
return board[move.EndRow][move.EndColumn].ChessPiece;
}
protected void ValidateNotAttackingSameTeam(Square[][] board, Move move)
{
var attacker = GetAttacker(board, move);
var occupant = GetDestinationPiece(board, move);
if (occupant != null && occupant.Team == attacker.Team)
throw new Exception("You may not attack the same team.");
}
protected bool InBounds(int row, int column)
{
var rowInBounds = 0 <= row && row <= 7;
var columnInBounds = (0 <= column && column <= 7);
return rowInBounds && columnInBounds;
}
protected int GetMovementModifier(int change)
{
return change > 0 ? 1 : change < 0 ? -1 : 0;
}
protected bool HasCollision(Square[][] board, Move move)
{
var rowModifier = GetMovementModifier(move.RowChange);
var columnModifier = GetMovementModifier(move.ColumnChange);
var row = move.StartRow + rowModifier;
var column = move.StartColumn + columnModifier;
while (row != move.EndRow || column != move.EndColumn)
{
if (!InBounds(row, column))
return true; //out of bounds
if (board[row][column].ChessPiece != null)
return true; //collison
row += rowModifier;
column += columnModifier;
}
return false;
}
public abstract IEnumerable<Move> GetValidMoves(Square[][] board);
public abstract bool IsLegalMove(Square[][] board, Move move, IEnumerable<Move> pastMoves = null);
public void Move(Square[][] board, Move move)
{
DestroyOccupant(board, move);
board[move.EndRow][move.EndColumn].ChessPiece = this;
board[move.StartRow][move.StartColumn].ChessPiece = null;
CurrentColumn = move.EndColumn;
CurrentRow = move.EndRow;
MoveCount++;
}
private void DestroyOccupant(Square[][] board, Move move)
{
var occupant = GetDestinationPiece(board, move);
if (occupant != null)
{
occupant.Alive = false;
occupant.CurrentColumn = null;
occupant.CurrentRow = null;
}
}
protected void GetDiagonalMoves(Square[][] board, int row, int column, List<Tuple<int, int>> endPositions)
{
for (var r = row; r < 8; r++)
{
ChessPiece occupant;
for (var c = column; c < 8; c++)
{
occupant = board[r][c].ChessPiece;
if (occupant != null && occupant.Team == Team) break;
endPositions.Add(new Tuple<int, int>(r, c));
if (occupant != null && occupant.Team != Team) break;
}
for (var c = column; c >= 0; c--)
{
occupant = board[r][c].ChessPiece;
if (occupant != null && occupant.Team == Team) break;
endPositions.Add(new Tuple<int, int>(r, c));
if (occupant != null && occupant.Team != Team) break;
}
}
}
protected void GetHorizontalMoves(Square[][] board, int row, int column, List<Tuple<int, int>> endPositions)
{
ChessPiece occupant;
for (var r = row; r < 8; r++)
{
occupant = board[r][column].ChessPiece;
if (occupant != null && occupant.Team == Team) break;
endPositions.Add(new Tuple<int, int>(r, column));
if (occupant != null && occupant.Team != Team) break;
}
for (var r = row; r >= 0; r--)
{
occupant = board[r][column].ChessPiece;
if (occupant != null && occupant.Team == Team) break;
endPositions.Add(new Tuple<int, int>(r, column));
if (occupant != null && occupant.Team != Team) break;
}
}
protected void GetVerticalMoves(Square[][] board, int column, int row, List<Tuple<int, int>> endPositions)
{
ChessPiece occupant;
for (var c = column; c < 8; c++)
{
occupant = board[row][c].ChessPiece;
if (occupant != null && occupant.Team == Team) break;
endPositions.Add(new Tuple<int, int>(row, c));
if (occupant != null && occupant.Team != Team) break;
}
for (var c = column; c < 8; c--)
{
occupant = board[row][c].ChessPiece;
if (occupant != null && occupant.Team == Team) break;
endPositions.Add(new Tuple<int, int>(row, c));
if (occupant != null && occupant.Team != Team) break;
}
}
protected Move SetupNewMove(int row, int column)
{
if (!CurrentColumn.HasValue || !CurrentRow.HasValue)
throw new Exception("A move can not be setup, this piece is missing a row or column.");
return new Move()
{
EndRow = row,
EndColumn = column,
StartRow = CurrentRow.Value,
StartColumn = CurrentColumn.Value
};
}
protected int LegalDirectionByTeam()
{
if (Team == Team.Light)
return 1;
return -1;
}
}
} |
#pragma warning disable CS0618
namespace Sentry.Samples.Ios;
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
public override UIWindow? Window
{
get;
set;
}
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
// Init the Sentry SDK
SentrySdk.Init(o =>
{
o.Debug = true;
o.Dsn = "https://eb18e953812b41c3aeb042e666fd3b5c@o447951.ingest.sentry.io/5428537";
});
// create a new window instance based on the screen size
Window = new UIWindow(UIScreen.MainScreen.Bounds);
// determine the background color for the view (SystemBackground requires iOS >= 13.0)
var backgroundColor = UIDevice.CurrentDevice.CheckSystemVersion(13, 0)
#pragma warning disable CA1416
? UIColor.SystemBackground
#pragma warning restore CA1416
: UIColor.White;
// create a UIViewController with a single UILabel
var vc = new UIViewController();
vc.View!.AddSubview(new UILabel(Window!.Frame)
{
BackgroundColor = backgroundColor,
TextAlignment = UITextAlignment.Center,
Text = "Hello, iOS!",
AutoresizingMask = UIViewAutoresizing.All,
});
Window.RootViewController = vc;
// make the window visible
Window.MakeKeyAndVisible();
// Try out the Sentry SDK
SentrySdk.CaptureMessage("From iOS");
// Uncomment to try these
// throw new Exception("Test Unhandled Managed Exception");
// SentrySdk.CauseCrash(CrashType.Native);
return true;
}
}
|
using System;
namespace GK.Api.Core
{
public interface IApiInfo
{
string Description { get; set; }
string FriendlyVersion { get; }
string FullName { get; }
string Name { get; set; }
string SwaggerJsonUrl { get; }
Version Version { get; set; }
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace HotelDatabase.Models
{
public class Occupancy
{
[Key]
public int Id { get; set; }
[Required]
public DateTime DateOccupied { get; set; }
[Range(1,int.MaxValue)]
public int AccountNumber { get; set; }
[Range(1,int.MaxValue)]
public int RoomNumber { get; set; }
[Range(typeof(decimal), "0", "10000000000")]
public decimal RateApplied { get; set; }
[Range(typeof(decimal), "0", "10000000000")]
public decimal PhoneCharge { get; set; }
[MaxLength(1000)]
public string Notes { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Laoziwubo.IBLL;
using Laoziwubo.IDAL;
using Laoziwubo.Model.Common;
namespace Laoziwubo.BLL
{
public class BaseB<T> : IBaseB<T>
{
private readonly IBaseD<T> _dao;
public BaseB(IBaseD<T> dao)
{
_dao = dao;
}
public Task<IEnumerable<T>> GetListAsync(QueryM q)
{
return _dao.GetEntitysAsync(q);
}
public T GetEntityById(int id)
{
return _dao.GetEntityById(id);
}
public bool Insert(T model)
{
return _dao.Insert(model);
}
public bool Update(T model)
{
return _dao.Update(model);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using CoreTest1.Data;
using CoreTest1.Models;
namespace CoreTest1.Controllers
{
public class LeftsController : Controller
{
private readonly RocketContext _context;
public LeftsController(RocketContext context)
{
_context = context;
}
// GET: Lefts
public async Task<IActionResult> Index()
{
var rocketContext = _context.Lefts.Include(l => l.Part).Include(l => l.Stock);
return View(await rocketContext.ToListAsync());
}
// GET: Lefts/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var left = await _context.Lefts
.Include(l => l.Part)
.Include(l => l.Stock)
.FirstOrDefaultAsync(m => m.ID == id);
if (left == null)
{
return NotFound();
}
return View(left);
}
// GET: Lefts/Create
public IActionResult Create()
{
ViewData["PartID"] = new SelectList(_context.Parts, "ID", "ID");
ViewData["StockID"] = new SelectList(_context.Stocks, "ID", "ID");
return View();
}
// POST: Lefts/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,PartID,StockID,ArrDate,Quantity")] Left left)
{
if (ModelState.IsValid)
{
_context.Add(left);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["PartID"] = new SelectList(_context.Parts, "ID", "ID", left.PartID);
ViewData["StockID"] = new SelectList(_context.Stocks, "ID", "ID", left.StockID);
return View(left);
}
// GET: Lefts/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var left = await _context.Lefts.FindAsync(id);
if (left == null)
{
return NotFound();
}
ViewData["PartID"] = new SelectList(_context.Parts, "ID", "ID", left.PartID);
ViewData["StockID"] = new SelectList(_context.Stocks, "ID", "ID", left.StockID);
return View(left);
}
// POST: Lefts/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,PartID,StockID,ArrDate,Quantity")] Left left)
{
if (id != left.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(left);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!LeftExists(left.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["PartID"] = new SelectList(_context.Parts, "ID", "ID", left.PartID);
ViewData["StockID"] = new SelectList(_context.Stocks, "ID", "ID", left.StockID);
return View(left);
}
// GET: Lefts/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var left = await _context.Lefts
.Include(l => l.Part)
.Include(l => l.Stock)
.FirstOrDefaultAsync(m => m.ID == id);
if (left == null)
{
return NotFound();
}
return View(left);
}
// POST: Lefts/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var left = await _context.Lefts.FindAsync(id);
_context.Lefts.Remove(left);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool LeftExists(int id)
{
return _context.Lefts.Any(e => e.ID == id);
}
}
}
|
// <copyright file="Constraint.cs" company="Firoozeh Technology LTD">
// Copyright (C) 2020 Firoozeh Technology LTD. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using FiroozehGameService.Models.Enums;
using FiroozehGameService.Utils;
/**
* @author Alireza Ghodrati
*/
namespace FiroozehGameService.Models.BasicApi.DBaaS.Options
{
/// <summary>
/// Represents ConstraintOptionData Model In Game Service Basic API
/// </summary>
[Serializable]
public class Constraint : TableOption
{
private int _limit;
private int _skip;
/// <summary>
/// Constraint TableOption
/// </summary>
/// <param name="skip">Skip Value for Constraint TableOption</param>
/// <param name="limit">Limit Value for Constraint TableOption</param>
public Constraint(int skip, int limit)
{
_skip = skip < 0
? throw new GameServiceException("Invalid Skip Value").LogException<Constraint>(DebugLocation.Internal,
"Constructor")
: _skip = skip;
_limit = limit <= 0 || limit > 200
? throw new GameServiceException("Invalid Limit Value, Value must Between 0 and 200")
.LogException<Constraint>(DebugLocation.Internal, "Constructor")
: _limit = limit;
}
internal override string GetParsedData()
{
return "&skip=" + _skip + "&limit=" + _limit;
}
}
} |
using UnityEngine;
using System.Collections;
public class FinalNotes : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine(PlayMusicLove());
}
IEnumerator PlayMusicLove()
{
while (true)
{
GetComponent<NoteSpawner>().SpawnRandomNote();
yield return new WaitForSeconds(Random.Range(1f, 2f));
}
}
}
|
using Extreme.Statistics.Distributions;
using System;
using System.Collections.Generic;
using System.Text;
namespace SimulationDemo.Randomness
{
public class Bernoulli : DistributionBase, IDistribution
{
private double _probability;
public Bernoulli(double probability)
{
_probability = probability;
}
public void PrintOut()
{
Console.WriteLine($"Bernoulli distribution with probability = {_probability}");
}
public override string ToString()
{
return $"Bernoulli({_probability})";
}
public ValueType Sample()
{
var bernoulli = new BernoulliDistribution(_probability);
return bernoulli.Sample(rand);
}
}
}
|
using Leprechaun.Model;
namespace Leprechaun.CodeGen
{
public interface ICodeGenerator
{
void GenerateCode(ConfigurationCodeGenerationMetadata metadata);
}
}
|
# region Includes
using System.Collections.Generic;
using System.Drawing;
using RobX.Library.Commons;
# endregion
namespace RobX.Simulator
{
/// <summary>
/// Class containing simulation envitonment parameters (obstacles, robot position, etc.).
/// </summary>
public class Environment
{
# region Public Variables
/// <summary>
/// Variable for Robot settings.
/// </summary>
public readonly RobotProperties Robot = new RobotProperties();
/// <summary>
/// Variable for Ground settings.
/// </summary>
public readonly GroundProperties Ground = new GroundProperties();
/// <summary>
/// The list of all obstacles in the environment.
/// </summary>
public readonly List<Obstacle> Obstacles = new List<Obstacle>();
# endregion
# region Public Classes
/// <summary>
/// Class for ground properties.
/// </summary>
public class GroundProperties
{
/// <summary>
/// Default ground width in millimeters.
/// </summary>
private const int DefaultWidth = 5000;
/// <summary>
/// Default ground height in millimeters.
/// </summary>
private const int DefaultHeight = 5000;
/// <summary>
/// The width of the ground in millimeters.
/// </summary>
public int Width = DefaultWidth;
/// <summary>
/// The height of the ground in millimeters.
/// </summary>
public int Height = DefaultHeight;
}
/// <summary>
/// Class for physical robot properties.
/// </summary>
public class RobotProperties
{
/// <summary>
/// The vertical position of the robot in millimeters.
/// </summary>
public double X;
/// <summary>
/// The horizontal position of the robot in millimeters.
/// </summary>
public double Y;
/// <summary>
/// The robot angle (in degrees).
/// </summary>
public double Angle;
/// <summary>
/// The trace (path) of the robot in the simulation.
/// </summary>
public readonly List<PointF> Trace = new List<PointF>();
}
# endregion
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MapNode
{
public int x;
public int y;
public int movementCost = 0;
public int parentCost = 0;
int heuristicCost = 0;
public int fullCost;
public bool isWalkable = true;
MapNode parentNode = null;
public string list = ".";
public SpawnedItemBase item;
public MapNode(int x, int y, bool isWalkable)
{
this.x = x;
this.y = y;
this.isWalkable = isWalkable;
}
public void SetMovementCost(int heuristic)
{
heuristicCost = heuristic;
fullCost = movementCost + heuristicCost + parentCost;
}
public void SetHeuristicCost(int heuristic)
{
heuristicCost = heuristic;
fullCost = movementCost + heuristicCost + parentCost;
}
public void SetParent(MapNode node){
parentNode = node;
fullCost = movementCost + heuristicCost + parentCost;
}
public void ClearNode()
{
parentNode = null;
movementCost = 10;
parentCost = 0;
heuristicCost = 10;
}
public MapNode GetParent()
{
return parentNode;
}
}
public class Map {
public MapNode[][] nodes;
int width;
int height;
public Map(int width, int height)
{
this.width = width;
this.height = height;
nodes = new MapNode[height][];
for (int i = 0; i < nodes.Length; i += 1)
{
nodes[i] = new MapNode[width];
}
}
public MapNode GetNodeNormalized(float x, float y){
return GetNode((int)(-x + 0.5f),(int)(y + 1f));
}
public MapNode GetNode(int x, int y)
{
try {
MapNode node = nodes[y][x];
if (node != null)
{
return nodes[y][x];
}
}
catch (System.IndexOutOfRangeException)
{
return null;
}
return null;
}
public void AddNode(int x, int y, bool isWalkable)
{
nodes[y][x] = new MapNode(x, y, isWalkable);
}
public void AddNode(int x, int y)
{
//if (nodes[y][x] != null) {
nodes[y][x] = new MapNode(x, y, true);
//}
}
public string NeighborsToString(MapNode currentNode)
{
string content = currentNode.x + "," + currentNode.y + "\n";
List<MapNode> neighbors = GetNeighbors(currentNode);
int levels = 0;
foreach(MapNode neighbor in neighbors){
if(neighbor.isWalkable){
content += neighbor.list;
}
else
{
if (neighbor.x == -1)
{
content += "X";
}
else
{
content += "x";
}
}
levels += 1;
if (levels % 3 == 0)
{
content += "\n";
}
if (levels == 4)
{
content += "p";
levels += 1;
}
}
return content;
}
public List<MapNode> GetNeighbors(MapNode currentNode){
int x = currentNode.x;
int y = currentNode.y;
List<MapNode> neighbors = new List <MapNode>();
for(int yBounds = -1; yBounds <= 1; yBounds += 1){
for(int xBounds = -1; xBounds <= 1; xBounds += 1){
if(xBounds == 0 && yBounds == 0){
continue;
}
if(IsWithinBounds(x + xBounds, y + yBounds)){
MapNode node = nodes[y + yBounds][x + xBounds];
if (node != null) {
//node.movementCost = (xBounds == 0 || yBounds == 0) ? 10 : 14;
neighbors.Add(node);
}
else
{
neighbors.Add(new MapNode(-1, -1, false));
}
}
else
{
neighbors.Add(new MapNode(-1, -1, false));
}
}
}
return neighbors;
}
bool IsWithinBounds(int x, int y)
{
return (x >= 0 && x < width) && (y >= 0 && y < height);
}
public string PrintableString(){
string content = "";
for (int i = 0; i < height; i += 1)
{
for (int j = 0; j < width; j += 1)
{
if (nodes[i][j] != null) {
if (nodes[i][j].isWalkable)
{
content += ".";
}
else
{
content += "x";
}
}
else
{
content += " ";
}
}
content += "\n";
}
return content;
}
}
|
using Kitapcim.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Kitapcim.Controllers
{
public class UyelikController : Controller
{
ApplicationDbContext _db = new ApplicationDbContext();
UserManager<ApplicationUser> UserManager { get; set; }
RoleManager<IdentityRole> RoleManager { get; set; }
IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
public UyelikController()
{
UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
}
}
}
|
using GameFormatReader.Common;
using System;
using System.Collections.Generic;
using System.IO;
namespace WindEditor
{
public class WStage : WScene
{
private WSkyboxNode m_skybox;
public WStage(WWorld world) : base(world)
{
IsRendered = true;
}
public override void Load(string filePath)
{
base.Load(filePath);
foreach (var folder in Directory.GetDirectories(filePath))
{
string folderName = Path.GetFileNameWithoutExtension(folder);
switch (folderName.ToLower())
{
case "dzs":
{
string fileName = Path.Combine(folder, "stage.dzs");
if (File.Exists(fileName))
LoadLevelEntitiesFromFile(fileName);
}
break;
case "bmd":
case "bdl":
{
m_skybox = new WSkyboxNode(m_world);
m_skybox.LoadSkyboxModelsFromFixedModelList(folder);
m_skybox.SetParent(this);
}
break;
}
}
}
public void PostLoadProcessing(string mapDirectory, List<WRoom> mapRooms)
{
string dzsFilePath = Path.Combine(mapDirectory, "Stage/dzs/stage.dzs");
if (File.Exists(dzsFilePath))
{
SceneDataLoader sceneData = new SceneDataLoader(dzsFilePath, m_world);
// Load Room Translation info. Wind Waker stores collision and entities in world-space coordinates,
// but models all of their rooms around 0,0,0. To solve this, there is a chunk labeled "MULT" which stores
// the room model's translation and rotation.
var multTable = sceneData.GetRoomTransformTable();
if (mapRooms.Count != multTable.Count)
Console.WriteLine("WStage: Mismatched number of entries in Mult Table ({0}) and number of loaded rooms ({1})!", multTable.Count, mapRooms.Count);
for (int i = 0; i < multTable.Count; i++)
{
WRoom room = mapRooms.Find(x => x.RoomIndex == multTable[i].RoomNumber);
if (room != null)
room.RoomTransform = multTable[i];
}
// Load Room Memory Allocation info. How much extra memory do these rooms allocate?
var allocTable = sceneData.GetRoomMemAllocTable();
if (mapRooms.Count != allocTable.Count)
Console.WriteLine("WStage: Mismatched number of entries in Meco Table ({0}) and number of loaded rooms ({1})!", allocTable.Count, mapRooms.Count);
for (int i = 0; i < allocTable.Count; i++)
{
WRoom room = mapRooms.Find(x => allocTable[i].RoomIndex == x.RoomIndex);
if (room != null)
room.MemoryAllocation = allocTable[i].MemorySize;
}
// Extract our EnvR data.
var envrData = GetLightingData();
// This doesn't always match up, as sea has 52 EnvR entries but only 50 rooms, but meh.
if (mapRooms.Count != envrData.Count)
{
Console.WriteLine("WStage: Mismatched number of entries in Envr ({0}) and number of loaded rooms ({1})!",
envrData.Count, mapRooms.Count);
}
if (envrData.Count > 0)
{
foreach (var room in mapRooms)
{
room.EnvironmentLighting = envrData[0];
}
}
for (int i = 0; i < envrData.Count; i++)
{
WRoom room = mapRooms.Find(x => x.RoomIndex == i);
if (room != null)
room.EnvironmentLighting = envrData[i];
}
}
}
private List<EnvironmentLighting> GetLightingData()
{
List<EnvironmentLighting> lights = new List<EnvironmentLighting>();
List<LightingTimePreset> times = new List<LightingTimePreset>();
List<LightingPalette> palettes = new List<LightingPalette>();
List<LightingSkyboxColors> skyboxes = new List<LightingSkyboxColors>();
if (!m_fourCCGroups.ContainsKey(FourCC.EnvR) ||
!m_fourCCGroups.ContainsKey(FourCC.Colo) ||
!m_fourCCGroups.ContainsKey(FourCC.Virt) ||
!m_fourCCGroups.ContainsKey(FourCC.Pale))
return lights;
foreach (var virt in m_fourCCGroups[FourCC.Virt].Children)
{
EnvironmentLightingSkyboxColors skybox = (EnvironmentLightingSkyboxColors)virt;
LightingSkyboxColors skycolors = new LightingSkyboxColors(skybox);
skyboxes.Add(skycolors);
}
foreach (var pale in m_fourCCGroups[FourCC.Pale].Children)
{
EnvironmentLightingColors colors = (EnvironmentLightingColors)pale;
LightingPalette palette = new LightingPalette(colors);
if (colors.SkyboxColorIndex < skyboxes.Count)
palette.Skybox = skyboxes[colors.SkyboxColorIndex];
else
palette.Skybox = new LightingSkyboxColors();
palettes.Add(palette);
}
foreach (var colo in m_fourCCGroups[FourCC.Colo].Children)
{
EnvironmentLightingTimesOfDay daytimes = (EnvironmentLightingTimesOfDay)colo;
LightingTimePreset preset = new LightingTimePreset();
preset.TimePresetA[0] = palettes[daytimes.DawnA];
preset.TimePresetA[1] = palettes[daytimes.MorningA];
preset.TimePresetA[2] = palettes[daytimes.NoonA];
preset.TimePresetA[3] = palettes[daytimes.AfternoonA];
preset.TimePresetA[4] = palettes[daytimes.DuskA];
preset.TimePresetA[5] = palettes[daytimes.NightA];
preset.TimePresetB[0] = palettes[0];//daytimes.DawnB];
preset.TimePresetB[1] = palettes[0]; //palettes[daytimes.MorningB];
preset.TimePresetB[2] = palettes[0]; //palettes[daytimes.NoonB];
preset.TimePresetB[3] = palettes[0]; //palettes[daytimes.AfternoonB];
preset.TimePresetB[4] = palettes[0]; //palettes[daytimes.DuskB];
preset.TimePresetB[5] = palettes[0]; //palettes[daytimes.NightB];
times.Add(preset);
}
foreach (var envr in m_fourCCGroups[FourCC.EnvR].Children)
{
EnvironmentLightingConditions condition = (EnvironmentLightingConditions)envr;
EnvironmentLighting env = new EnvironmentLighting();
env.WeatherA[0] = times[condition.ClearA];
env.WeatherA[1] = times[condition.RainingA < times.Count ? condition.RainingA : 0];
env.WeatherA[2] = times[condition.SnowingA];
env.WeatherA[3] = times[condition.UnknownA];
env.WeatherB[0] = times[condition.ClearB];
env.WeatherB[1] = times[condition.RainingB];
env.WeatherB[2] = times[condition.SnowingB];
env.WeatherB[3] = times[condition.UnknownB];
lights.Add(env);
}
return lights;
}
public override void SetTimeOfDay(float timeOfDay)
{
base.SetTimeOfDay(timeOfDay);
if (m_skybox == null)
return;
WRoom first_room = null;
foreach (var node in m_world.Map.SceneList)
{
if (node is WRoom)
{
first_room = (WRoom)node;
break;
}
}
if (first_room == null || first_room.EnvironmentLighting == null)
return;
var envrData = GetLightingData();
var curLight = envrData[0].Lerp(EnvironmentLighting.WeatherPreset.Default, true, timeOfDay);
m_skybox.SetColors(curLight.Skybox);
}
public override void SaveEntitiesToDirectory(string directory)
{
string dzsDirectory = string.Format("{0}/dzs", directory);
if (!Directory.Exists(dzsDirectory))
Directory.CreateDirectory(dzsDirectory);
string filePath = string.Format("{0}/stage.dzs", dzsDirectory);
using (EndianBinaryWriter writer = new EndianBinaryWriter(File.Open(filePath, FileMode.Create), Endian.Big))
{
SceneDataExporter exporter = new SceneDataExporter();
exporter.ExportToStream(writer, this);
}
}
public override string ToString()
{
return Name;
}
}
}
|
using Microsoft.AspNet.Identity;
using System;
using System.Linq;
using System.Web.UI;
using WebSite;
using System.Web.Services;
using System.Collections.Generic;
using Newtonsoft.Json;
public partial class Account_Register : Page
{
[WebMethod]
public static string Nick(string NickName)
{
var db = new Entidades();
var consulta = db.AspNetUsers.Where(s => s.UserName == NickName);
List<string> result_nick = new List<string>();
foreach (AspNetUsers Nick in consulta)
{
result_nick.Add(Nick.UserName);
}
String json = JsonConvert.SerializeObject(result_nick);
return json;
}
[WebMethod]
public static string Email(string Mail)
{
var db = new Entidades();
var consulta = db.AspNetUsers.Where(s => s.Email == Mail);
List<string> result_email = new List<string>();
foreach (AspNetUsers Email in consulta)
{
result_email.Add(Email.Email);
}
String json = JsonConvert.SerializeObject(result_email);
return json;
}
[WebMethod]
public static string Registro(string NickS, string nameS, string AppPaternS, string AppMaterS, string InstitucS, string countrS, string passwoS, string phoS, string emaiS)
{
Boolean correcto = false;
System.Collections.ArrayList veredicto = new System.Collections.ArrayList();
var manager = new UserManager();
var user = new ApplicationUser() { UserName = NickS };
IdentityResult result = manager.Create(user, passwoS);
try
{
var db = new Entidades();
var reg = db.AspNetUsers.FirstOrDefault(x => x.UserName == NickS);
reg.Name = nameS;
reg.Apellido_Pat = AppPaternS;
reg.Apellido_Mat = AppMaterS;
reg.Institucion = InstitucS;
reg.Pais = countrS;
reg.PhoneNumber = phoS;
reg.Email = emaiS;
db.SaveChanges();
correcto = true;
}
catch(Exception e)
{
correcto = false;
}
if (result.Succeeded && correcto)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
veredicto.Add("SI");
}
else
{
veredicto.Add("NO");
}
String json =JsonConvert.SerializeObject(veredicto);
return json;
}
} |
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using TriangleCollector.Models.Interfaces;
using TriangleCollector.Services;
namespace TriangleCollector.Models.Exchanges.Binance
{
public class BinanceExchange : IExchange
{
public string ExchangeName { get; }
public IExchangeClient ExchangeClient { get; } = new BinanceClient();
public List<IClientWebSocket> ActiveClients { get; } = new List<IClientWebSocket>();
public List<IClientWebSocket> InactiveClients { get; } = new List<IClientWebSocket>();
public Type OrderbookType { get; } = typeof(BinanceOrderbook);
public HashSet<IOrderbook> TradedMarkets { get; set; } = new HashSet<IOrderbook>();
public ConcurrentDictionary<string, IOrderbook> OfficialOrderbooks { get; } = new ConcurrentDictionary<string, IOrderbook>();
public ConcurrentQueue<Triangle> TrianglesToRecalculate { get; set; } = new ConcurrentQueue<Triangle>();
public ConcurrentDictionary<string, Triangle> Triangles { get; } = new ConcurrentDictionary<string, Triangle>();
public HashSet<string> TriarbEligibleMarkets { get; set; } = new HashSet<string>();
public ConcurrentDictionary<string, IOrderbook> SubscribedMarkets { get; set; } = new ConcurrentDictionary<string, IOrderbook>();
public bool QueuedSubscription { get; set; } = false;
public bool AggregateStreamOpen { get; set; } = false;
public ConcurrentQueue<IOrderbook> SubscriptionQueue { get; set; } = new ConcurrentQueue<IOrderbook>();
public ConcurrentDictionary<string, List<Triangle>> TriangleTemplates { get; } = new ConcurrentDictionary<string, List<Triangle>>();
public int UniqueTriangleCount { get; set; } = 0;
public ConcurrentQueue<(bool, string)> OrderbookUpdateQueue { get; } = new ConcurrentQueue<(bool, string)>();
public ConcurrentDictionary<string, int> OrderbookUpdateStats { get; set; } = new ConcurrentDictionary<string, int>();
public ConcurrentDictionary<string, DateTime> ProfitableSymbolMapping { get; } = new ConcurrentDictionary<string, DateTime>();
public ConcurrentDictionary<string, DateTime> TriangleRefreshTimes { get; } = new ConcurrentDictionary<string, DateTime>();
public ConcurrentQueue<Triangle> RecalculatedTriangles { get; } = new ConcurrentQueue<Triangle>();
public int TriangleCount { get; set; }
private readonly ILoggerFactory _factory = new NullLoggerFactory();
public decimal TotalUSDValueProfitableTriangles { get; set; }
public decimal TotalUSDValueViableTriangles { get; set; }
public decimal EstimatedViableProfit { get; set; }
public BinanceExchange(string name)
{
ExchangeName = name;
ExchangeClient.Exchange = this;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassicCraft
{
class DeathWishBuff : Effect
{
public static int LENGTH = 30;
public DeathWishBuff(Player p)
: base(p, p, true, LENGTH, 1)
{
}
public override void StartBuff()
{
base.StartBuff();
Player.DamageMod *= 1.2;
}
public override void EndBuff()
{
base.EndBuff();
Player.DamageMod /= 1.2;
}
public override string ToString()
{
return "Death Wish's Buff";
}
}
}
|
namespace DFC.ServiceTaxonomy.GraphSync.Enums
{
public enum DisabledStatus
{
Disabled,
AlreadyDisabled,
ReEnabledDuringQuiesce
}
}
|
namespace RRExpress.AppCommon {
public enum SettingCatlogs {
Global
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Abhs.Common
{
public class ValidateTools
{
/// <summary>
/// 校验时间格式 HH:mm
/// </summary>
/// <param name="StrSource"></param>
/// <returns></returns>
public static bool IsTime(string StrSource)
{
if (StrSource.Length != 5)
return false;
return Regex.IsMatch(StrSource, @"^((20|21|22|23|[0-1]?\d):[0-5]?\d)$");
}
/// <summary>
/// 是否为时间型字符串
/// </summary>
/// <param name="source">时间字符串(15:00:00)</param>
/// <returns></returns>
public static bool IsTimes(string StrSource)
{
if (StrSource.Length != 8)
return false;
return Regex.IsMatch(StrSource, @"^((20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TraoDoiDoCu.BusinessLayer;
using TraoDoiDoCu.Models.Account;
namespace TraoDoiDoCu.Controllers.Account
{
public class AccountController : Controller
{
AccountBUS bus = new AccountBUS();
//
// GET: /Account/login
public ActionResult Login()
{
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
return RedirectToAction("Index", "Home");
return View("Login");
}
//
// POST: /Account/login
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
if (bus.LoginIsValid(model.UserName,model.Password))
{
if(!bus.IsActiveAccount(model.UserName))
{
ModelState.AddModelError("", "Tài khoản chưa được kích hoạt");
}
else
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Sai tên tài khoản hoặc mật khẩu");
}
}
return View(model);
}
//
// GET: /Account/logout
public ActionResult Logout()
{
if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
return RedirectToAction("Index", "Home");
FormsAuthentication.SignOut();
return View("Logout");
}
//
// GET: /Account/register
public ActionResult Register()
{
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
return RedirectToAction("Index", "Home");
return View("Register");
}
//
// Post: /Account/register
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
if (bus.CheckExistenceAccount(model.Email, model.UserName))
{
if (bus.AddAccount(model))
{
ViewBag.Message = "Tài khoản đã được ghi nhận trong hệ thống. Xin vui lòng kiểm tra email để kích hoạt tài khoản.";
return View("Result");
}
else
{
ViewBag.Alert = "Chúng tôi không thể gửi email kích hoạt đến email của bạn. Xin lỗi vì sự bất tiện này.";
return View("Result");
}
}
else
{
ViewBag.Message = "Tài khoản đã tồn tại trong hệ thống.";
return View("Register");
}
}
return View(model);
}
// GET: /Account/Activate
[HttpGet]
public ActionResult Activate(string Username, string ActivationCode)
{
bool res = bus.ActivateAccount(Username, ActivationCode);
ViewBag.Title = "Kết quả kích hoạt tài khoản";
if (res)
{
ViewBag.Message = "Kích hoạt tài khoản thành công. Bạn có thể đăng nhập tài khoản ngay bây giờ.";
return View("Result");
}
else
{
ViewBag.Alert = "Kích hoạt tài khoản thất bại. Xin liên lạc với ban quản trị để biết thêm chi tiết.";
return View("Result");
}
}
// GET: /Account/ForgotPassword
public ActionResult ForgotPassword()
{
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
return RedirectToAction("Index", "Home");
return View("ForgotPassword");
}
// POST: /Account/ForgotPassword
[HttpPost]
public ActionResult ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
if (bus.CheckMailExistence(model.Email))
{
ViewBag.Title = "Kết quả lấy lại mật khẩu";
if (bus.SetUpResetPassword(model.Email))
{
ViewBag.Message = "Xin vui lòng kiểm tra email để đổi lại mật khẩu.";
return View("Result");
}
else
{
ViewBag.Alert = "Chúng tôi không thể gửi mail lấy lại mật khẩu đến email của bạn. Chúng tôi xin lỗi về sự bất tiện này.";
return View("Result");
}
}
else
{
ViewBag.Alert = "Email không tồn tại.";
return View("ForgotPassword");
}
}
return View(model);
}
// GET: /Account/ResetPassword
[HttpGet]
public ActionResult ResetPassword(string Email, string ResetCode)
{
if (bus.ChekcResetPassword(Email, ResetCode))
{
return View("ResetPassword");
}
else
{
ViewBag.Title = "Kết quả đổi mật khẩu";
ViewBag.Message = "Link đổi mật khẩu đã quá hạn.";
return View("Result");
}
}
// POST: /Account/ResetPassword
[HttpPost]
public ActionResult ResetPassword(ResetPasswordViewModel resetPassVM)
{
if (ModelState.IsValid)
{
ViewBag.Title = "Kết reset mật khẩu";
if (bus.ChangePassword(resetPassVM))
{
ViewBag.Message = "Đổi khẩu thành công.";
return View("Result");
}
else
{
ViewBag.Message = "Đổi mật khẩu thất bại.";
return View("Result");
}
}
return View(resetPassVM);
}
}
} |
namespace BlazorShared.Models.Patient
{
public class UpdatePatientRequest : BaseRequest
{
public int ClientId { get; set; }
public int PatientId { get; set; }
public string Name { get; set; }
}
}
|
using GameToolkit.Localization;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class Save : MonoBehaviour {
[HideInInspector]
public static Save instance;
public AudioMixer audioMixer;
private void Awake()
{
if (instance == null)
instance = this;
else
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
public void SaveGame()
{
PlayerPrefs.SetInt("level", StoryManager.instance.GetLevel());
}
public void LoadGame()
{
int level = PlayerPrefs.GetInt("level");
if (level != 0)
{
StoryManager.instance.SetLevel(level);
LevelChangerScript.instance.FadeToLevel(StoryManager.instance.GetIndexOfTownInStory());
}
else
{
LevelChangerScript.instance.FadeToLevel(2);
}
}
public void SaveVolume(float volume)
{
PlayerPrefs.SetFloat("volume", volume);
}
public void SaveFullScreen(bool fullScreen)
{
PlayerPrefs.SetString("fullScreen", fullScreen.ToString());
}
public void SaveLanguage(int language)
{
PlayerPrefs.SetInt("language", language);
}
public void LoadOptions()
{
string fullString = PlayerPrefs.GetString("fullScreen");
if (fullString != "")
{
bool isFullScreen = bool.Parse(fullString);
Debug.Log("Full screen " + isFullScreen);
Screen.fullScreen = isFullScreen;
}
if (PlayerPrefs.GetFloat("volume") != -80)
{
audioMixer.SetFloat("masterVolume", PlayerPrefs.GetFloat("volume"));
}
Debug.Log("langue " + PlayerPrefs.GetInt("language"));
if (PlayerPrefs.GetInt("language") == 0)
{
Localization.Instance.CurrentLanguage = SystemLanguage.English;
}
else if (PlayerPrefs.GetInt("language") == 1)
{
Localization.Instance.CurrentLanguage = SystemLanguage.French;
}
}
}
|
using EmberKernel.Plugins.Components;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Reflection;
using System.Text;
using System.Web;
namespace BeatmapDownloader.Abstract.Services.DownloadProvider
{
public class HttpUtils : IDisposable
{
public HttpClient Requestor { get; }
public WebClient Downloader { get; }
public HttpUtils()
{
Requestor = new HttpClient();
var downloaderAssembly = typeof(HttpUtils).Assembly.GetName(false);
var emberKernelVersion = typeof(IComponent).Assembly.GetName(false);
var executeVersion = Assembly.GetEntryAssembly().GetName();
Requestor.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(downloaderAssembly.Name, downloaderAssembly.Version.ToString()));
Requestor.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(emberKernelVersion.Name, emberKernelVersion.Version.ToString()));
Requestor.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(executeVersion.Name, executeVersion.Version.ToString()));
Downloader = new WebClient();
Downloader.Headers.Add(HttpRequestHeader.UserAgent, Requestor.DefaultRequestHeaders.UserAgent.ToString());
Downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged;
}
public event Action<int, long, long> DownloadProgressChanged;
private void Downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
DownloadProgressChanged?.Invoke(e.ProgressPercentage, e.BytesReceived, e.TotalBytesToReceive);
}
public bool TryGetFileNameFromDownloader(out string fileName)
{
if (!string.IsNullOrEmpty(Downloader.ResponseHeaders["Content-Disposition"]))
{
string header_contentDisposition = Downloader.ResponseHeaders["content-disposition"];
var disposition = new ContentDisposition(header_contentDisposition);
if (disposition.FileName != null && disposition.FileName.Length > 0)
{
fileName = HttpUtility.UrlDecode(disposition.FileName);
return true;
}
}
fileName = null;
return false;
}
public void Dispose()
{
Requestor.Dispose();
Downloader.Dispose();
}
}
}
|
using gView.Framework.Carto;
using System;
/// <summary>
/// The <c>gView.Framework</c> provides all interfaces to develope
/// with and for gView
/// </summary>
namespace gView.Framework.system
{
public class CloneOptions
{
public CloneOptions(IDisplay display,
bool applyRefScale,
float maxRefScaleFactor = 0f,
float maxLabelRefscaleFactor = 0f)
{
this.Display = display;
this.ApplyRefScale = applyRefScale;
this.DpiFactor = display == null || display.dpi == 96D ?
1f :
(float)System.Math.Pow(display.dpi / 96.0, 1.0);
this.MaxRefScaleFactor = maxRefScaleFactor <= float.Epsilon ? float.MaxValue : maxRefScaleFactor;
this.MaxLabelRefScaleFactor = maxLabelRefscaleFactor <= float.Epsilon ? float.MaxValue : maxLabelRefscaleFactor;
}
public IDisplay Display { get; private set; }
public float MaxRefScaleFactor { get; private set; }
public float MaxLabelRefScaleFactor { get; private set; }
public float DpiFactor { get; private set; }
public bool ApplyRefScale { get; private set; }
public float RefScaleFactor(float factor)
{
return Math.Min(factor, this.MaxRefScaleFactor);
}
public float LabelRefScaleFactor(float factor)
{
return Math.Min(factor, this.MaxLabelRefScaleFactor);
}
}
}
|
using UnityEngine;
using UnityEditor;
using Ardunity;
[CustomEditor(typeof(DialSliderReactor))]
public class DialSliderReactorEditor : ArdunityObjectEditor
{
SerializedProperty script;
SerializedProperty invert;
void OnEnable()
{
script = serializedObject.FindProperty("m_Script");
invert = serializedObject.FindProperty("invert");
}
public override void OnInspectorGUI()
{
this.serializedObject.Update();
//DialSliderReactor reactor = (DialSliderReactor)target;
GUI.enabled = false;
EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]);
GUI.enabled = true;
EditorGUILayout.PropertyField(invert, new GUIContent("Invert"));
this.serializedObject.ApplyModifiedProperties();
}
static public void AddMenuItem(GenericMenu menu, GenericMenu.MenuFunction2 func)
{
string menuName = "Unity/Add Reactor/UI/DialSliderReactor";
if(Selection.activeGameObject != null && Selection.activeGameObject.GetComponent<DialSlider>() != null)
menu.AddItem(new GUIContent(menuName), false, func, typeof(DialSliderReactor));
else
menu.AddDisabledItem(new GUIContent(menuName));
}
} |
// Copyright 2013-2015 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Serilog.Configuration;
/// <summary>
/// Controls template parameter destructuring configuration.
/// </summary>
public class LoggerDestructuringConfiguration
{
readonly LoggerConfiguration _loggerConfiguration;
readonly Action<Type> _addScalar;
readonly Action<Type> _addDictionaryType;
readonly Action<IDestructuringPolicy> _addPolicy;
readonly Action<int> _setMaximumDepth;
readonly Action<int> _setMaximumStringLength;
readonly Action<int> _setMaximumCollectionCount;
internal LoggerDestructuringConfiguration(
LoggerConfiguration loggerConfiguration,
Action<Type> addScalar,
Action<Type> addDictionaryType,
Action<IDestructuringPolicy> addPolicy,
Action<int> setMaximumDepth,
Action<int> setMaximumStringLength,
Action<int> setMaximumCollectionCount)
{
_loggerConfiguration = Guard.AgainstNull(loggerConfiguration);
_addScalar = Guard.AgainstNull(addScalar);
_addDictionaryType = Guard.AgainstNull(addDictionaryType);
_addPolicy = Guard.AgainstNull(addPolicy);
_setMaximumDepth = Guard.AgainstNull(setMaximumDepth);
_setMaximumStringLength = Guard.AgainstNull(setMaximumStringLength);
_setMaximumCollectionCount = Guard.AgainstNull(setMaximumCollectionCount);
}
/// <summary>
/// Treat objects of the specified type as scalar values, i.e., don't break
/// them down into properties even when destructuring complex types.
/// </summary>
/// <param name="scalarType">Type to treat as scalar.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="scalarType"/> is <code>null</code></exception>
public LoggerConfiguration AsScalar(Type scalarType)
{
Guard.AgainstNull(scalarType);
_addScalar(scalarType);
return _loggerConfiguration;
}
/// <summary>
/// Treat objects of the specified type as scalar values, i.e., don't break
/// them down into properties even when destructuring complex types.
/// </summary>
/// <typeparam name="TScalar">Type to treat as scalar.</typeparam>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration AsScalar<TScalar>() => AsScalar(typeof(TScalar));
/// <summary>
/// When destructuring objects, transform instances with the provided policies.
/// </summary>
/// <param name="destructuringPolicies">Policies to apply when destructuring.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="destructuringPolicies"/> is <code>null</code></exception>
/// <exception cref="ArgumentException">When any element of <paramref name="destructuringPolicies"/> is <code>null</code></exception>
// ReSharper disable once MemberCanBePrivate.Global
public LoggerConfiguration With(params IDestructuringPolicy[] destructuringPolicies)
{
Guard.AgainstNull(destructuringPolicies);
foreach (var destructuringPolicy in destructuringPolicies)
{
if (destructuringPolicy == null) throw new ArgumentException("Null policy is not allowed.");
_addPolicy(destructuringPolicy);
}
return _loggerConfiguration;
}
/// <summary>
/// When destructuring objects, transform instances with the provided policy.
/// </summary>
/// <typeparam name="TDestructuringPolicy">Policy to apply when destructuring.</typeparam>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration With<TDestructuringPolicy>()
where TDestructuringPolicy : IDestructuringPolicy, new()
{
return With(new TDestructuringPolicy());
}
/// <summary>
/// Capture instances of the specified type as dictionaries.
/// By default, only concrete instantiations of are considered dictionary-like.
/// </summary>
/// <typeparam name="T">Type of dictionary.</typeparam>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration AsDictionary<T>()
where T : IDictionary
{
_addDictionaryType(typeof(T));
return _loggerConfiguration;
}
/// <summary>
/// When destructuring objects, transform instances of the specified type with
/// the provided function.
/// </summary>
/// <param name="transformation">Function mapping instances of <typeparamref name="TValue"/>
/// to an alternative representation.</param>
/// <typeparam name="TValue">Type of values to transform.</typeparam>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="transformation"/> is <code>null</code></exception>
public LoggerConfiguration ByTransforming<TValue>(Func<TValue, object> transformation)
{
Guard.AgainstNull(transformation);
var policy = new ProjectedDestructuringPolicy(t => t == typeof(TValue),
o => transformation((TValue)o));
return With(policy);
}
/// <summary>
/// When destructuring objects, transform instances of the specified type with
/// the provided function, if the predicate returns true. Be careful to avoid any
/// intensive work in the predicate, as it can slow down the pipeline significantly.
/// </summary>
/// <param name="predicate">A predicate used to determine if the transform applies to
/// a specific type of value</param>
/// <param name="transformation">Function mapping instances of <typeparamref name="TValue"/>
/// to an alternative representation.</param>
/// <typeparam name="TValue">Type of values to transform.</typeparam>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="predicate"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="transformation"/> is <code>null</code></exception>
public LoggerConfiguration ByTransformingWhere<TValue>(
Func<Type, bool> predicate,
Func<TValue, object> transformation)
{
Guard.AgainstNull(predicate);
Guard.AgainstNull(transformation);
var policy = new ProjectedDestructuringPolicy(predicate,
o => transformation((TValue)o));
return With(policy);
}
/// <summary>
/// When destructuring objects, depth will be limited to 10 property traversals deep to
/// guard against ballooning space when recursive/cyclic structures are accidentally passed. To
/// change this limit pass a new maximum depth.
/// </summary>
/// <param name="maximumDestructuringDepth">The maximum depth to use.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentOutOfRangeException">When <paramref name="maximumDestructuringDepth"/> is negative</exception>
public LoggerConfiguration ToMaximumDepth(int maximumDestructuringDepth)
{
if (maximumDestructuringDepth < 0) throw new ArgumentOutOfRangeException(nameof(maximumDestructuringDepth), "Maximum destructuring depth must be positive.");
_setMaximumDepth(maximumDestructuringDepth);
return _loggerConfiguration;
}
/// <summary>
/// When destructuring objects, string values can be restricted to specified length
/// thus avoiding bloating payload. Limit is applied to each value separately,
/// sum of length of strings can exceed limit.
/// </summary>
/// <param name="maximumStringLength">The maximum string length.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentOutOfRangeException">When <paramref name="maximumStringLength"/> is less than 2</exception>
public LoggerConfiguration ToMaximumStringLength(int maximumStringLength)
{
if (maximumStringLength < 2) throw new ArgumentOutOfRangeException(nameof(maximumStringLength), maximumStringLength, "Maximum string length must be at least two.");
_setMaximumStringLength(maximumStringLength);
return _loggerConfiguration;
}
/// <summary>
/// When destructuring objects, collections be restricted to specified count
/// thus avoiding bloating payload. Limit is applied to each collection separately,
/// sum of length of collection can exceed limit.
/// Applies limit to all <see cref="IEnumerable"/> including dictionaries.
/// </summary>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentOutOfRangeException">When <paramref name="maximumCollectionCount"/> is less than 1</exception>
public LoggerConfiguration ToMaximumCollectionCount(int maximumCollectionCount)
{
if (maximumCollectionCount < 1) throw new ArgumentOutOfRangeException(nameof(maximumCollectionCount), maximumCollectionCount, "Maximum collection length must be at least one.");
_setMaximumCollectionCount(maximumCollectionCount);
return _loggerConfiguration;
}
}
|
exec("./Profiles.cs");
exec("./AchGUI.gui");
if(!$Ach::Loaded) {
$Ach::Gui::X = 10;
$Ach::Gui::Y["General"] = 0;
$Ach::Gui::Y["Deathmatch"] = 0;
$Ach::Gui::Y["Building"] = 0;
$Ach::Gui::Y["Special"] = 0;
$Ach::Gui::Y["Unsorted"] = 0;
$Ach::Loaded = true;
$remapDivision[$remapCount] = "Achievements";
$remapName[$remapCount] = "Open Achievements";
$remapCmd[$remapCount] = "openAchGUI";
$remapCount++;
}
AchGeneralh.visible = true;
AchDeathmatchh.visible = false;
AchBuildingh.visible = false;
AchSpecialh.visible = false;
AchUnsortedh.visible = false;
Achievements_Box_General.visible = true;
Achievements_Box_Building.visible = false;
Achievements_Box_Deathmatch.visible = false;
Achievements_Box_Special.visible = false;
Achievements_Box_Unsorted.visible = false;
$Ach::GUI::LastOpen = "General";
function openAchGUI()
{
if(!$Ach::GUI::Open) {
canvas.pushDialog(AchGUI);
$Ach::GUI::Open = true;
} else {
canvas.popDialog(AchGUI);
$Ach::GUI::Open = false;
}
}
function clientCmdAddAch(%bitmapImage, %name, %text, %cat)
{
if(%name $= "" || %text $= "" || !$Ach::Loaded)
return;
if($Ach::Gui::Y[%cat] $= "" || %cat $= "")
%cat = "Unsorted";
if(!isFile($Ach::Icons[%bitmapImage]))
%bitmapImage = "Add-Ons/Script_achievements/images/unknown.png";
$Ach::Bitmap::Locked[%name] = new GuiSwatchCtrl() {
profile = "GuiDefaultProfile";
horizSizing = "right";
vertSizing = "bottom";
position = $Ach::Gui::X SPC $Ach::Gui::Y[%cat];
extent = "737 74";
minExtent = "8 2";
enabled = "1";
visible = "1";
clipToParent = "1";
color = "255 255 255 110";
new GuiBitmapCtrl() {
profile = "GuiDefaultProfile";
horizSizing = "right";
vertSizing = "bottom";
position = "5 5";
extent = "64 64";
minExtent = "8 2";
enabled = "1";
visible = "1";
clipToParent = "1";
bitmap = $Ach::Icons[%bitmapImage];
wrap = "0";
lockAspectRatio = "0";
alignLeft = "0";
overflowImage = "0";
keepCached = "0";
mColor = "255 255 255 255";
mMultiply = "0";
};
new GuiMLTextCtrl() {
profile = "GuiMLTextProfile";
horizSizing = "right";
vertSizing = "bottom";
position = "77 3";
extent = "670 20";
minExtent = "8 2";
enabled = "1";
visible = "1";
clipToParent = "1";
lineSpacing = "2";
allowColorChars = "0";
maxChars = "-1";
maxBitmapHeight = "-1";
selectable = "1";
text = %name;
};
new GuiMLTextCtrl() {
profile = "GuiMLTextProfile";
horizSizing = "right";
vertSizing = "bottom";
position = "93 27";
extent = "654 39";
minExtent = "8 2";
enabled = "1";
visible = "1";
clipToParent = "1";
lineSpacing = "2";
allowColorChars = "0";
maxChars = "-1";
maxBitmapHeight = "-1";
selectable = "1";
text = %text;
};
};
eval("Achievements_Box_"@%cat@".add("@$Ach::Bitmap::Locked[%name]@");");
$Ach::Bitmap::Unlocked[%name] = new GuiSwatchCtrl() {
profile = "GuiDefaultProfile";
horizSizing = "right";
vertSizing = "bottom";
position = "0 0";
extent = "737 74";
minExtent = "8 2";
visible = "1";
color = "255 255 255 110";
};
$Ach::Bitmap::Locked[%name].add($Ach::Bitmap::Unlocked[%name]);
$Ach::Gui::Y[%cat] = $Ach::Gui::Y[%cat] + 78;
eval("Achievements_Box_"@%cat@".resize(1, 1, 737,"@$Ach::Gui::Y[%cat]@");");
}
function registerAchievementIcon(%path, %name)
{
if(%name $= "" || $Ach::Icons[%name] !$= "")
return;
if(!isFile(%path))
%path = "Add-Ons/Script_achievements/images/unknown.png";
$Ach::Icons[%name] = %path;
}
function clientCmdRegisterAchievementIcon(%path, %name)
{
if(%name $= "" || $Ach::Icons[%name] !$= "")
return;
if(!isFile(%path))
%path = "Add-Ons/Script_achievements/images/unknown.png";
$Ach::Icons[%name] = %path;
}
function clientCmdUnlockAch(%name)
{
if(%name $= "")
return;
// Now check it, because it was returning weird errors before.
if(isObject($Ach::Bitmap::Unlocked[%name]))
$Ach::Bitmap::Unlocked[%name].delete();
}
function AchGUI::CatClick(%this, %Cat)
{
eval("Ach"@$Ach::GUI::LastOpen@"h.visible=false;Achievements_Box_"@$Ach::GUI::LastOpen@".visible=false;");
eval("Ach"@%Cat@"h.visible=true;Achievements_Box_"@%Cat@".visible=true;");
$Ach::GUI::LastOpen = %Cat;
}
function clientCmdclearAch()
{
Achievements_Box_General.clear();
Achievements_Box_Building.clear();
Achievements_Box_Deathmatch.clear();
Achievements_Box_Special.clear();
Achievements_Box_Unsorted.clear();
$Ach::Gui::X = 10;
$Ach::Gui::Y["General"] = 0;
$Ach::Gui::Y["Deathmatch"] = 0;
$Ach::Gui::Y["Building"] = 0;
$Ach::Gui::Y["Special"] = 0;
$Ach::Gui::Y["Unsorted"] = 0;
}
function clientCmdIHaveAchievementsMod()
{
commandtoserver('IHaveAchievementsMod');
}
// Now register the icons.
registerAchievementIcon("Add-Ons/Script_achievements/images/....png", "...");
registerAchievementIcon("Add-Ons/Script_achievements/images/crap.png", "crap");
registerAchievementIcon("Add-Ons/Script_achievements/images/eye.png", "eye");
registerAchievementIcon("Add-Ons/Script_achievements/images/money_sign.png", "moneysign");
registerAchievementIcon("Add-Ons/Script_achievements/images/pedo.png", "pedo");
registerAchievementIcon("Add-Ons/Script_achievements/images/banana.png", "banana");
registerAchievementIcon("Add-Ons/Script_achievements/images/blablabla.png", "blablabla");
registerAchievementIcon("Add-Ons/Script_achievements/images/bsod.png", "bsod");
registerAchievementIcon("Add-Ons/Script_achievements/images/censored.png", "censored");
registerAchievementIcon("Add-Ons/Script_achievements/images/dice.png", "dice");
registerAchievementIcon("Add-Ons/Script_achievements/images/fail.png", "fail");
registerAchievementIcon("Add-Ons/Script_achievements/images/heart.png", "heart");
registerAchievementIcon("Add-Ons/Script_achievements/images/lol.png", "lol");
registerAchievementIcon("Add-Ons/Script_achievements/images/mac.png", "mac");
registerAchievementIcon("Add-Ons/Script_achievements/images/middlefinger.png", "middlefinger");
registerAchievementIcon("Add-Ons/Script_achievements/images/mouse.png", "mouse");
registerAchievementIcon("Add-Ons/Script_achievements/images/mw.png", "mw");
registerAchievementIcon("Add-Ons/Script_achievements/images/number1.png", "number1");
registerAchievementIcon("Add-Ons/Script_achievements/images/pa.png", "pa");
registerAchievementIcon("Add-Ons/Script_achievements/images/pacman.png", "pacman");
registerAchievementIcon("Add-Ons/Script_achievements/images/pwned.png", "pwned");
registerAchievementIcon("Add-Ons/Script_achievements/images/stop.png", "stop");
registerAchievementIcon("Add-Ons/Script_achievements/images/target.png", "target");
registerAchievementIcon("Add-Ons/Script_achievements/images/trans.png", "trans");
registerAchievementIcon("Add-Ons/Script_achievements/images/trash.png", "trash");
registerAchievementIcon("Add-Ons/Script_achievements/images/unknown.png", "unknown");
registerAchievementIcon("Add-Ons/Script_achievements/images/void.png", "void");
registerAchievementIcon("Add-Ons/Script_achievements/images/weirdface.png", "weirdface");
registerAchievementIcon("Add-Ons/Script_achievements/images/hugger.png", "hugger");
registerAchievementIcon("Add-Ons/Script_achievements/images/GunSpam.png", "gunspam");
registerAchievementIcon("Add-Ons/Script_achievements/images/windows.png", "windows");
registerAchievementIcon("Add-Ons/Script_achievements/images/nuke.png", "nuke");
registerAchievementIcon("Add-Ons/Script_achievements/images/health.png", "health");
registerAchievementIcon("Add-Ons/Script_achievements/images/blockland.png", "blockland");
registerAchievementIcon("Add-Ons/Script_achievements/images/lego.png", "lego");
registerAchievementIcon("Add-Ons/Script_achievements/images/arrows.png", "arrows");
// User based packs.
registerAchievementIcon("Add-Ons/Script_achievements/images/Regulith/eventer.png", "eventer");
registerAchievementIcon("Add-Ons/Script_achievements/images/Regulith/hammer.png", "hammer"); |
using CPClient.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace CPClient.Data.Interfaces
{
public interface IRepositoryWrapper
{
IRedeSocialTipoRepository RedeSocialTipo { get; }
ITelefoneTipoRepository TelefoneTipo { get; }
IClienteRepository Cliente { get; }
IEnderecoTipoRepository EnderecoTipo { get; }
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Senparc.Areas.Admin.Models.VD;
using Senparc.CO2NET.Extensions;
using Senparc.Core.Enums;
using Senparc.Core.Models;
using Senparc.Core.Models.DataBaseModel;
using Senparc.Mvc.Filter;
using Senparc.Office;
using Senparc.Service;
using Senparc.Utility;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Senparc.Areas.Admin.Controllers
{
[MenuFilter("Activity")]
public class ActivityController : BaseAdminController
{
private readonly AccountService _accountService;
// private readonly SenparcEntities _senparcEntities;
private readonly ActivityService _activityService;
public ActivityController(AccountService accountService
// , SenparcEntities senparcEntities
, ActivityService activityService
)
{
_accountService = accountService;
// _senparcEntities = senparcEntities;
_activityService = activityService;
}
public ActionResult Index(string kw = null, int pageIndex = 1)
{
//var seh = new SenparcExpressionHelper<Account>();
//seh.ValueCompare.AndAlso(true, z => !z.Flag)
// .AndAlso(!kw.IsNullOrEmpty(), z => z.RealName.Contains(kw) || z.NickName.Contains(kw) || z.UserName.Contains(kw) || z.Phone.Contains(kw));
//var where = seh.BuildWhereExpression();
//var modelList = _accountService.GetObjectList(pageIndex, 20, where, z => z.Id, OrderingType.Descending);
//var vd = new Account_IndexVD()
//{
// AccountList = modelList,
// kw = kw
//};
var seh = new SenparcExpressionHelper<Activity>();
seh.ValueCompare.AndAlso(true, z => !z.Flag)
.AndAlso(!kw.IsNullOrEmpty(), z => z.Title.Contains(kw) || z.Content.Contains(kw) || z.Description.Contains(kw));
var where = seh.BuildWhereExpression();
var modelList = _activityService.GetObjectList(pageIndex, 20, where, z => z.Id, OrderingType.Descending);
var vd = new Activity_IndexVD()
{
ActivityList = modelList,
kw = kw
};
return View(vd);
}
public ActionResult Create()
{
return View();
}
public ActionResult Edit(string id)
{
bool isEdit = !string.IsNullOrEmpty(id);
var vd = new Activity_EditVD();
if (isEdit)
{
var model = _activityService.GetObject(z => z.Id == id);
if (model == null)
{
return RenderError("信息不存在!");
}
vd.Id = model.Id;
vd.CoverUrl = model.CoverUrl;
vd.Content = model.Content;
vd.Description = model.Description;
vd.Summary = model.Summary;
vd.IsPublish = model.IsPublish;
vd.Title = model.Title;
vd.ScheduleStatus = model.ScheduleStatus;
//vd.Note = model.Note;
}
vd.IsEdit = isEdit;
return View(vd);
}
[HttpPost]
public async Task<IActionResult> Edit(Activity_EditVD model)
{
bool isEdit =!string.IsNullOrEmpty(model.Id);
if (!ModelState.IsValid)
{
return View(model);
}
Activity account = null;
if (isEdit)
{
account = _activityService.GetObject(z => z.Id == model.Id);
if (account == null)
{
base.SetMessager(MessageType.danger, "信息不存在!");
return RedirectToAction("Index");
}
account.ScheduleStatus = model.ScheduleStatus;
account.Content = model.Content ?? "";
account.CoverUrl = model.CoverUrl ?? "";
account.Description = model.Description ?? "";
account.IsPublish = true;
account.Summary = model.Summary ?? "";
account.Title = model.Title ?? "";
account.ScheduleStatus = model.ScheduleStatus;
}
else
{
account = new Activity()
{
Id = Guid.NewGuid().ToString("N"),
Content = model.Content ?? "",
CoverUrl = model.CoverUrl ?? "",
Description = model.Description ?? "",
Flag = false,
IsPublish = true,
IssueTime = DateTime.Now,
Summary = model.Summary??"",
Title = model.Title??"",
ScheduleStatus = model.ScheduleStatus
};
}
try
{
//if (_accountService.CheckPhoneExisted(account.Id, model.Phone))
//{
// ModelState.AddModelError("Phone", "手机号码重复");
// return View(model);
//}
// await this.TryUpdateModelAsync<Activity>(account, ""
//, z =>
//, z => z.Phone
//, z => z.Note);
await this.TryUpdateModelAsync(account, "",
v => v.Title,
v => v.Content,
v => v.Summary,
v => v.Flag,
v => v.IsPublish,
v => v.CoverUrl
);
this._activityService.SaveObject(account);
base.SetMessager(MessageType.success, $"{(isEdit ? "修改" : "新增")}成功!");
return RedirectToAction("Index");
}
catch (Exception)
{
base.SetMessager(MessageType.danger, $"{(isEdit ? "修改" : "新增")}失败!");
return RedirectToAction("Index");
}
}
[HttpPost]
public ActionResult Delete(List<string> ids)
{
try
{
var objList = _activityService.GetFullList(z => ids.Contains(z.Id), z => z.Id, OrderingType.Ascending);
_activityService.DeleteAll(objList);
SetMessager(MessageType.success, "删除成功!");
}
catch (Exception e)
{
SetMessager(MessageType.danger, $"删除失败【{e.Message}!");
}
return RedirectToAction("Index");
}
}
}
|
using Alabo.Data.People.Circles.Domain.Entities;
using Alabo.Extensions;
using Alabo.Framework.Basic.Regions.Domain.Services;
using Alabo.Framework.Core.Enums.Enum;
using Alabo.Helpers;
using Alabo.Tool.Payment;
using Alabo.Tool.Payment.MiniProgram.Clients;
using System;
using System.Collections.Generic;
using System.Linq;
using ZKCloud.Open.ApiBase.Connectors;
using ZKCloud.Open.ApiBase.Formatters;
namespace Alabo.Data.People.Circles.Client
{
/// <summary>
/// 商圈数据导入
/// https://github.com/kzgame/china_regions/blob/master/region_dumps.json
/// </summary>
public class CircleMapClient : ApiStoreClient
{
private static readonly Func<IConnector> ConnectorCreator = () => new HttpClientConnector();
private static readonly Func<IDataFormatter> FormmaterCreator = () => new JsonFormatter();
private static readonly Uri BaseUri = new Uri("http://ui.5ug.com");
/// <summary>
/// 秘钥
/// </summary>
private string _key = "7a0bfcba0cbd3490c8cbf1331a5e68c2";
/// <summary>
/// Initializes a new instance of the <see cref="MiniProgramClient" /> class.
/// </summary>
public CircleMapClient()
: base(BaseUri, ConnectorCreator(), FormmaterCreator())
{
}
public IList<CircleMapItem> GetCircleMap()
{
var baseUrl = "/static/json/circlemap.json";
var url = BuildQueryUri(baseUrl);
var result = Connector.Get(url);
var aMapDistrict = result.DeserializeJson<List<CircleMapItem>>();
return aMapDistrict;
}
/// <summary>
/// 获取商圈数据
/// </summary>
public IList<Circle> GetCircleList()
{
try
{
var baseUrl = "/static/json/circle.json";
var url = BuildQueryUri(baseUrl);
var result = Connector.Get(url);
var aMapDistrict = result.DeserializeJson<List<Circle>>();
return aMapDistrict;
}
catch
{
return new List<Circle>();
}
}
/// <summary>
/// 转换成商圈格式
/// 通过单元测试,保存json到服务上
/// </summary>
public IList<Circle> MapToCircle()
{
var provices = Ioc.Resolve<IRegionService>().GetList(r => r.Level == RegionLevel.Province);
var list = new List<Circle>();
var circelMaps = GetCircleMap();
foreach (var proviceItem in provices)
{
var proviceMap = circelMaps.FirstOrDefault(r =>
r.Name.Contains(proviceItem.Name.Replace("省", "").Replace("市", "").Replace("区", "")));
if (proviceMap == null) {
throw new SystemException();
}
// 城市
var cities = Ioc.Resolve<IRegionService>()
.GetList(r => r.Level == RegionLevel.City && r.ParentId == proviceItem.RegionId);
foreach (var cityItem in cities)
{
var cityMap = proviceMap.Cities.FirstOrDefault(r =>
r.Name.Contains(cityItem.Name.Replace("省", "").Replace("市", "").Replace("区", "")));
if (cityMap == null) {
continue;
}
var coutries = Ioc.Resolve<IRegionService>().GetList(r =>
r.Level == RegionLevel.County && r.ParentId == cityItem.RegionId);
foreach (var countyItem in coutries)
{
var coutryItem = cityMap.Counties.FirstOrDefault(r =>
r.Name.Contains(countyItem.Name.Replace("省", "").Replace("市", "").Replace("区", "")
.Replace("县", "")));
if (coutryItem != null) {
foreach (var circleItem in coutryItem.Circles) {
if (circleItem.Name != "其他")
{
var circle = new Circle
{
CityId = cityItem.RegionId,
Name = circleItem.Name,
CountyId = countyItem.RegionId,
ProvinceId = proviceItem.RegionId,
FullName = countyItem.FullName + circleItem.Name
};
list.Add(circle);
}
}
}
}
}
}
// 通过单元测试,保存json到服务上
var json = list.ToJson();
return list;
}
}
} |
using Sentry.Android.Extensions;
namespace Sentry.Android.Callbacks;
internal class BeforeSendCallback : JavaObject, JavaSdk.SentryOptions.IBeforeSendCallback
{
private readonly Func<SentryEvent, Hint, SentryEvent?> _beforeSend;
private readonly SentryOptions _options;
private readonly JavaSdk.SentryOptions _javaOptions;
public BeforeSendCallback(
Func<SentryEvent, Hint, SentryEvent?> beforeSend,
SentryOptions options,
JavaSdk.SentryOptions javaOptions)
{
_beforeSend = beforeSend;
_options = options;
_javaOptions = javaOptions;
}
public JavaSdk.SentryEvent? Execute(JavaSdk.SentryEvent e, JavaSdk.Hint h)
{
// Note: Hint is unused due to:
// https://github.com/getsentry/sentry-dotnet/issues/1469
var evnt = e.ToSentryEvent(_javaOptions);
var hint = h.ToHint();
var result = _beforeSend?.Invoke(evnt, hint);
return result?.ToJavaSentryEvent(_options, _javaOptions);
}
}
|
using ApartmentApps.Data;
using ApartmentApps.Data.Repository;
namespace ApartmentApps.Api.Modules
{
public abstract class DashboardComponent<TResultViewModel> : PortalComponent<TResultViewModel>
where TResultViewModel : ComponentViewModel
{
//public IKernel Kernel { get; }
public AnalyticsModule Analytics { get; set; }
public ApplicationDbContext Context { get; }
public IUserContext UserContext { get; }
public DashboardContext DashboardContext { get; set; }
public IRepository<TItem> Repo<TItem>() where TItem : class, IBaseEntity
{
return Analytics.Repo<TItem>(DashboardContext);
}
protected DashboardComponent(AnalyticsModule analytics, ApplicationDbContext dbContext, IUserContext userContext)
{
//Kernel = kernel;
Analytics = analytics;
Context = dbContext;
UserContext = userContext;
}
}
} |
using System;
using Microsoft.AspNetCore.Http;
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.CrossOriginPolicies.EmbedderPolicy
{
/// <summary>
/// The Cross Origin Embedder Policy directive builder base class
/// </summary>
public abstract class CrossOriginEmbedderPolicyDirectiveBuilderBase : CrossOriginPolicyDirectiveBuilderBase
{
/// <summary>
/// Initializes a new instance of the <see cref="CrossOriginEmbedderPolicyDirectiveBuilderBase"/> class.
/// </summary>
/// <param name="directive">The name of the directive</param>
protected CrossOriginEmbedderPolicyDirectiveBuilderBase(string directive) : base(directive)
{
}
/// <inheritdoc />
internal override abstract Func<HttpContext, string> CreateBuilder();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using DelftTools.Utils.Aop;
using log4net;
namespace DelftTools.TestUtils
{
public partial class WindowsFormsTestHelper : Form
{
private static Form synchronizationForm;
private static WindowsFormsTestHelper form;
private static ILog log = LogManager.GetLogger(typeof(WindowsFormsTestHelper));
private static Action<Form> formShown;
private static Exception exception;
static WindowsFormsTestHelper()
{
InitializeSynchronizatonObject();
AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
Application.ThreadException += Application_ThreadException;
}
private static void InitializeSynchronizatonObject()
{
if (synchronizationForm == null)
{
synchronizationForm = new Form { ShowInTaskbar = false, WindowState = FormWindowState.Minimized };
synchronizationForm.Show();
}
if (InvokeRequiredAttribute.SynchronizeObject != synchronizationForm)
{
InvokeRequiredAttribute.SynchronizeObject = synchronizationForm;
}
}
private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
exception = e.ExceptionObject as Exception;
if (exception != null)
{
log.Error("Exception occured: " + exception.Message, exception);
}
else
{
log.Error("Unhandled exception occured: " + e.ExceptionObject);
}
}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
exception = e.Exception;
log.Error("Windows.Forms exception occured: " + e.Exception.Message, e.Exception);
}
public WindowsFormsTestHelper()
{
Application.EnableVisualStyles();
SetStyle(
ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
InitializeComponent();
}
protected override void OnShown(EventArgs e)
{
InitializeSynchronizatonObject(); // it may happen that other form overrides it
}
public static void Show(Control control, Action<Form> formVisibleChangedAction, params object[] propertyObjects)
{
new WindowsFormsTestHelper().ShowControl(control, formVisibleChangedAction, propertyObjects);
}
public static void Show(Control control, params object[] propertyObjects)
{
new WindowsFormsTestHelper().ShowControl(control, propertyObjects);
}
public static void ShowModal(Control control, Action<Form> formVisibleChangedAction, params object[] propertyObjects)
{
new WindowsFormsTestHelper().ShowControlModal(control, formVisibleChangedAction, propertyObjects);
}
/// <summary>
/// Shows a control Modally by embedding it in a testform or calling .Show() for a toplevel control (Form).
/// </summary>
/// <param name="control"></param>
/// <param name="propertyObjects"></param>
public static void ShowModal(Control control, params object[] propertyObjects)
{
new WindowsFormsTestHelper().ShowControlModal(control, propertyObjects);
}
/// <summary>
/// Embeds the controls into one container control, and shows this control modally.
/// All controls will be using dockstyle top.
/// </summary>
/// <param name="controls">Controls to embed</param>
/// <param name="propertyObjects">Objects to show as property</param>
public static void ShowModal(IEnumerable<Control> controls, params object[] propertyObjects)
{
ShowModal(controls, true, propertyObjects);
}
/// <summary>
/// Embeds the controls into one container control, and shows this control modally.
/// All controls will be using dockstyle top, exect the last control (if useFillForLastControl is true).
/// </summary>
/// <param name="controls">Controls to embed</param>
/// <param name="useFillForLastControl">If true, the last control will be using dockstyle fill</param>
/// <param name="propertyObjects">Objects to show as property</param>
public static void ShowModal(IEnumerable<Control> controls, bool useFillForLastControl, params object[] propertyObjects)
{
var containerControl = new Control();
var numberOfControls = 0;
foreach (var control in controls)
{
control.Dock = DockStyle.Top;
containerControl.Controls.Add(control);
numberOfControls++;
}
if (useFillForLastControl)
{
containerControl.Controls[numberOfControls - 1].Dock = DockStyle.Fill;
}
ShowModal(containerControl, propertyObjects);
}
/// <summary>
/// Checks build_number environment variable to determine whether we run on the build server.
/// </summary>
public static bool IsBuildServer
{
get
{
return File.Exists("C:\\build.server")
|| File.Exists("/tmp/build-server")
|| !String.IsNullOrEmpty(Environment.GetEnvironmentVariable("BUILD_NUMBER"));
}
}
public void ShowControl(Control control, Action<Form> formShownAction, params object[] propertyObjects)
{
exception = null;
formShown = formShownAction;
if (control.TopLevelControl == control)
{
ShowTopLevelControl(control, false);
}
else
{
ShowControlInTestForm(control, false, propertyObjects);
}
}
public void ShowControl(Control control, params object[] propertyObjects)
{
exception = null;
formShown = null;
if (control.TopLevelControl == control)
{
ShowTopLevelControl(control,false);
}
else
{
ShowControlInTestForm(control, false, propertyObjects);
}
}
public void ShowControlModal(Control control, Action<Form> formVisibleChangedAction, params object[] propertyObjects)
{
exception = null;
formShown = formVisibleChangedAction;
var modal = true;
if (control.TopLevelControl == control)
{
ShowTopLevelControl(control, modal);
}
else
{
ShowControlInTestForm(control, modal, propertyObjects);
}
}
public void ShowControlModal(Control control, params object[] propertyObjects)
{
exception = null;
formShown = null;
var modal = true;
if (control.TopLevelControl == control)
{
ShowTopLevelControl(control, modal);
}
else
{
ShowControlInTestForm(control, modal, propertyObjects);
}
}
private void ShowControlInTestForm(Control control, bool modal, object[] propertyObjects)
{
PropertyObjects = propertyObjects;
propertyGrid1.SelectedObject = control;
control.Dock = DockStyle.Fill;
splitContainer1.Panel2.Controls.Add(control);
InitializeTree(control);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
Show();
while (!control.Visible)
{
Application.DoEvents();
}
try
{
if (formShown != null)
{
formShown(this);
}
}
catch (Exception e)
{
exception = e;
}
if (IsBuildServer)
{
Application.DoEvents();
if(exception != null)
{
log.Error("Exception occured: " + exception.Message, exception);
log.Error("Stack trace: " + exception.StackTrace);
throw exception;
}
}
else
{
log.DebugFormat("Not on buildserver so will show the following control modal: {0}", control);
while (modal && Visible)
{
Application.DoEvents();
}
if (exception != null)
{
Trace.WriteLine(exception.StackTrace);
throw exception;
}
}
if (IsBuildServer && modal)
{
Close();
Dispose();
}
}
private static void ShowTopLevelControl(Control control,bool modal)
{
bool wasShown = false;
control.Paint += delegate { wasShown = true; }; // sometimes Visible does not work for forms
control.VisibleChanged += delegate
{
if (control.Visible)
{
wasShown = true;
}
try
{
if (formShown != null && control.Visible)
{
formShown(control is Form ? (Form)control : form);
}
}
catch (Exception e)
{
exception = e;
}
};
control.Show();
if (IsBuildServer)
{
Application.DoEvents();
if (exception != null)
{
throw exception;
}
}
else while (modal && control.Visible)
{
Application.DoEvents();
}
while (!wasShown && !control.Visible) // wait until control is shown
{
Application.DoEvents();
}
if (exception != null)
{
throw exception;
}
if (IsBuildServer && modal)
{
control.Hide();
control.Dispose();
}
}
public static void Close(Control control)
{
control.Hide();
control.Dispose();
}
public static object[] PropertyObjects { get; set; }
public PropertyGrid PropertyGrid
{
get { return propertyGrid1; }
}
public static object PropertyObject
{
get { return form.PropertyGrid.SelectedObject; }
set { form.PropertyGrid.SelectedObject = value; }
}
private class RootNode : ArrayList
{
public override string ToString()
{
return "RootNode";
}
}
private void InitializeTree(Control control)
{
IList itemsToShow = new RootNode {control};
foreach (var o in PropertyObjects)
{
itemsToShow.Add(o);
}
treeView1.ImageList = new ImageList { ColorDepth = ColorDepth.Depth32Bit };
treeView1.ImageList.Images.Add("Control", Resources.Control);
treeView1.ImageList.Images.Add("Data", Resources.Data);
AddAllNodes(treeView1.Nodes, itemsToShow);
treeView1.NodeMouseClick += delegate { propertyGrid1.SelectedObject = treeView1.SelectedNode.Tag; };
}
private void AddAllNodes(TreeNodeCollection nodes, IEnumerable itemsToShow)
{
foreach (var item in itemsToShow.Cast<object>().Where(i => i != null))
{
var imageIndex = item is Control ? 0 : 1;
var node = new TreeNode(item.ToString(), imageIndex, imageIndex) {Tag = item};
nodes.Add(node);
if(item is Control)
{
var control = ((Control)item);
AddAllNodes(node.Nodes, control.Controls);
// hack, try to get Data or DataSource property
PropertyInfo dataProperty = null;
try
{
dataProperty = control.GetType().GetProperty("Data");
}
catch (Exception) {}
if(dataProperty != null)
{
AddAllNodes(node.Nodes, new [] {dataProperty.GetValue(control, null)});
}
var dataSourceProperty = control.GetType().GetProperty("DataSource");
if (dataSourceProperty != null)
{
AddAllNodes(node.Nodes, new[] { dataSourceProperty.GetValue(control, null) });
}
}
if(item is IEnumerable)
{
AddAllNodes(node.Nodes, (IEnumerable)item);
}
}
}
}
} |
using BusVenta;
using DatVentas;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace VentasD1002
{
public partial class frmConexionRemota : Form
{
public frmConexionRemota()
{
InitializeComponent();
}
string strConexion;
int id;
string indicador;
private AES aes = new AES();
int IdCaja = 0;
string SerialPC;
private void frmConexionRemota_Load(object sender, EventArgs e)
{
ManagementObject mos = new ManagementObject(@"Win32_PhysicalMedia='\\.\PHYSICALDRIVE0'");
SerialPC = mos.Properties["SerialNumber"].Value.ToString().Trim();
IdCaja = new BusBox().showBoxBySerial(SerialPC).Id;
}
private void btnConectar_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtIP.Text))
{
}
else
{
MessageBox.Show("Ingrese la IP", "Campo necesario", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ComprobarConexion()
{
try
{
SqlConnection conn = new SqlConnection(strConexion);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT Id_Usuario from tb_Usuario", conn);
id = Convert.ToInt32(cmd.ExecuteScalar());
indicador = "CONECTADO";
conn.Close();
}
catch (Exception ex)
{
indicador = "NO CONECTADO";
}
}
private void ConectarServidor_Manual()
{
string Ip = txtIP.Text;
strConexion = "Data Source=" + Ip + ";Initial Catalog=DBVENTAS; Integrated Security=False; User Id=SoftVentas; Password=123";
ComprobarConexion();
if (indicador.Equals("CONECTADO"))
{
frmEncriptar.SaveToXML(aes.Encrypt(strConexion, Desencryptation.appPwdUnique, int.Parse("256")));
if (IdCaja > 0)
{
MessageBox.Show("Conexión establecida!, vuelva a abrir el sistema", "ÉXITO", MessageBoxButtons.OK, MessageBoxIcon.Information);
Dispose();
}
else
{
frmCajaRemota.strConexion = strConexion;
Dispose();
frmCajaRemota cajaRemota = new frmCajaRemota();
cajaRemota.Show();
}
}
}
public static void SaveToXML(object dbcnString)
{
XmlDocument doc = new XmlDocument();
doc.Load("ConnectionString.xml");
XmlElement root = doc.DocumentElement;
root.Attributes[0].Value = Convert.ToString(dbcnString);
XmlTextWriter writer = new XmlTextWriter("ConnectionString.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
writer.Close();
}
}
}
|
using System;
namespace Algorithms.Structures
{
public class BinarySearchTree<T> where T : struct, IComparable<T>
{
private class Node
{
public Node(T value) => Value = value;
public T Value { get; set; }
public Node? Left { get; set; }
public Node? Right { get; set; }
}
private Node? _root;
public void Insert(T value)
{
var node = new Node(value);
if (_root is null)
{
_root = node;
return;
}
Insert(value, _root);
}
private void Insert(T value, Node node)
{
if (node.Value.Equals(value))
return;
if (node.Value.CompareTo(value) < 0)
{
if (node.Right is null)
node.Right = new Node(value);
else
Insert(value, node.Right);
}
if (node.Value.CompareTo(value) > 0)
{
if (node.Left is null)
node.Left = new Node(value);
else
Insert(value, node.Left);
}
}
public void Delete(T value) => Delete(_root, value);
private Node? Delete(Node? root, T value)
{
if (root is null)
return root;
if (root.Value.CompareTo(value) > 0)
root.Left = Delete(root.Left, value);
else if (root.Value.CompareTo(value) < 0)
root.Right = Delete(root.Right, value);
else
{
if (root.Left is null)
return root.Right;
else if (root.Right is null)
return root.Left;
var nodeToDelete = FindNodeToDelete(root);
root.Value = nodeToDelete.Value;
root.Right = Delete(root.Right, nodeToDelete.Value);
}
return root;
}
private Node FindNodeToDelete(Node node)
{
var cur = node.Right;
if (cur is null)
return node;
while (cur.Left is not null)
cur = cur.Left;
return cur;
}
public bool Find(T value)
{
var curNode = _root;
while (curNode is not null)
{
if (curNode.Value.CompareTo(value) == 0)
return true;
if (curNode.Value.CompareTo(value) > 0)
curNode = curNode.Left;
else
curNode = curNode.Right;
}
return false;
}
public void Inorder(Action<T> action) => Inorder(_root, action);
private void Inorder(Node? node, Action<T> action)
{
if (node is null)
return;
Inorder(node.Left, action);
action.Invoke(node.Value);
Inorder(node.Right, action);
}
public void Preorder(Action<T> action) => Preorder(_root, action);
private void Preorder(Node? node, Action<T> action)
{
if (node is null)
return;
action.Invoke(node.Value);
Preorder(node.Left, action);
Preorder(node.Right, action);
}
public void Postorder(Action<T> action) => Postorder(_root, action);
private void Postorder(Node? node, Action<T> action)
{
if (node is null)
return;
Postorder(node.Left, action);
Postorder(node.Right, action);
action.Invoke(node.Value);
}
}
} |
using System.Collections.Generic;
using System.Linq;
using TheMapToScrum.Back.DAL.Entities;
using TheMapToScrum.Back.DTO;
namespace TheMapToScrum.Back.BLL.Mapping
{
internal static class MapDeveloperDTO
{
internal static DeveloperDTO ToDto(Developer objet)
{
DeveloperDTO retour = new DeveloperDTO();
if (objet != null)
{
retour.Id = objet.Id;
retour.LastName = objet.LastName;
retour.FirstName = objet.FirstName;
retour.IsDeleted = objet.IsDeleted;
retour.DateCreation = (System.DateTime)objet.DateCreation;
retour.DateModification = (System.DateTime)objet.DateModification;
}
return retour;
}
internal static List<DeveloperDTO> ToDto(List<Developer> liste)
{
List<DeveloperDTO> retour = new List<DeveloperDTO>();
retour = liste.Select(x => new DeveloperDTO()
{
Id = x.Id,
LastName = x.LastName,
FirstName = x.FirstName,
DateCreation = (System.DateTime)x.DateCreation,
DateModification = (System.DateTime)x.DateModification,
IsDeleted = x.IsDeleted
})
.ToList();
return retour;
}
}
}
|
using System.Collections.Generic;
namespace IrsMonkeyApi.Models.Dto
{
public class WizardDto
{
public int WizardId { get; set; }
public int? FormId { get; set; }
public string Header { get; set; }
public List<WizardStepDto> Steps { get; set; }
}
} |
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ricky.Infrastructure.Core.ObjectContainer;
using VnStyle.Services.Business;
namespace VnStyle.Web.Infrastructure.Helpers
{
public static class AppHelper
{
public static string HostAction(this UrlHelper url, string actionName, string controllerName, object routeValues)
{
var routeValueDictionary = new RouteValueDictionary(routeValues);
return url.BaseUrl() + url.Action(actionName, controllerName, routeValueDictionary);
}
public static string HostAction(this UrlHelper url, string actionName)
{
return url.BaseUrl() + url.Action(actionName);
}
public static string HostAction(this UrlHelper url, string actionName, string controllerName)
{
return url.BaseUrl() + url.Action(actionName, controllerName);
}
public static string HomePage(this UrlHelper url)
{
return url.BaseUrl() + url.Action("Index", "Home");
}
public static string Language(this UrlHelper url, string lang)
{
var routeValueDictionary = new RouteValueDictionary(url.RequestContext.RouteData.Values);
if (routeValueDictionary.ContainsKey("lang")) routeValueDictionary.Remove("lang");
routeValueDictionary["lang"] = lang;
return url.BaseUrl() + url.RouteUrl(routeValueDictionary);
}
public static string HostContent(this UrlHelper url, string contentPath)
{
return url.BaseUrl() + url.Content(contentPath);
}
public static string Version()
{
return Guid.NewGuid().ToString();
}
public static string T(this HtmlHelper html, string text, params object[] args)
{
return EngineContext.Current.Resolve<IResourceService>().T(text, args);
}
}
}
|
namespace ApiTemplate.Common.Markers.Configurations
{
public interface IConfiguration
{
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using ProjectBueno.Game.Entities;
using ProjectBueno.Game.Spells;
using System;
namespace ProjectBueno.Engine
{
public class SkillHandler : MenuHandler
{
public GameHandler game;
protected Player player;
public static readonly Vector2 namePos;
public static readonly Vector2 descPos;
public static readonly Vector2 costPos;
public static readonly Vector2 kpPos;
protected Skill curHeld;
public SkillHandler(GameHandler game, Player player)
{
this.game = game;
background = Main.content.Load<Texture2D>("skillTree");
this.player = player;
}
static SkillHandler()
{
namePos = new Vector2((int)Main.Config["namePos"]["x"], (int)Main.Config["namePos"]["y"]);
descPos = new Vector2((int)Main.Config["descPos"]["x"], (int)Main.Config["descPos"]["y"]);
costPos = new Vector2((int)Main.Config["costPos"]["x"], (int)Main.Config["costPos"]["y"]);
kpPos = new Vector2((int)Main.Config["kpPos"]["x"], (int)Main.Config["kpPos"]["y"]);
}
public override void Draw()
{
float mouseX = Main.newMouseState.X * downscale;
float mouseY = Main.newMouseState.Y * downscale;
Skill drawHeldText = curHeld;
Main.spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, Main.AliasedRasterizer, null, screenScale);
Main.spriteBatch.Draw(background, Vector2.Zero, Color.White);
foreach (Skill skillButton in player.skills)
{
if (skillButton.DrawButton(mouseX, mouseY))
{
drawHeldText = skillButton;
}
}
drawHeldText = player.spells[player.selectedSpell].DrawButtons(mouseX, mouseY) ?? drawHeldText;
if (drawHeldText != null)
{
Main.spriteBatch.DrawString(Main.retroFont, drawHeldText.name, namePos, Color.Purple);
Main.spriteBatch.DrawString(Main.retroFont, drawHeldText.description, descPos, Color.Black);
Main.spriteBatch.DrawString(Main.retroFont, drawHeldText.cost + "KP", costPos, Color.Green);
}
if (curHeld != null)
{
curHeld.Draw(new Vector2(mouseX-Skill.buttonSize*0.5f, mouseY-Skill.buttonSize*0.5f));
}
Main.spriteBatch.DrawString(Main.retroFont, player.knowledgePoints + "KP", kpPos, Color.Green);
Main.spriteBatch.End();
}
public override void Update()
{
float mouseX = Main.newMouseState.X * downscale;
float mouseY = Main.newMouseState.Y * downscale;
bool clearHeld = true;
if (Main.newMouseState.LeftButton == ButtonState.Pressed && Main.oldMouseState.LeftButton == ButtonState.Released)
{
foreach (Skill skill in player.skills)
{
if (skill.onClick(mouseX, mouseY, ref player.knowledgePoints, ref curHeld))
{
clearHeld = false;
}
}
if (!player.spells[player.selectedSpell].onPlaceClick(mouseX, mouseY, ref curHeld) && clearHeld)
{
curHeld = null;
}
}
if (Main.newKeyState.IsKeyDown(Keys.Back) && !Main.oldKeyState.IsKeyDown(Keys.Back))
{
Main.Handler = game;
}
if (Main.newKeyState.IsKeyDown(Keys.K) && !Main.oldKeyState.IsKeyDown(Keys.K))
{
game.player.knowledgePoints = 10000;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MoneyShare.Models;
using MoneyShare.Repos;
using MoneyShare.ViewModels;
namespace MoneyShare.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ForgotPasswordController : ControllerBase
{
private SignInManager<MemberModel> _signInManager;
private UserManager<MemberModel> _userManager;
private IMemberServices _memberServices;
private IConfiguration _configuration;
// private static string _LoginFailureMessage = "Login Failed.";
public ForgotPasswordController(
SignInManager<MemberModel> signInManager,
UserManager<MemberModel> userManager,
IMemberServices memberServices,
IConfiguration configuration)
{
_signInManager = signInManager;
_userManager = userManager;
_memberServices = memberServices;
_configuration = configuration;
}
[HttpPost]
public async Task<ActionResult> Post([FromBody] ForgotPasswordViewModel model)
{
if (
string.IsNullOrWhiteSpace(model.Username) ||
string.IsNullOrWhiteSpace(model.Email) ||
string.IsNullOrWhiteSpace(model.FirstName) ||
string.IsNullOrWhiteSpace(model.LastName))
{
return new UnauthorizedResult();
}
else
{
MemberModel UnameMember = await _userManager.FindByNameAsync(model.Username);
MemberModel EmailMember = await _userManager.FindByEmailAsync(model.Email);
if (
UnameMember != null &&
UnameMember == EmailMember &&
UnameMember.FirstName == model.FirstName &&
EmailMember.LastName == model.LastName)
{
var token = await _userManager.GeneratePasswordResetTokenAsync(UnameMember);
var resetLink = Url.Action("ResetPassword", "Home",
new { UserId = EmailMember.Id, Token = token }, Request.Scheme);
_memberServices.SendResetLink(UnameMember, resetLink);
return new OkResult();
}
return new UnauthorizedResult();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace BancoSeries.Interfaces
{
public interface IGerenciador<T>
{
void Adicionar(T item);
void Excluir(int id);
T Selecionar(int id);
void Limpar();
int PegarProximoID();
string[] Listar();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Optymalizacja_wykorzystania_pamieci.Diagnostics;
using Optymalizacja_wykorzystania_pamieci.Interfaces;
namespace Optymalizacja_wykorzystania_pamieci.Tasks.Simple_Allocation
{
class Simple_Array_Allocation
{
private bool allocation { get; set; }
public Simple_Array_Allocation(bool allocation)
{
this.allocation = allocation;
}
public Queue<TaskInterface> PrepareForSimpleAllocation(int number_of_tasks)
{
Queue<TaskInterface> list_of_tasks = new Queue<TaskInterface>();
//Dodawanie do kolejki zadań
if (this.allocation)
for(int i = 0; i < number_of_tasks; i++)
list_of_tasks.Enqueue(new Engine_Task<Simple_Array_Allocation, Simple_Allocation_Parameters>
(i, this, new TypeOfTask<Simple_Array_Allocation, Simple_Allocation_Parameters>(SimpleAllocationWithAdditionalMemory), null));
else
for (int i = 0; i < number_of_tasks; i++)
list_of_tasks.Enqueue(new Engine_Task<Simple_Array_Allocation, Simple_Allocation_Parameters>
(i, this, new TypeOfTask<Simple_Array_Allocation, Simple_Allocation_Parameters>(SimpleAllocationWithoutAdditionalMemory), null));
return list_of_tasks;
}
public void SimpleAllocationWithoutAdditionalMemory(Simple_Array_Allocation a, Simple_Allocation_Parameters p)
{
try
{ //Celowo nie użyto pętli
int[] tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
}
catch(Exception)
{
Console.WriteLine("\nNie udalo sie zaalokowac tablic - prawdopodobnie przekroczono limit pamieci.\n");
}
}
public void SimpleAllocationWithAdditionalMemory(Simple_Array_Allocation a, Simple_Allocation_Parameters p)
{
try
{
for (int i = 0; i < 50; i++)
{
int[] tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
tab = new int[1000000];
}
}
catch (Exception)
{
Console.WriteLine("\nNie udalo sie zaalokowac tablic - prawdopodobnie przekroczono limit pamieci.\n");
}
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebCore.CustomerActionResult;
using WebCore.Fileters;
namespace WebCore.WebApi
{
[ApiController]
[Route("api/[controller]")]
public class TestController : Controller
{
[HttpGet(nameof(GetResult))]
public string GetResult()
{
return "测试Get请求";
}
[HttpPost(nameof(PostResult))]
public string PostResult()
{
return "测试Post请求";
}
[HttpGet(nameof(GetReultWithParam))]
public string GetReultWithParam(string msg, string msg2)
{
return $"get {msg} {msg2}";
}
[HttpPost(nameof(PostResultWithParam))]
public string PostResultWithParam([FromForm]string msg, [FromForm]string msg2)
{
return $"post {msg} {msg2}";
}
[HttpPost(nameof(PostResultWithModel))]
public MyClass[] PostResultWithModel([FromBody]MyClass model)
{
return new[] { model };
}
//[HttpPost(nameof(UploadFile))]
//public string UploadFile([FromForm]IFormCollection form)
//{
// var file1 = form.Files["file001"];
// var file2 = form.Files["file002"];
// string msg = form["msg"];
// return $"文件1长度:{file1.Length} 文件2长度:{file2.Length} msg:{msg} 111";
//}
[CustomerResultFilter]
[HttpGet(nameof(TestMyContentResult))]
public IActionResult TestMyContentResult()
{
//return new ContentResult()
//{
// Content = JsonConvert.SerializeObject(new
// {
// msg = "123",
// msg2 = "456"
// })
//};
return new MyContentResult()
{
Content = new
{
msg = "123",
msg2 = "456"
}
};
}
}
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
}
}
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WebStore.DomainNew.Filters;
using WebStore.Interfaces;
namespace WebStore.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Roles ="Administrator")]
public class HomeController : Controller
{
private readonly IProductService _productService;
public HomeController(IProductService productService)
{
_productService = productService;
}
public IActionResult Index()
{
return View();
}
public IActionResult ProductList()
{
return View(_productService
.GetProducts(new ProductsFilter()));
}
}
} |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
namespace BuildingGame
{
class CellSelection
{
Sprite freeSpace;
Sprite blockedSpace;
Map map;
Cell[,] cells;
int width;
int height;
public CellSelection(Map map, int width, int height)
{
this.map = map;
cells = new Cell[width, height];
this.width = width;
this.height = height;
freeSpace = Sprites.FreeSpace;
blockedSpace = Sprites.BlockedSpace;
}
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
foreach (Cell c in cells)
{
if (c.Building == null)
freeSpace.Draw(spriteBatch, Vector2.Transform(map.CalcWorldToScreen(c.Position), map.Camera.GetMatrix()));
else
blockedSpace.Draw(spriteBatch, Vector2.Transform(map.CalcWorldToScreen(c.Position), map.Camera.GetMatrix()));
}
}
public Cell[,] GetCells()
{
return cells;
}
public void SetSize(int width,int height)
{
this.width = width;
this.height = height;
}
public void Update(GameTime gameTime)
{
Vector2 trans = Vector2.Transform(Input.MousePosition.ToVector2(), Matrix.Invert(map.Camera.GetMatrix()));
Vector2 position = map.CalcScreenToWorld(trans);
position -= new Vector2(width / 2, height / 2);
Point p = Vector2.Clamp(position.ToPoint().ToVector2(), new Vector2(0, 0), new Vector2(map.Width - 1, map.Height - 1)).ToPoint();
//Point p = _map.Selector.GetCellWorldPosition(); // - new Point(building.Size.X / 2, building.Size.Y / 2)
if (p.X + width >= map.Width)
p.X = map.Width - width;
if (p.Y + height >= map.Height)
p.Y = map.Height - height;
//if (p.X - building.Size.X <= 0)
// p.X = building.Size.X;
//if (p.Y - building.Size.Y <= 0)
// p.Y = building.Size.Y;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
cells[x,y] = map.Grid.Cells[p.X + x, p.Y + y];
}
}
}
//public bool canBuild()
//{
// foreach (Cell c in _cells)
// {
// if (c.Building != null)
// return false;
// }
// return true;
//}
}
} |
using Likja.Conthread.ThirdParty;
using Likja.Domain.Common;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Likja.Conthread
{
[Table("conthread")]
public class Conthread : DomainEntity
{
[Column("title")]
[Required, MaxLength(50)]
public string Title { get; set; }
[Column("content")]
public string Content { get; set; }
[Column("created_by")]
[MaxLength(50)]
public string CreatedBy { get; set; }
[Column("content_type")]
public ContentType ContentType { get; set; }
[NotMapped]
public string HashId
{
get { return Id.ConvertToHash(); }
}
[NotMapped]
public string SlugTitle
{
get { return Title.GenerateSlug(); }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RimLiqourProject.Models;
using NewRimLiqourProject.Models;
namespace NewRimLiqourProject.Controllers
{
public class OrderController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: /Order/
public async Task<ActionResult> Index()
{
var orders = db.Orders.Include(o => o.Products);
return View(await orders.ToListAsync());
}
// GET: /Order/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Order order = await db.Orders.FindAsync(id);
if (order == null)
{
return HttpNotFound();
}
return View(order);
}
// GET: /Order/Create
public ActionResult Create()
{
ViewBag.ProductID = new SelectList(db.Products, "ProductID", "ProductName");
return View();
}
// POST: /Order/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Order order)
{
if (ModelState.IsValid)
{
try
{
order.DateCreated = DateTime.Now;
db.Orders.Add(order);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
catch
{
ModelState.AddModelError("", "Error 4");
}
}
ViewBag.ProductID = new SelectList(db.Products, "ProductID", "ProductName", order.ProductID);
return View(order);
}
// GET: /Order/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Order order = await db.Orders.FindAsync(id);
if (order == null)
{
return HttpNotFound();
}
ViewBag.ProductID = new SelectList(db.Products, "ProductID", "ProductName", order.ProductID);
return View(order);
}
// POST: /Order/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Order order)
{
if (ModelState.IsValid)
{
db.Entry(order).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.ProductID = new SelectList(db.Products, "ProductID", "ProductName", order.ProductID);
return View(order);
}
// GET: /Order/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Order order = await db.Orders.FindAsync(id);
if (order == null)
{
return HttpNotFound();
}
return View(order);
}
// POST: /Order/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Order order = await db.Orders.FindAsync(id);
db.Orders.Remove(order);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using RSS.Business.Interfaces;
using RSS.Business.Notifications;
using System;
using System.Linq;
namespace RSS.WebApi.Controllers
{
[ApiController]
public abstract class MainController : ControllerBase
{
private readonly INotifiable _notifiable;
public readonly IUser AppUser;
protected Guid UserId { get; }
protected bool AuthenticatedUser { get; }
protected MainController(INotifiable notifiable,
IUser appUser)
{
_notifiable = notifiable;
AppUser = appUser;
if (appUser.IsAuthenticated())
{
UserId = appUser.GetUserId();
AuthenticatedUser = true;
}
}
protected ActionResult CustomResponse(ModelStateDictionary modelState)
{
if (!modelState.IsValid) NotifyModelInvalidError(modelState);
return CustomResponse();
}
private bool ValidOperation()
{
return !_notifiable.HasNotification();
}
protected ActionResult CustomResponse(object result = null)
{
if (ValidOperation())
{
return Ok(new {
success = true,
data = result
});
}
return BadRequest(new {
success = false,
errors = _notifiable.GetNotifications().Select(n => n.Message)
});
}
protected void NotifyModelInvalidError(ModelStateDictionary modelState)
{
var errors = modelState.Values.SelectMany(e => e.Errors);
foreach (var error in errors)
{
var errMsg = error.Exception == null ? error.ErrorMessage : error.Exception.Message;
NotifyError(errMsg);
}
}
protected void NotifyError(string errMsg)
{
_notifiable.Handle(new Notification(errMsg));
}
}
}
|
//---------------------------------------------------------------------------------
// Copyright (c) August 2018, devMobile Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//---------------------------------------------------------------------------------
namespace devMobile.IoT.Rfm9x
{
using System;
using System.Diagnostics;
using System.Runtime.InteropServices.WindowsRuntime;
using Meadow.Devices;
using Meadow.Hardware;
public sealed class RegisterManager
{
ISpiBus SpiBus = null;
private IDigitalOutputPort ChipSelectGpioPin = null;
private SpiPeripheral Rfm9XLoraModem = null;
private const byte RegisterAddressReadMask = 0X7f;
private const byte RegisterAddressWriteMask = 0x80;
public RegisterManager(IMeadowDevice device, ISpiBus spiBus, IPin chipSelectPin)
{
this.SpiBus = spiBus;
// Chip select pin configuration
ChipSelectGpioPin = device.CreateDigitalOutputPort(chipSelectPin, initialState: true);
Rfm9XLoraModem = new SpiPeripheral(spiBus, ChipSelectGpioPin);
}
public Byte ReadByte(byte address)
{
byte[] writeBuffer = new byte[] { address &= RegisterAddressReadMask, 0x0 };
byte[] readBuffer = new byte[writeBuffer.Length];
Debug.Assert(Rfm9XLoraModem != null);
SpiBus.ExchangeData(this.ChipSelectGpioPin, ChipSelectMode.ActiveLow, writeBuffer, readBuffer);
return readBuffer[1];
}
public byte[] Read(byte address, int length)
{
byte[] writeBuffer = new byte[length + 1];
byte[] readBuffer = new byte[writeBuffer.Length];
byte[] replyBuffer = new byte[length];
Debug.Assert(Rfm9XLoraModem != null);
writeBuffer[0] = address &= RegisterAddressReadMask;
SpiBus.ExchangeData(this.ChipSelectGpioPin, ChipSelectMode.ActiveLow, writeBuffer, readBuffer);
Array.Copy(readBuffer, 1, replyBuffer, 0, length);
return replyBuffer;
}
public void WriteByte(byte address, byte value)
{
byte[] writeBuffer = new byte[] { address |= RegisterAddressWriteMask, value };
byte[] readBuffer = new byte[writeBuffer.Length];
Debug.Assert(Rfm9XLoraModem != null);
SpiBus.ExchangeData(this.ChipSelectGpioPin, ChipSelectMode.ActiveLow, writeBuffer, readBuffer);
}
public void Write(byte address, [ReadOnlyArray()] byte[] bytes)
{
byte[] writeBuffer = new byte[1 + bytes.Length];
byte[] readBuffer = new byte[writeBuffer.Length];
Debug.Assert(Rfm9XLoraModem != null);
Array.Copy(bytes, 0, writeBuffer, 1, bytes.Length);
writeBuffer[0] = address |= RegisterAddressWriteMask;
SpiBus.ExchangeData(this.ChipSelectGpioPin, ChipSelectMode.ActiveLow, writeBuffer, readBuffer);
}
public void Dump(byte start, byte finish)
{
Console.WriteLine("Register dump");
for (byte registerIndex = start; registerIndex <= finish; registerIndex++)
{
byte registerValue = this.ReadByte(registerIndex);
Console.WriteLine("Register 0x{0:x2} - Value 0X{1:x2} - Bits {2}", registerIndex, registerValue, Convert.ToString(registerValue, 2).PadLeft(8, '0'));
}
}
}
}
|
namespace Students
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class MyExtensionMethods
{
public static void ExtractGroup2(this List<Student> list)
{
var group2 =
from student in list
orderby student.FirstName
where (student.GroupNumber == 2)
select student;
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("Students in Group 2 (By an extension method):");
Console.WriteLine(new string('-', 40));
Console.ForegroundColor = ConsoleColor.DarkGray;
foreach (var stud in group2)
{
Console.WriteLine(stud.ToString());
}
}
public static void ExtraxtByEmail(this List<Student> list)
{
var abvAccounts =
from student in list
where (student.Email.Substring(student.Email.Length - 6, 3) == "abv")
select student;
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("Students with accounts in abv.bg:");
Console.WriteLine(new string('-', 40));
Console.ForegroundColor = ConsoleColor.DarkGray;
foreach (var stud in abvAccounts)
{
Console.WriteLine(stud.ToString());
}
}
public static void ExtractByPhone(this List<Student> list)
{
var fromSofia =
from student in list
where (student.Tel.Substring(0,2) == "02")
select student;
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("Students with Telephones in Sofia:");
Console.WriteLine(new string('-', 40));
Console.ForegroundColor = ConsoleColor.DarkGray;
foreach (var stud in fromSofia)
{
Console.WriteLine(stud.ToString());
}
}
public static void ExtractMarksof06(this List<Student> list)
{
var listOf06 =
from stud in list
where (stud.FN.Substring(4, 2) == "06")
select stud;
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("Students with enrolled in 06:");
Console.WriteLine(new string('-', 40));
Console.ForegroundColor = ConsoleColor.DarkGray;
foreach (var stud in listOf06)
{
Console.WriteLine("Last name: {0}", stud.LastName);
Console.WriteLine("Marks: {0}", string.Join(", ", stud.Marks));
}
}
public static void GroupByGroups(this List<Student> list)
{
var groupedList =
from stud in list
orderby stud.GroupNumber ascending
select stud;
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("Students by Groups");
Console.WriteLine(new string('-', 40));
Console.ForegroundColor = ConsoleColor.DarkGray;
foreach (var stud in groupedList)
{
Console.WriteLine(stud);
}
}
}
}
|
using System;
namespace Element_equal_to_sum
{
class Program
{
static void Main(string[] args)
{
int numberOfNumbers = int.Parse(Console.ReadLine());
int sum = 0;
int maxNumber = int.MinValue;
for (int i = 0; i < numberOfNumbers; i++)
{
int inputNumber = int.Parse(Console.ReadLine());
sum += inputNumber;
if (inputNumber > maxNumber)
{
maxNumber = inputNumber;
}
}
if ((sum - maxNumber) == maxNumber)
{
Console.WriteLine("Yes");
Console.WriteLine($"Sum = {maxNumber}");
}
else
{
Console.WriteLine("No");
Console.WriteLine($"Diff = {Math.Abs(maxNumber - (sum - maxNumber))}");
}
}
}
}
|
using System.Drawing;
namespace gView.Framework.system.UI
{
public interface IUIImageList
{
Image this[int index] { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OPCClient
{
public class DCHisRow
{
public long PartitioningKey { get; set; }
public int TagID { get; set; }
public string TagName { get; set; }
public int UnixTime { get; set; }
public string DateType { get; set; }
public float Value { get; set; }
public string ValueStr { get; set; }
public string Quality { get; set; }
}
}
|
using System;
using System.Text;
namespace MySql.Data.Serialization
{
internal class InitDatabasePayload
{
public static PayloadData Create(string databaseName)
{
var writer = new PayloadWriter();
writer.WriteByte((byte) CommandKind.InitDatabase);
writer.Write(Encoding.UTF8.GetBytes(databaseName));
return new PayloadData(new ArraySegment<byte>(writer.ToBytes()));
}
}
}
|
using System;
using System.Activities.Expressions;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.UI.WebControls;
public partial class Admin_Suppliers_AddInvoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Helper.ValidateAdmin();
if (!IsPostBack)
{
}
}
[WebMethod]
public static List<string> GetSupplier(string prefixText)
{
List<string> name = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = @"SELECT SupplierName, SupplierID FROM Suppliers WHERE
SupplierName LIKE @SearchText
ORDER BY SupplierName ASC";
cmd.Parameters.AddWithValue("@SearchText", "%" + prefixText + "%");
cmd.Connection = conn;
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
string myString = dr["SupplierName"] + "/vn/" + dr["SupplierID"];
name.Add(myString);
}
}
conn.Close();
}
}
return name;
}
protected void btnUser_Click(object sender, EventArgs e)
{
if (hfName.Value != "0")
{
using (var con = new SqlConnection(Helper.GetCon()))
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = @"SELECT SupplierID, SupplierName, ContactNo,
Address, ContactNo, ContactPerson, Status
FROM Suppliers WHERE SupplierID = @id";
cmd.Parameters.AddWithValue("@id", hfName.Value);
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
if (dr.Read())
{
txtSupplierName.Text = dr["SupplierName"].ToString();
txtPayable.Text = dr["SupplierName"].ToString();
txtAddress.Text = dr["Address"].ToString();
txtContactNo.Text = dr["ContactNo"].ToString();
txtContactPer.Text = dr["ContactPerson"].ToString();
txtStatus.Text = dr["Status"].ToString();
}
}
}
}
}
GetInvoice();
}
protected void btnAddInvoice_Click(object sender, EventArgs e)
{
if (txtInvoiceNo.Text != "")
{
invoiceNoError.Visible = false;
if (!isExist())
{
invoiceExist.Visible = false;
using (var con = new SqlConnection(Helper.GetCon()))
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = @"INSERT INTO Invoice
(InvoiceNumber, Description, InvoiceDate, Amount,
SupplierID, CheckID, Status, UserID, DateAdded)
VALUES
(@inum, @desc, @idate, @amnt, @supid, @cid, @status, @uid, @dadded)";
cmd.Parameters.AddWithValue("@inum", txtInvoiceNo.Text);
cmd.Parameters.AddWithValue("@desc", txtDesc.Text);
cmd.Parameters.AddWithValue("@idate", txtInvoiceDate.Text);
cmd.Parameters.AddWithValue("@amnt", txtInvoiceAmnt.Text);
cmd.Parameters.AddWithValue("@supid", hfName.Value);
cmd.Parameters.AddWithValue("@cid", -1);
cmd.Parameters.AddWithValue("@status", ddlStatus.SelectedValue);
cmd.Parameters.AddWithValue("@uid", Session["userid"].ToString());
cmd.Parameters.AddWithValue("@dadded", Helper.PHTime());
cmd.ExecuteNonQuery();
}
txtInvoiceNo.Text = string.Empty;
txtDesc.Text = string.Empty;
txtInvoiceDate.Text = string.Empty;
txtInvoiceAmnt.Text = string.Empty;
GetInvoice();
}
else
{
invoiceExist.Visible = true;
}
}
else
{
invoiceNoError.Visible = true;
}
}
bool isExist()
{
bool isExist;
using (var con = new SqlConnection(Helper.GetCon()))
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = @"SELECT InvoiceNumber FROM Invoice
WHERE InvoiceNumber = @ino AND SupplierID = @sid";
cmd.Parameters.AddWithValue("@sid", hfName.Value);
cmd.Parameters.AddWithValue("@ino", txtInvoiceNo.Text);
using (SqlDataReader dr = cmd.ExecuteReader())
{
dr.Read();
{
isExist = dr.HasRows;
}
}
}
return isExist;
}
private void GetInvoice()
{
using (var con = new SqlConnection(Helper.GetCon()))
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = @"SELECT InvoiceID, InvoiceNumber, Description,
InvoiceDate, Amount, Status, DateAdded
FROM Invoice WHERE SupplierID = @id
AND UserID = @uid AND CheckID = '-1'";
cmd.Parameters.AddWithValue("@uid", Session["userid"].ToString());
cmd.Parameters.AddWithValue("@id", hfName.Value);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
con.Close();
da.Fill(ds, "Invoice");
lvInvoice.DataSource = ds;
lvInvoice.DataBind();
}
GetTotal();
}
private void GetTotal()
{
using (var con = new SqlConnection(Helper.GetCon()))
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = @"SELECT SUM(Amount) AS Total
FROM Invoice WHERE SupplierID = @id
AND UserID = @uid AND CheckID = '-1'";
cmd.Parameters.AddWithValue("@uid", Session["userid"].ToString());
cmd.Parameters.AddWithValue("@id", hfName.Value);
using (var dr = cmd.ExecuteReader())
{
if (!dr.HasRows) return;
if (!dr.Read()) return;
if (dr["Total"].ToString() != "")
{
txtCheckAmnt.Text = Convert.ToDecimal(dr["Total"]).ToString("##.00");
}
else
{
txtCheckAmnt.Text = "0.00";
}
}
}
}
protected void lvInvoice_PagePropertiesChanging(object sender, System.Web.UI.WebControls.PagePropertiesChangingEventArgs e)
{
dpInvoice.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
GetInvoice();
}
protected void lvInvoice_DataBound(object sender, EventArgs e)
{
dpInvoice.Visible = dpInvoice.PageSize < dpInvoice.TotalRowCount;
}
protected void lvInvoice_ItemCommand(object sender, System.Web.UI.WebControls.ListViewCommandEventArgs e)
{
Literal ltInvoiceID = (Literal)e.Item.FindControl("ltInvoiceID");
using (var con = new SqlConnection(Helper.GetCon()))
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = @"DELETE FROM Invoice
WHERE InvoiceID = @id";
cmd.Parameters.AddWithValue("@id", ltInvoiceID.Text);
cmd.ExecuteNonQuery();
}
GetInvoice();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (var con = new SqlConnection(Helper.GetCon()))
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = @"INSERT INTO Cheques
(Bank, CheckNo, PayableTo, CheckAmount, CheckDate, DateAdded)
VALUES
(@bank, @chkno, @payto, @chkamnt, @chkdate, @dadded);
SELECT TOP 1 ChequeID FROM Cheques ORDER BY ChequeID DESC";
cmd.Parameters.AddWithValue("@bank", txtBank.Text);
cmd.Parameters.AddWithValue("@chkno", txtCheckNo.Text);
cmd.Parameters.AddWithValue("@payto", txtPayable.Text);
cmd.Parameters.AddWithValue("@chkamnt", txtCheckAmnt.Text);
cmd.Parameters.AddWithValue("@chkdate", txtDate.Text);
cmd.Parameters.AddWithValue("@dadded", Helper.PHTime());
int chequeid = (int)cmd.ExecuteScalar();
Helper.Log("Add Cheque",
"Added new cheque: " + txtBank.Text + txtPayable.Text,
"", Session["userid"].ToString());
cmd.Parameters.Clear();
cmd.CommandText = @"UPDATE Invoice SET CheckID = @cid
WHERE SupplierID = @sid AND UserID = @uid
AND CheckID = '-1'";
cmd.Parameters.AddWithValue("@cid", chequeid);
cmd.Parameters.AddWithValue("@sid", hfName.Value);
cmd.Parameters.AddWithValue("@uid", Session["userid"].ToString());
cmd.ExecuteNonQuery();
Response.Redirect("View.aspx");
}
}
} |
using Entities.DbEntities;
using Microsoft.AspNet.Identity.EntityFramework;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace Repositories
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public virtual DbSet<JournalEntry> JournalEntries { get; set; }
public virtual DbSet<CrossOutList> CrossOutLists { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder
.Entity<ApplicationUser>()
.HasMany(x => x.JournalEntries)
.WithRequired(x => x.User)
.WillCascadeOnDelete(false);
modelBuilder
.Entity<JournalEntry>()
.HasKey(x => x.Id);
modelBuilder
.Entity<JournalEntry>()
.Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
//modelBuilder
// .Entity<JournalEntry>()
// .HasRequired(x => x.User)
// .WithMany(x => x.JournalEntries)
// .HasForeignKey(x => x.UserId)
// .WillCascadeOnDelete(false);
modelBuilder
.Entity<CrossOutList>()
.HasKey(x => x.UserId);
modelBuilder
.Entity<CrossOutList>()
.HasRequired(x => x.User)
.WithRequiredDependent(x => x.CrossOutList)
.WillCascadeOnDelete(false);
modelBuilder
.Entity<CrossOutList>()
.Property(x => x.Filtering)
.IsRequired();
modelBuilder
.Entity<CrossOutList>()
.Property(x => x.Overgeneralization)
.IsRequired();
modelBuilder
.Entity<CrossOutList>()
.Property(x => x.PolarizedThinking)
.IsRequired();
modelBuilder
.Entity<CrossOutList>()
.Property(x => x.Catastrophising)
.IsRequired();
modelBuilder
.Entity<CrossOutList>()
.Property(x => x.Shoulds)
.IsRequired();
modelBuilder
.Entity<CrossOutList>()
.Property(x => x.MindReading)
.IsRequired();
modelBuilder
.Entity<CrossOutList>()
.Property(x => x.EmotionalReasoning)
.IsRequired();
modelBuilder
.Entity<CrossOutList>()
.Property(x => x.Personalizing)
.IsRequired();
}
}
} |
using UnityEngine;
using System;
public class Level : MonoBehaviour
{
public Builder builder; public Builder Builder {
get {
return this.builder;
}
}
private const int daysPerLevel = 3;
private Day[] days;
public Day[] Days
{
get { return days; }
}
private int currentDay;
public int CurrentDayNumber{
get{return currentDay;}
}
public Day CurrentDay {
get {
if(currentDay < daysPerLevel){
return days[currentDay];
}else{
return null;
}
}
}
private double budget;
public double Budget
{
get { return budget; }
}
private float timePerDay;
public float TimePerDay
{
get { return timePerDay; }
}
private static Level instance;
private bool lostLevel;
public static Level Instance
{
get { return instance; }
}
private bool onDayReportScreen;
private bool onLevelReportScreen;
private float totalTimeSpent;
private float timeSpent;
private double totalBudgetSpent;
private double totalLevelBudget;
private double totalSolutionBudget;
private bool calculatedTimeSpent;
public Texture2D[] botones;
public GUISkin skin;
void Awake() {
if (instance == null)
{
instance = this;
}
else
{
Debug.Log("Solo puede haber un level activo a la vez");
Destroy(this.gameObject);
}
}
void Start()
{
Debug.Log(LevelSettings.Instance.Difficulty);
budget = 0.0d;
timeSpent = 0;
totalSolutionBudget=0;
totalBudgetSpent = 0.0d;
calculatedTimeSpent=false;
onLevelReportScreen=false;
onDayReportScreen=false;
days = new Day[daysPerLevel];
days[0] = new Day(TSPSolver.generateCase(LevelSettings.Instance.NodeCount, LevelSettings.Instance.CityDimensions));
double cost = TSPSolver.calculateCost(days[0].Solution, days[0].TspCase);
budget += cost;
Debug.Log("Costo "+ 0 + ": "+cost);
for (int i = 1; i < daysPerLevel; i++)
{
days[i] = new Day(TSPSolver.generateCase(LevelSettings.Instance.NodeCount, days[0].TspCase.Nodes[0], LevelSettings.Instance.CityDimensions));
cost = TSPSolver.calculateCost(days[i].Solution, days[i].TspCase);
Debug.Log("Costo "+ i + ": "+cost);
budget += cost;
}
Debug.Log("Optimo:"+budget);
budget += budget * (LevelSettings.Instance.ErrorMargin / 100.0f);
Debug.Log("Maximo:"+budget);
timePerDay = LevelSettings.Instance.Time;
currentDay = 0;
totalLevelBudget=budget;
loadDay();
Player.Instance.truck = builder.truck;
Player.Instance.CurrentDay = CurrentDay;
}
private void loadDay()
{
try
{
builder.buildCity(CurrentDay);
}
catch (Exception e)
{
Debug.Log(e);
}
}
public void nextDay(int[] playerSolution, double spentMoney) {
budget -= spentMoney;
Debug.Log("SpentMoney = "+spentMoney+", Budget = "+budget);
currentDay++;
calculatedTimeSpent=false;
if (currentDay < daysPerLevel)
{
loadDay();
Player.Instance.CurrentDay = CurrentDay;
}
else
{
Debug.Log(budget);
if (budget > 0.0d)
{
if(LevelSettings.Instance.Difficulty != Difficulty.Extreme){
LevelSettings.Instance.Difficulty = (Difficulty)(((int)LevelSettings.Instance.Difficulty)+1);
Application.LoadLevel("Game");
}
}
else
{
lostLevel = true;
}
}
}
public void showDayReportScreen(){
if(budget<0.0d){
lostLevel=true;
} else {
if(!calculatedTimeSpent){
onDayReportScreen=true;
totalTimeSpent+= Time.timeSinceLevelLoad;
timeSpent= Time.timeSinceLevelLoad;
totalBudgetSpent+= Player.Instance.SpentMoney;
totalSolutionBudget+= TSPSolver.calculateCost(CurrentDay.Solution, CurrentDay.TspCase);
calculatedTimeSpent=true;
}
}
}
void OnGUI() {
GUI.skin = skin;
if(lostLevel){
if(GUI.Button(new Rect(Screen.width/3, Screen.height/2 - 5 - Screen.height/4, Screen.width/3, Screen.height/4), "Retry")){
Application.LoadLevel("Game");
}
if (GUI.Button(new Rect(Screen.width / 3, Screen.height / 2, Screen.width / 3, Screen.height / 4), "Quit"))
{
Application.LoadLevel("Main Menu");
}
} else {
if(onLevelReportScreen){
GUI.BeginGroup(new Rect(Screen.width/4 + Screen.width/8, Screen.height/4, 2*Screen.width/8, Screen.height/3));
GUI.Box(new Rect(0, 0, 2 * Screen.width / 8, Screen.height / 3), "");
GUI.Label(new Rect(80, 10, 200, 20), "Level Complete");
GUI.Label(new Rect(30, 50, 200, 20), "Total budget remaining: " + budget);
GUI.Label(new Rect(30, 75, 200, 20), "Total time spent: " + (int)totalTimeSpent);
GUI.Label(new Rect(30, 100, 200, 20), "Total budget spent: " + totalBudgetSpent);
GUI.Label(new Rect(30, 124, 200, 20), "Best solution's budget: " + totalSolutionBudget);
if(GUI.Button(new Rect(30, 180, 100, 50), "Main Menu")){
Application.LoadLevel("Main Menu");
}
if(GUI.Button(new Rect(140, 180, 100, 50), "Next Level")){
onLevelReportScreen=false;
Player.Instance.NextLevel();
}
GUI.EndGroup();
}
if(onDayReportScreen){
GUI.BeginGroup(new Rect(Screen.width/4 + Screen.width/8, Screen.height/4, 2*Screen.width/8, Screen.height/3));
GUI.Box(new Rect(0, 0, 2 * Screen.width / 8, Screen.height / 3), "");
GUI.Label(new Rect(110, 10, 200, 20), "Day " + (currentDay+1));
GUI.Label(new Rect(30, 50, 200, 20), "Time Spent: " + (int)timeSpent);
GUI.Label(new Rect(30, 75, 200, 20), "Budget Remaining: " + budget);
GUI.Label(new Rect(30, 100, 200, 20), "Budget Spent this day: " + Player.Instance.SpentMoney);
GUI.Label(new Rect(30, 125, 200, 20), "Best solution's budget: " + TSPSolver.calculateCost(CurrentDay.Solution, CurrentDay.TspCase));
if (currentDay+1 >= daysPerLevel){
if(GUI.Button(new Rect(75, 180, 100, 50), "Continue")){
//show level report screen
onDayReportScreen=false;
onLevelReportScreen=true;
}
} else {
if(GUI.Button(new Rect(75, 180, 100, 50), "Next Day")){
Player.Instance.NextLevel();
onDayReportScreen=false;
}
}
GUI.EndGroup();
}
float countdownTimer = timePerDay - Time.timeSinceLevelLoad;
if(countdownTimer <= 0){
lostLevel=true;
}
double money = budget - Player.Instance.SpentMoney;
GUI.Label(new Rect(Screen.width/20, 0, Screen.width/4, Screen.height/10), botones[0]);
GUI.Label(new Rect(Screen.width/10, Screen.height/80 ,Screen.width/4,Screen.height/10),((int)countdownTimer) / 60 + ":" + ((int)countdownTimer) % 60);
GUI.Label(new Rect(Screen.width/20+Screen.width/3, 0, Screen.width/4, Screen.height/10), botones[1]);
GUI.Label(new Rect(Screen.width/10+Screen.width/3,Screen.height/80,Screen.width/4,Screen.height/10),(int)money + "");
GUI.Label(new Rect(Screen.width/20+2*Screen.width/3, 0, Screen.width/4, Screen.height/10), botones[2]);
GUI.Label(new Rect(Screen.width/10+2*Screen.width/3,Screen.height/80,Screen.width/4,Screen.height/10), (currentDay+1) + "");
}
}
}
|
using System;
namespace Uintra.Features.Navigation.Models
{
public class TopNavigationExtendedViewModel : TopNavigationViewModel
{
public Uri UintraDocumentationLink { get; set; }
public Version UintraDocumentationVersion { get; set; }
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DATN_Hoa_Yambi.Controllers
{
public class NhapLieuController : Controller
{
// GET: NhapLieu
public ActionResult Index()
{
if (Session["User"]!=null)
{
return View();
}
else
{
return RedirectToAction("Index", "User");
}
}
[HttpPost]
public string getdataTaiTrong()
{
VuVanHoa_DatabaseDataContext db = new VuVanHoa_DatabaseDataContext();
var qr_user = db.tbl_Users.Where(o => o.MaNguoiDung == Session["User"].ToString()).SingleOrDefault();
return JsonConvert.SerializeObject(qr_user);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FailureSimulator.Core.Graph;
using FailureSimulator.Core.PathAlgorithms;
using FailureSimulator.Core.Simulator;
namespace FailureSimulator.Console
{
class Program
{
static void Main(string[] args)
{
var graph = new Graph();
var v1 = graph.AddVertex(new Vertex("v1", 0));
var v2 = graph.AddVertex(new Vertex("v2", 0));
graph.AddVertex(new Vertex("v3", 0));
graph.AddVertex(new Vertex("v4", 0));
graph.AddEdge("v1", "v3", 0.00);
graph.AddEdge("v1", "v4", 0.00);
graph.AddEdge("v3", "v2", 0.00);
graph.AddEdge("v4", "v2", 0.00);
var sim = new Simulator(new DfsPathFinder());
var report = sim.Simulate(graph, v1, v2, SimulationSettings.Default);
PrintValue("Min fail time", report.MinFailureTime);
PrintValue("Max fail time", report.MaxFailureTime);
PrintValue("Average fail time", report.AverageFailureTime);
PrintValueNA("Average repair time");
PrintValueNA("Availability rate");
System.Console.WriteLine("Pathes:");
foreach (var path in report.Pathes)
{
for(int i = 0; i < path.Count - 1; i++)
System.Console.Write(path[i].Name + " -> ");
System.Console.WriteLine(path.Last().Name);
}
System.Console.WriteLine("Failure bar chart:");
foreach (var point in report.FailureBarChart)
{
System.Console.WriteLine($"{point.X,-10:0.###} {point.Y}");
}
PrintValueNA("Repair bar chart");
PrintValueNA("Time diagram");
}
static void PrintValue(string name, double value)
{
System.Console.WriteLine("{0,-20}: {1:0.###}", name, value);
}
static void PrintValueNA(string name)
{
System.Console.WriteLine("{0,-20}: N/A", name);
}
}
}
|
namespace Ejercicio
{
public class ChicoBestia : Titan
{
string color;
public ChicoBestia(int tristeza) : base(tristeza)
{
this.color = "Verde";
}
public int NivelDeTristeza(){
return tristeza;
}
public void cambiarDeColor(string color){
this.color = color;
tristeza += 4;
}
public override void comerPizza() => color = "Amarillo patito fluorescente de las montañas del himalaya amazonico";
public override void llorarPorRobocop(){
if(tristeza > 7) tristeza -= 8;
else tristeza -= tristeza;
}
public override bool estaTriste(){
return tristeza > 5;
}
public override int poder(){
return color.Length * 13;
}
}
} |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using PaperPlane.TLTranslator.Compiler;
using PaperPlane.TLTranslator.Compiler.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace PaperPlane.TLTranslator
{
class Program
{
static void Main(string[] args)
{
var parser = new TLDocParser();
var combinators =
parser.ParseCurrentSchema(
@"C:\Users\cankr\Documents\GitHub\paperplane\PaperPlane.TLTranslator\Compiler\Schema.tl");
var types = combinators.OfType<TypeCombinator>();
var functions = combinators.OfType<FunctionCombinator>();
var namespaces = new List<NamespaceDeclarationSyntax>();
foreach (var namespaceGroup in types.GroupBy(t => t.Namespace))
{
var members = new List<MemberDeclarationSyntax>();
foreach (var type in namespaceGroup
.GroupBy(g => g.ClassName)
.Where(g => g.Count() == 1)
.Select(g => g.First()))
{
members.Add(SyntaxHelper.CreateClass(
SyntaxHelper.ToCamelCase(type.ClassName),
new[] { SyntaxHelper.CreateConstructorId(type.ConstructorId) },
type.Args.Select(a =>
SyntaxHelper.CreateProperty(
SyntaxHelper.ToCamelCase(a.Name),
SyntaxHelper.ReplaceType(types, a.Type, out IEnumerable<AttributeSyntax> attrs),
asPublic: true,
attributes: attrs)),
new[] { "TLGenericObject" }));
}
foreach (var typeGroup in namespaceGroup
.GroupBy(g => g.ClassName)
.Where(g => g.Count() > 1))
{
var typeMembers = typeGroup
.SelectMany(t => t.Args)
.GroupBy(a => a.Name);
members.Add(SyntaxHelper.CreateClass(
SyntaxHelper.ToCamelCase(typeGroup.Key),
Enumerable.Empty<AttributeSyntax>(),
typeMembers.SelectMany(g =>
g.GroupBy(a => a.Type).Count() == 1 ?
new[] {
SyntaxHelper.CreateProperty(
SyntaxHelper.ToCamelCase(g.First().Name),
SyntaxHelper.ReplaceType(types, g.First().Type, out IEnumerable<AttributeSyntax> attrs),
asPublic: true,
attributes: attrs)
} :
g.Select(a => SyntaxHelper.CreateProperty(
"I" + SyntaxHelper.ToCamelCase(a.ConstructorName) + "." + SyntaxHelper.ToCamelCase(a.Name),
SyntaxHelper.ReplaceType(types, a.Type, out IEnumerable<AttributeSyntax> attrs2),
asPublic: false,
attributes: attrs2))
),
new[] { "TLGenericPolymorph" }.Union(typeGroup.Select(t => "I" + SyntaxHelper.ToCamelCase(t.ConstructorName)))));
foreach (var type in typeGroup)
{
members.Add(
SyntaxHelper.CreateInterface(
"I" + SyntaxHelper.ToCamelCase(type.ConstructorName),
new[] { SyntaxHelper.CreateConstructorId(type.ConstructorId) },
type.Args.Select(a => SyntaxHelper.CreateProperty(
SyntaxHelper.ToCamelCase(a.Name),
SyntaxHelper.ReplaceType(types, a.Type, out IEnumerable<AttributeSyntax> attrs),
asPublic: false)))
);
}
}
namespaces.Add(
NamespaceDeclaration(IdentifierName("PaperPlane.API.ProtocolSchema.DataTypes." + SyntaxHelper.ToCamelCase(namespaceGroup.Key ?? "Common")))
.WithMembers(List(members)));
}
var unit = CompilationUnit()
.WithMembers(List<MemberDeclarationSyntax>(namespaces))
.WithUsings(List(new[] {
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.Collections.Generic")),
UsingDirective(IdentifierName("PaperPlane.API.ProtocolSchema.Base")),
UsingDirective(IdentifierName("PaperPlane.API.ProtocolSchema.Internal"))
}))
.NormalizeWhitespace();
File.WriteAllText(@"C:\Users\cankr\Documents\GitHub\paperplane\PaperPlane.API\ProtocolSchema\DataTypes\GeneratedTypes.cs", unit.ToString());
namespaces = new List<NamespaceDeclarationSyntax>();
foreach (var namespaceGroup in functions.GroupBy(t => t.Namespace))
{
var members = new List<MemberDeclarationSyntax>();
foreach (var function in namespaceGroup)
{
var returnType = SyntaxHelper.ReplaceType(types, function.ReturnTypeName, out IEnumerable<AttributeSyntax> attrs2, "DT.");
if (returnType == "bool")
returnType = "DT.Common.Bool";
if (returnType.StartsWith("List<"))
returnType = returnType.Replace("List<", "TLVector<");
members.Add(SyntaxHelper.CreateClass(
SyntaxHelper.ToCamelCase(function.ConstructorName),
new[] { SyntaxHelper.CreateConstructorId(function.ConstructorId) },
function.Args.Select(a =>
SyntaxHelper.CreateProperty(
SyntaxHelper.ToCamelCase(a.Name),
SyntaxHelper.ReplaceType(types, a.Type, out IEnumerable<AttributeSyntax> attrs, "DT."),
asPublic: true,
attributes: attrs)),
new[] { $"TLMethod<{returnType}>" } ));
}
namespaces.Add(
NamespaceDeclaration(IdentifierName("PaperPlane.API.ProtocolSchema.Methods." + SyntaxHelper.ToCamelCase(namespaceGroup.Key ?? "Common")))
.WithMembers(List(members)));
}
unit = CompilationUnit()
.WithMembers(List<MemberDeclarationSyntax>(namespaces))
.WithUsings(List(new[] {
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.Collections.Generic")),
UsingDirective(IdentifierName("PaperPlane.API.ProtocolSchema.Base")),
UsingDirective(IdentifierName("PaperPlane.API.ProtocolSchema.Internal")),
UsingDirective(NameEquals("DT"), IdentifierName("PaperPlane.API.ProtocolSchema.DataTypes"))
}))
.NormalizeWhitespace();
File.WriteAllText(@"C:\Users\cankr\Documents\GitHub\paperplane\PaperPlane.API\ProtocolSchema\Methods\GeneratedFunctions.cs", unit.ToString());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MvvmCross.Platform;
using MvvmCross.Plugins.Location;
using MvvmCross.Plugins.Messenger;
namespace ResidentAppCross.Services
{
public class LocationService
: ILocationService
{
private readonly IMvxLocationWatcher _watcher;
private readonly IMvxMessenger _messenger;
private MvxSubscriptionToken _token;
public LocationService(IMvxLocationWatcher watcher, IMvxMessenger messenger)
{
_watcher = watcher;
_messenger = messenger;
_token = messenger.Subscribe<StartLocationServices>(OnStart);
}
private void OnStart(StartLocationServices obj)
{
}
private void OnLocation(MvxGeoLocation location)
{
if (!_messenger.HasSubscriptionsFor<LocationMessage>()) return;
var message = new LocationMessage(this,
location.Coordinates.Latitude,
location.Coordinates.Longitude
);
_messenger.Publish(message);
}
private void OnError(MvxLocationError error)
{
Mvx.Error("Seen location error {0}", error.Code);
}
public bool Started = false;
public void Start()
{
if (Started) return;
_token?.Dispose();
Started = true;
_watcher.Start(new MvxLocationOptions(), OnLocation, OnError);
}
}
public interface ILocationService
{
void Start();
}
public class StartLocationServices : MvxMessage
{
public StartLocationServices(object sender) : base(sender)
{
}
}
public class LocationMessage : MvxMessage
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public LocationMessage(LocationService locationService, double latitude, double longitude) : base(locationService)
{
Latitude = latitude;
Longitude = longitude;
}
}
}
|
using Library.API.Configurations;
using Library.API.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Library.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers(configure =>
{
configure.Filters.Add<JsonExceptionFilter>();
// 对于请求不支持的数据格式返回406
configure.ReturnHttpNotAcceptable = true;
// configure.OutputFormatters.Add(new XmlSerializerOutputFormatter()); // 仅支持输出xml格式
configure.CacheProfiles.AddCacheProfiles();
// 控制器访问添加认证
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
configure.Filters.Add(new AuthorizeFilter(policy));
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
})
.AddXmlSerializerFormatters();
// 数据库上下文
services.AddDatabaseConfiguration(Configuration);
// 认证
services.AddAuthenticationConfiguration(Configuration);
// 数据保护API
services.AddDataProtection();
// AutoMapper
services.AddAutoMapperConfiguration();
// 服务器缓存
services.AddResponseCachingConfiguration();
// 内存缓存
services.AddMemoryCacheConfiguration();
// Redis缓存
services.AddRedisCacheConfiguration(Configuration);
// 注入服务
services.AddDependencyInjectionConfiguration();
// Swagger
services.AddSwaggerConfiguration();
// 版本控制
services.AddApiVersioningConfiguration();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseResponseCachingSetup();
app.UseMiddleware<RequestRateLimitingMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwaggerSetup();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Author: Nathan Hales
/// Edited by Jospeh K.
/// Attached to trigger boxs hazard in the clock tower level this script sends its data to the Angel boss and gets turned on during one of its attacks.
/// Its a timer based activation that waits to be called by the boss.
/// </summary>
public class ElectricPlatform : MonoBehaviour
{
[HideInInspector] public bool canStun = true;
[HideInInspector] public bool noBlock = false;
[HideInInspector] public float stunTime = 1;
[HideInInspector]public float timer = 1.5f, DamageTimer = 0.05f;
[HideInInspector] public int _damage;
private float timeKeeper;//Ticks up with time for threshold checks.
private bool damagePause = false;//Pauses the damage
private CameraTargetController _cameraTargetController;
void Start () {
HelloAngel();
_cameraTargetController = GameObject.FindObjectOfType<CameraTargetController>();
//Turn your self off.
gameObject.SetActive(false);
}
void Update ()
{
if(timeKeeper > 0f) {timeKeeper -= Time.deltaTime;} //count Down
else{ gameObject.SetActive(false); }//Turn your gameobject off.
}
void OnDisable()
{
//reset time keeper to the amount of time in the timer;
timeKeeper = timer;
damagePause = false;
StopAllCoroutines();
}
void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player"))
{
if (!damagePause && IsPC(other))
{
Health _health = other.transform.parent.parent.GetComponent<Health>();
StartCoroutine(dealDamage(_health, other.transform.position));
}
}
}
IEnumerator dealDamage(Health playerHealth, Vector3 playerPos)
{
Vector3 dmgDir = transform.position - playerPos;
playerHealth.TakeDamage( _damage, canStun, stunTime, dmgDir, false);
damagePause = true;
yield return new WaitForSeconds(DamageTimer);
damagePause = false;
}
/// <summary>
/// Checks to see if the collider belongs to a character currently controlled by the player.
/// </summary>
/// <param name="characteCollider"></param>
/// <returns></returns>
bool IsPC(Collider characteCollider)
{
if(_cameraTargetController.controlledChar == 0 && characteCollider.transform.parent.parent.gameObject.name == "Sondra")
return false;
else if (_cameraTargetController.controlledChar == 1 && characteCollider.transform.parent.parent.gameObject.name == "Wolf")
return false;
else return true;
}
void HelloAngel()
{
Angel_AI myBoss = GameObject.FindObjectOfType<Angel_AI>(); //find the angel's AI
myBoss._electricPlatforms.Add(this.GetComponent<ElectricPlatform>()); //store a refference to yourself with the boss AI
//Get your stats from the boss
canStun = myBoss.ePlatformCanStun;
stunTime = myBoss.ePlatformStunTime;
noBlock = myBoss.ePlatformNoBlock;
timer = myBoss.ePlatformTimer;
DamageTimer = myBoss.ePlatformDamageTimer;
_damage = myBoss.ePlatformDamage;
timeKeeper = timer;
}
}
|
using UnityEngine;
using System.Collections;
using MoreMountains.Tools;
namespace MoreMountains.CorgiEngine
{
/// Moving platform extension with Moving Away feature.
/// Intended for Corgi Engine v6.2.1+
/// v 1.0 - Muppo (2020)
public class MoveAwayPlatform : MovingPlatform
{
protected override void Start()
{
base.Start();
CycleOption = CycleOptions.StopAtBounds;
StartMovingWhenPlayerIsColliding = true;
}
protected override void ExecuteUpdate ()
{
if(PathElements == null || PathElements.Count < 1 || _endReached || !CanMove)
{ return; }
// Check if platform should hide or unhide
if(_collidingWithPlayer == true)
{
MoveAway();
}
else if(_currentIndex <= 0)
{
RestorePosition();
}
Move ();
}
public override void OnTriggerEnter2D(Collider2D collider)
{
base.OnTriggerEnter2D(collider);
ResetEndReached();
}
public virtual void MoveAway()
{
if (CycleOption == CycleOptions.StopAtBounds)
CycleOption = CycleOptions.BackAndForth;
}
public virtual void RestorePosition()
{
if (CycleOption == CycleOptions.BackAndForth)
CycleOption = CycleOptions.StopAtBounds;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BO.Constates;
using TO;
using System.Drawing;
using BO;
namespace Web.Cadastros
{
public partial class Usuarios : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Usuario"] == null)
{
Session["PaginaAnterior"] = "~/Cadastros/Usuario/Usuarios.aspx";
Response.Redirect("~/Login.aspx");
}
else
{
string[] usuario = Session["Usuario"].ToString().Split('|');
int codigo = Convert.ToInt32(usuario[0]);
if (usuario[2] != TipoUsuario.ADMINISTRADOR.ToString())
{
Response.Redirect("~/AcessoNegado.aspx");
}
}
lblMsg.Text = string.Empty;
}
private void MostrarCamposCadastro()
{
fvwUsuarios.Visible = true;
LblTitulo.Text = "Cadastro de Usuário";
gvwUsuarios.Visible = false;
txtFiltro.Visible = false;
BtnFiltrar.Visible = false;
lblFiltro.Visible = false;
lblstatus.Visible = false;
ddlStatus.Visible = false;
}
private void MostrarCamposConsulta()
{
gvwUsuarios.SelectedIndex = -1;
gvwUsuarios.Visible = true;
txtFiltro.Visible = true;
lblstatus.Visible = true;
ddlStatus.Visible = true;
BtnFiltrar.Visible = true;
lblFiltro.Visible = true;
LblTitulo.Text = "Usuários";
fvwUsuarios.Visible = false;
}
protected void gvwUsuarios_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ReiniciarSenha")
{
try
{
if (UsuarioBO.ReiniciarSenha(Convert.ToInt32(e.CommandArgument)) > 0)
{
lblMsg.Text = "Senha reiniciada com sucesso";
lblMsg.ForeColor = Color.Green;
}
else
{
lblMsg.Text = "O usuário foi removido por outro usuário";
lblMsg.ForeColor = Color.Red;
}
gvwUsuarios.DataBind();
}
catch (Exception ex)
{
lblMsg.Text = "Falha ao reiniciar a Senha do usuário";
lblMsg.ForeColor = Color.Red;
}
}
}
protected void gvwUsuarios_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblstatus = ((Label)e.Row.FindControl("lblStatus"));
if (lblstatus.Text == "A")
{
lblstatus.Text = "Ativo";
}
else if (lblstatus.Text == "I")
{
lblstatus.Text = "Inativo";
}
Label lbltipo = ((Label)e.Row.FindControl("lblTipo"));
int tipo = Convert.ToInt32(lbltipo.Text);
if (tipo == BO.Constates.TipoUsuario.ADMINISTRADOR)
{
lbltipo.Text = "Administrador";
}
else if (tipo == BO.Constates.TipoUsuario.ADMINISTRADOR)
{
lbltipo.Text = "Administrador";
}
else if (tipo == BO.Constates.TipoUsuario.GERENTE_PROJETO)
{
lbltipo.Text = "Gerente";
}
else if (tipo == BO.Constates.TipoUsuario.ANALISTA)
{
lbltipo.Text = "Analista";
}
else if (tipo == BO.Constates.TipoUsuario.LIDER)
{
lbltipo.Text = "Lider";
}
else if (tipo == BO.Constates.TipoUsuario.CLIENTE)
{
lbltipo.Text = "Cliente";
}
else if (tipo == BO.Constates.TipoUsuario.DESENVOLVEDOR)
{
lbltipo.Text = "Desenvolvedor";
}
else if (tipo == BO.Constates.TipoUsuario.TESTADOR)
{
lbltipo.Text = "Testador";
}
else if (tipo == BO.Constates.TipoUsuario.GERENTE_DESENVOLVEDOR)
{
lbltipo.Text = "Gerente de Desenvolvimento";
}
else if (tipo == BO.Constates.TipoUsuario.GERENTE_CONTRATO)
{
lbltipo.Text = "Gerente de Contrato";
}
}
}
protected void gvwUsuarios_SelectedIndexChanged(object sender, EventArgs e)
{
MostrarCamposCadastro();
LblTitulo.Text = "Atualizar Usuário";
fvwUsuarios.ChangeMode(FormViewMode.Edit);
}
protected void BtnCadastrar_Click(object sender, ImageClickEventArgs e)
{
MostrarCamposCadastro();
fvwUsuarios.ChangeMode(FormViewMode.Insert);
}
protected void BtnCancelar_Click(object sender, EventArgs e)
{
fvwUsuarios.ChangeMode(FormViewMode.ReadOnly);
MostrarCamposConsulta();
}
protected void fvwUsuarios_ItemInserted(object sender, FormViewInsertedEventArgs e)
{
if (e.Exception != null && e.Exception.InnerException is ApplicationException)
{
e.ExceptionHandled = true;
e.KeepInInsertMode = true;
lblMsg.Text = e.Exception.InnerException.Message;
lblMsg.ForeColor = Color.Red;
}
else
{
lblMsg.Text = "Usuário cadastrado com sucesso";
lblMsg.ForeColor = Color.Green;
MostrarCamposConsulta();
gvwUsuarios.DataBind();
}
}
protected void fvwUsuarios_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
{
if (e.Exception != null && e.Exception.InnerException is ApplicationException)
{
e.ExceptionHandled = true;
e.KeepInEditMode = true;
}
}
protected void OdsFvwUsuario_Updated(object sender, ObjectDataSourceStatusEventArgs e)
{
if (e.Exception != null && e.Exception.InnerException is ApplicationException)
{
e.ExceptionHandled = true;
lblMsg.Text = e.Exception.InnerException.Message;
lblMsg.ForeColor = Color.Red;
}
else
{
if (Convert.ToInt32(e.ReturnValue) < 1)
{
lblMsg.Text = "Usuário removido por outro usuário";
lblMsg.ForeColor = Color.Red;
}
else
{
lblMsg.Text = "Usuário atualizado com sucesso";
lblMsg.ForeColor = Color.Green;
}
MostrarCamposConsulta();
gvwUsuarios.DataBind();
}
}
protected void OdsConsulta_Deleted(object sender, ObjectDataSourceStatusEventArgs e)
{
if (e.Exception != null && e.Exception.InnerException is ApplicationException)
{
e.ExceptionHandled = true;
lblMsg.Text = e.Exception.InnerException.Message;
lblMsg.ForeColor = Color.Red;
}
else
{
lblMsg.Text = "Usuário removido com sucesso";
lblMsg.ForeColor = Color.Green;
MostrarCamposConsulta();
gvwUsuarios.DataBind();
}
}
protected void cvLogin_ServerValidate(object source, ServerValidateEventArgs args)
{
string login = ((TextBox)fvwUsuarios.FindControl("txtLogin")).Text;
if (UsuarioBO.VerificarLogin(login))
{
lblMsg.Text = "Login já cadastrado";
lblMsg.ForeColor = Color.Red;
args.IsValid = false;
}
}
protected void fvwUsuarios_PreRender(object sender, EventArgs e)
{
if (fvwUsuarios.CurrentMode == FormViewMode.Edit)
{
DropDownList ddl = ((DropDownList)fvwUsuarios.FindControl("ddlTipoUsuario"));
if (ddl.SelectedValue == TipoUsuario.ANALISTA.ToString() || ddl.SelectedValue == TipoUsuario.LIDER.ToString() || ddl.SelectedValue == TipoUsuario.TESTADOR.ToString())
{
((Panel)fvwUsuarios.FindControl("pnlProducao")).Visible = true;
}
else
{
((Panel)fvwUsuarios.FindControl("pnlProducao")).Visible = false;
}
}
}
}
} |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Collections;
public class Oyunyoneticisi : MonoBehaviour {
[SerializeField]
private Sprite bgImage;
public Sprite[] puzzles;
private bool firstGuess;
private bool secondGuess;
private int countGuess;
private int countCurrentGuess;
private int countWrongGuess;
private int firstGuessIndex;
private int secondGuessIndex;
private int gameGuess;
private string firstGuessPuzzle;
private string secondGuessPuzzle;
public Text t;
public List<Sprite> gamePuzzles = new List<Sprite>();
public List<Button> btns = new List<Button>();
void Start()
{
GetButtons();
AddListeners();
AddGamePuzzles();
Shuffle(gamePuzzles);
gameGuess = gamePuzzles.Count/2;
}
void GetButtons()
{
GameObject [] objects = GameObject.FindGameObjectsWithTag ("PuzzleButton");
for (int i = 0; i < objects.Length; i++)
{
btns.Add(objects[i].GetComponent<Button>());
btns[i].image.sprite = bgImage;
}
}
void AddListeners()
{
foreach(Button btn in btns)
{
btn.onClick.AddListener(()=>PickAllPuzzle());
}
}
void AddGamePuzzles()
{
int looper = btns.Count;
int index = 0;
for (int i = 0; i < looper; i++)
{
if (index == looper / 2)
{
index = 0;
}
gamePuzzles.Add(puzzles[index]);
index++;
}
}
public void PickAllPuzzle()
{
string name = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name;
if (!firstGuess)
{
firstGuess = true;
firstGuessIndex = int.Parse(UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name);
firstGuessPuzzle = gamePuzzles[firstGuessIndex].name;
btns[firstGuessIndex].image.sprite = gamePuzzles[firstGuessIndex];
}
else if (!secondGuess)
{
secondGuess = true;
secondGuessIndex = int.Parse(UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name);
secondGuessPuzzle = gamePuzzles[secondGuessIndex].name;
btns[secondGuessIndex].image.sprite = gamePuzzles[secondGuessIndex];
StartCoroutine(CheckIfThePuzzleMacth());
}
}
IEnumerator CheckIfThePuzzleMacth()
{
yield return new WaitForSeconds(1f);
if (firstGuessPuzzle == secondGuessPuzzle)
{
yield return new WaitForSeconds(.5f);
btns[firstGuessIndex].interactable = false;
btns[secondGuessIndex].interactable = false;
btns[firstGuessIndex].image.color = new Color(0, 0, 0, 0);
btns[secondGuessIndex].image.color = new Color(0, 0, 0, 0);
checkIfTheGameFinished();
}
else
{
btns[firstGuessIndex].image.sprite = bgImage;
btns[secondGuessIndex].image.sprite = bgImage;
countWrongGuess++;
if (countWrongGuess == 5)
{
Invoke("SceneMang", 2);
t.text = "Kaybettin";
}
}
yield return new WaitForSeconds(.5f);
firstGuess = secondGuess = false;
}
void checkIfTheGameFinished()
{
countCurrentGuess++;
if (countCurrentGuess==gameGuess)
{
t.text = "Kazandın";
Invoke("SceneMang", 2);
}
}
void SceneMang()
{
SceneManager.LoadScene("anamenu");
}
void Shuffle(List<Sprite> list)
{
for(int i = 0; i < list.Count; i++)
{
Sprite temp = list[i];
int randomindex = Random.Range(0, list.Count);
list[i] = list[randomindex];
list[randomindex] = temp;
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WorldNomads.Utility;
namespace WorldNomads.UnitTest
{
[TestClass]
public class GetEvenNumbers
{
[TestMethod]
public void GetEvenNumbers_Negative()
{
var result = IntegerParser.GetEvenNumbers(-100);
Assert.AreEqual(string.Empty, result);
}
[TestMethod]
public void GetEvenNumbers_Zero()
{
var result = IntegerParser.GetEvenNumbers(0);
Assert.AreEqual("0", result);
}
[TestMethod]
public void GetEvenNumbers_Positive()
{
var result = IntegerParser.GetEvenNumbers(300);
var array = result.Split(',');
Assert.AreEqual(151, array.Length);
Assert.AreEqual("0", array[0]);
Assert.AreEqual("300", array[150]);
}
}
}
|
using Discord.Commands;
using Discord.WebSocket;
using System.Threading.Tasks;
namespace CutieBox.Commands
{
[Group("cute")]
public class Cute : ModuleBase
{
[Command]
public Task ExecuteAsync()
=> ReplyAsync(string.Format("{0} is a big cutie!", Context.User.Mention));
}
}
|
using HTB.v2.intranetx.util;
namespace HTB.v2.intranetx.permissions
{
public class PermissionsRoutePlanner
{
public bool GrantRoutePlannerForAll { get; set; }
public bool GrantRoutePlannerForSelfOnly { get; set; }
public PermissionsRoutePlanner()
{
GrantRoutePlannerForAll = false;
GrantRoutePlannerForSelfOnly = false;
}
public void LoadPermissions(int userId)
{
GrantRoutePlannerForAll = GlobalUtilArea.Rolecheck(413, userId);
GrantRoutePlannerForSelfOnly = GlobalUtilArea.Rolecheck(412, userId);
}
}
} |
namespace MySurveys.Web.Areas.Administration.ViewModels
{
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using AutoMapper;
using Base;
using Models;
using MvcTemplate.Web.Infrastructure.Mapping;
public class QuestionViewModel : AdministrationViewModel, IMapFrom<Question>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Required]
[StringLength(50), MinLength(3)]
[UIHint("CustomString")]
public string Content { get; set; }
[Display(Name = "Survey Title")]
[HiddenInput(DisplayValue = false)]
public string SurveyTitle { get; set; }
[Display(Name = "Parent")]
[UIHint("CustomString")]
public string ParentContent { get; set; }
[Display(Name = "Total Answers")]
[HiddenInput(DisplayValue = false)]
public int TotalPossibleAnswers { get; set; }
[Display(Name = "Is Dynamic?")]
[HiddenInput(DisplayValue = false)]
public bool IsDependsOn { get; set; }
public void CreateMappings(IMapperConfiguration configuration)
{
configuration.CreateMap<Question, QuestionViewModel>()
.ForMember(s => s.SurveyTitle, opt => opt.MapFrom(q => q.Survey.Title))
.ForMember(s => s.TotalPossibleAnswers, opt => opt.MapFrom(a => a.PossibleAnswers.Count))
.ReverseMap();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoundedNPC : MonoBehaviour {
//Movement script for NPC with bounds in HubLevel
private Vector3 directionVector;
private Transform myTransform;
public float speed;
private Rigidbody2D myRigidbody;
private Animator myAnim;
public Collider2D bounds;
private bool isMoving; //Is the NPC moving
public bool playerInRange;
public float minMoveTime;
public float maxMoveTime;
private float moveTimeSeconds;
public float minWaitTime;
public float maxWaitTime;
private float waitTimeSeconds;
// Use this for initialization
void Start () {
moveTimeSeconds = Random.Range(minMoveTime, maxMoveTime);
waitTimeSeconds = Random.Range(minWaitTime, maxWaitTime);
myTransform = GetComponent<Transform>();
myRigidbody = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
ChangeDirection();
}
// Update is called once per frame
void Update () {
if (isMoving)
{
moveTimeSeconds -= Time.deltaTime;
if (moveTimeSeconds <= 0)
{
moveTimeSeconds = Random.Range(minMoveTime, maxMoveTime);
isMoving = false;
}
if (!playerInRange)
{
Move();
}
}
else
{
waitTimeSeconds -= Time.deltaTime;
if(waitTimeSeconds <= 0)
{
ChooseDifferentDirection();
isMoving = true;
waitTimeSeconds = Random.Range(minWaitTime, maxWaitTime);
}
}
}
private void ChooseDifferentDirection() //Make direction appear to be more random
{
Vector3 temp = directionVector;
ChangeDirection();
int loops = 0;
while (temp == directionVector && loops < 100)
{
loops++; //Dont get into an infinite loop
ChangeDirection(); //Change direction
}
}
private void Move() //Move the NPC
{
Vector3 temp = myTransform.position + directionVector * speed * Time.deltaTime;
if (bounds.bounds.Contains(temp))
{
myRigidbody.MovePosition(temp);
}
else
{
ChangeDirection();
}
}
void ChangeDirection() //Change the direction by using 4 different cases, one for each direction
{
int direction = Random.Range(0, 4);
switch (direction)
{
case 0:
//Walking right
directionVector = Vector3.right;
break;
case 1:
//walking up
directionVector = Vector3.up;
break;
case 2:
//Walking left
directionVector = Vector3.left;
break;
case 3:
//walking down
directionVector = Vector3.down;
break;
default:
break;
}
UpdateAnimation();
}
void UpdateAnimation()
{
myAnim.SetFloat("moveX", directionVector.x);
myAnim.SetFloat("moveY", directionVector.y);
}
private void OnCollisionEnter2D(Collision2D other) //If NPC collides start moving again in different direction
{
ChooseDifferentDirection();
}
private void OnTriggerEnter2D(Collider2D other) //If colliding with player then player in range = true
{
if (other.CompareTag("Player") && other.isTrigger)
{
playerInRange = true;
}
}
private void OnTriggerExit2D(Collider2D other) //When player isnt in range anymore
{
if (other.CompareTag("Player") && other.isTrigger)
{
playerInRange = false;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class InputStyring : MonoBehaviour
{
public bool Keyboard = true;
private RaycastHit hit;
private bool mouseDown = false;
private int floorMask;
public static InputStyring Instance
{
get;
private set;
}
void Awake()
{
Instance = this;
floorMask = LayerMask.GetMask("Gulv");
}
void FixedUpdate()
{
#if UNITY_EDITOR || UNITY_WEBPLAYER || UNITY_STANDALONE
if (Keyboard)
CheckKeyboard();
else
CheckMouse();
#endif
#if UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8 || UNITY_BLACKBERRY
CheckTouch();
#endif
}
void Tap(Vector3 position)
{
Ray ray = Camera.main.ScreenPointToRay(position);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100.0F, floorMask))
{
//Debug.DrawLine(ray.origin, hit.point, Color.red, 10);
KarakterStyring.Instance.Bevæg(KarakterStyring.Instance.RetningTilMål(hit.point));
}
}
void CheckMouse()
{
if (Input.GetMouseButton(0) && mouseDown == false)
{
Click();
mouseDown = true;
}
else if (Input.GetMouseButton(0))
{
Tap(Input.mousePosition);
}
else if (!Input.GetMouseButton(0))
{
mouseDown = false;
}
}
void CheckTouch()
{
if (Input.touchCount == 1)
{
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
Click();
}
}
if (Input.touchCount > 0)
{
Touch touch = Input.touches[0];
if (touch.deltaTime == 0.0)
{
return;
}
Tap(touch.position);
}
}
void CheckKeyboard()
{
// Store the input axes.
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
// Move the player around the scene.
KarakterStyring.Instance.Bevæg (new Vector3(h, v, 0));
}
void Click()
{
//do something with mouseclick
}
} |
using System;
using System.Reflection;
namespace ITVDN_Reflections
{
class Program
{
static void Main(string[] args)
{
Race race = new Race();
Console.WriteLine(race.Armor);
Console.WriteLine(new string ('_', 35));
//race.armor = "Hello"; // не получится так как Armor нет сеттера только геттер.
// Чтобы достучаться до этого поля нам необходимо преминить РЕФЛЕКСИЮ.
// Любая работа с пефлексией начинается с получение экземпляра класса TYPE для нашего типа
// с которым мы хотим работать.
// Поэтому.
// Получаем тип.
var type = race.GetType();
// Далее чтобы обратиться к скрытым полям и свойсвам.
// здесь мы во флагах указываем что это экземплярное поле и оно не открыто.
var field = type.GetField("armor", BindingFlags.Instance | BindingFlags.NonPublic);
field.SetValue(race, "46 попугаев защиты");
Console.WriteLine(race.Armor);
// Но по сути его так никто не использует.
//--------------------------------------------------------------------------------
//Достал тип объекта -> его свойства -> вывел на экран
Console.WriteLine(new string ('_', 35));
var now = DateTime.Now;
type = now.GetType();
var properies = type.GetProperties();
foreach (var item in properies)
{
Console.WriteLine($"{item.Name} - {item.GetValue(now)}");
}
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DATN_Hoa_Yambi.Controllers
{
public class NhapLieuCocController : Controller
{
// GET: NhapLieuCoc
public ActionResult Index()
{
return View();
}
[HttpPost]
public string NhapLieuCoc()
{
string macoc = Request["txt_ma_coc"];
string tencoc = Request["txt_ten_coc"];
double dodaicoc = double.Parse(Request["txt_do_dai_coc"]);
double dk_coc = double.Parse(Request["txt_duong_kinh_coc"]);
double sothanh = double.Parse(Request["txt_so_thanh_thep"]);
double dk_thep = double.Parse(Request["txt_duong_kinh_thep_coc"]);
int ID_betong = int.Parse(Request["cbb_betong"]);
int ID_cotthep = int.Parse(Request["cbb_cotthep"]);
dk_thep = dk_thep / 10; // đổi đơn vị ra cm
// Tính As coc :
double As_coc = (Math.PI * Math.Pow(dk_thep, 2)) / 4 * sothanh;
// Tính Fa <Diện tích tiết diện cọc:>
double Fa_coc = Math.Pow(dk_coc, 2) * 10000; // đổitừ m2 ra cm2
VuVanHoa_DatabaseDataContext db = new VuVanHoa_DatabaseDataContext();
tbl_betong bt = db.tbl_betongs.Where(o => o.id_betong == ID_betong).FirstOrDefault();
tbl_cot_thep ct = db.tbl_cot_theps.Where(x => x.IDCotThep == ID_cotthep).FirstOrDefault();
double? Pvl = 0.9 * (Fa_coc * bt.rb / 10 + As_coc * ct.Rsc / 10); // chia 10 để đổi đơn vị sang cm
Pvl = Math.Round((double)Pvl);
return Pvl.ToString();
}
[HttpPost]
public String AddNewCoc()
{
string macoc = Request["txt_ma_coc"];
string tencoc = Request["txt_ten_coc"];
double dodaicoc = double.Parse(Request["txt_do_dai_coc"]);
double dk_coc = double.Parse(Request["txt_duong_kinh_coc"]);
double sothanh = double.Parse(Request["txt_so_thanh_thep"]);
double dk_thep = double.Parse(Request["txt_duong_kinh_thep_coc"]);
int ID_betong = int.Parse(Request["cbb_betong"]);
int ID_cotthep = int.Parse(Request["cbb_cotthep"]);
dk_thep = dk_thep / 10; // đổi đơn vị ra cm
// Tính As coc :
double As_coc = (Math.PI * Math.Pow(dk_thep, 2)) / 4 * sothanh;
// Tính Fa <Diện tích tiết diện cọc:>
double Fa_coc = Math.Pow(dk_coc, 2) * 10000; // đổitừ m2 ra cm2
VuVanHoa_DatabaseDataContext db = new VuVanHoa_DatabaseDataContext();
tbl_betong bt = db.tbl_betongs.Where(o => o.id_betong == ID_betong).FirstOrDefault();
tbl_cot_thep ct = db.tbl_cot_theps.Where(x => x.IDCotThep == ID_cotthep).FirstOrDefault();
double? Pvl = 0.9 * (Fa_coc * bt.rb / 10 + As_coc * ct.Rsc / 10); // chia 10 để đổi đơn vị sang cm
Pvl = Math.Round((double)Pvl);
// Thêm cọc vào cơ sở DỮ Liệu
tbl_coc new_coc = new tbl_coc();
new_coc.MaCoc = macoc;
new_coc.TenCoc = tencoc;
new_coc.DoDai = dodaicoc.ToString();
new_coc.DuongKinhCoc = dk_coc;
new_coc.SoThanhThep = (byte)sothanh;
new_coc.DuongKinhThep =(byte) dk_thep;
new_coc.id_betong = ID_betong;
new_coc.IDCotThep = ID_cotthep;
new_coc.SucChiuTai = Pvl;
new_coc.is_deleted = 0;
new_coc.DienTich_TD = Fa_coc/10000; // chia 10000 để đổi ra đơn vị mét
new_coc.ChuVi_TD = dk_coc * 4;
db.tbl_cocs.InsertOnSubmit(new_coc);
db.SubmitChanges();
return "Thêm Cọc Thành Công";
}
}
} |
/**
* \file SeasonalEmployee.cs
* \author Ab-Code: Sekou Diaby, Tuan Ly, Becky Linyan Li, Bowen Zhuang
* \date 21-11-2014
* \brief contains all the methods and attributes to handle a Seasonla Employee.
* \brief The Seasonal Employee is the child class of the parent Employee clas.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace AllEmployees
{
///
/// \class SeasonalEmployee
/// \brief to model the attributes and behaviour of an SeasonalEmployee,
/// \brief accessor and mutators for the attributes, validates all the fields of the employee and
/// \biref shows the details of the SeasonalEmployee.
///
public class SeasonalEmployee : Employee
{
/* ====================================== */
/* PRIVATE */
/* ====================================== */
/* -------------- ATTRIBUTES ------------ */
private string season; ///< \brief the season of work for the employee
private float piecePay; ///< \brief the Peice pay for the employee
/* ====================================== */
/* PUBLIC */
/* ====================================== */
///
/// \brief This function is the constructor of the SeasonalEmployee and it set the initial value for data members to blank
/// \details <b>Details</b>
/// \param no param
/// \return no returns
///
public SeasonalEmployee()
{
bool empTypeRes = SetemployeeType(SEASONAL);
if (empTypeRes)
{
season = "";
piecePay = 0;
}
}
///
/// \brief This function is the constructor of the SeasonalEmployee and it set the initial value for data members to parameters
/// \details <b>Details</b>
/// \param newSeason - <b>string </b> -the season of work for the employee
/// \param newPiecePay - <b>float </b> -the Peice pay for the employee
/// /// \return no returns
///
public SeasonalEmployee(string newSeason, float newPiecePay)
{
bool empTypeRes = SetemployeeType(SEASONAL);
if (empTypeRes)
{
season = newSeason;
piecePay = newPiecePay;
}
}
///
/// \brief This function is the constructor of the SeasonalEmployee and it set the initial value for data members to parameters
/// \details <b>Details</b>
/// \param fName - <b>string </b> -the first name for the employee
/// \param lName - <b>string </b> -the last name for the employee
/// /// \return no returns
///
public SeasonalEmployee(string fName, string lName)
{
bool empTypeRes = SetemployeeType(SEASONAL);
if (empTypeRes)
{
firstName = fName;
lastName = lName;
}
}
///
/// \brief This function sets the employee's work season to the parameter passed in
/// \details <b>Details</b>
///
/// \param newSeason - <b>string</b> - The season of work for the employee
/// \return ret - <b>bool</b> -The result to see if the attribute was set.
///
public bool Setseason(string newSeason)
{
bool ret = false;
if (newSeason != "")
{
//string allSeason = "FALL WINTER SUMMER SPRING";
if (newSeason.ToUpper() == "FALL")
{
season = newSeason;
ret = true;
}
else if (newSeason.ToUpper() == "WINTER")
{
season = newSeason;
ret = true;
}
else if (newSeason.ToUpper() == "SUMMER")
{
season = newSeason;
ret = true;
}
else if (newSeason.ToUpper() == "SPRING")
{
season = newSeason;
ret = true;
}
}
else
{
season = newSeason;
ret = true;
}
return ret;
}
///
/// \brief This function sets the employee's Piece Pay to the parameter passed in
/// \details <b>Details</b>
///
/// \param newPiecePay - <b>float</b> - The pay for the employee
/// \return ret - <b>bool</b> -The result to see if the attribute was set.
///
public bool SetpiecePay(float newPiecePay)
{
bool ret = false;
if (newPiecePay >= 0)
{
piecePay = newPiecePay;
ret = true;
}
return ret;
}
///
/// \brief This function gets the Seasonal employee's season and returns it.
/// \details <b>Details</b>
///
/// \param no params
/// \return season - <b>string</b> -The season of the created Seasonal employee object.
///
public string Getseason()
{
return season;
}
///
/// \brief This function gets the Seasonal employee's piecePay and returns it.
/// \details <b>Details</b>
///
/// \param no params
/// \return piecePay - <b>float</b> -The piecePay of the created Seasonal employee object.
///
public float GetpiecePay()
{
return piecePay;
}
///
/// \brief This function validates all the fields of a seasonal time employee
/// \details <b>Details</b> -It will validate all the parents attributes,
/// than it validates all the attributes specific
/// to the class. If all field are valid, it return
/// a bool and set the employee to be valid.
///
/// \param no parameters
/// \return ret - <b>bool</b> -The result to see if the seasonal employee is valid.
///
public override bool Validate()
{
string exceptions = "";
bool ret = true;
if (employeeType != SEASONAL)
{
ret = false;
exceptions += "\nThe employee must be a Seasonal employee\n";
} // First name cannot be blank to be a valid Seasonal time employee
if (firstName != "")
{
// Seasonal employee's First name must only contain aplhabets, hyphen and dashes
if (Regex.IsMatch(firstName, "[^a-zA-Z-']"))
{
exceptions += "First Name must only contain alphabets, hyphen and dashes\n";
ret = false;
}
}
else
{
exceptions += "First Name must not be empty and must only contain alphabets, hyphen and dashes\n";
ret = false;
}
// Last name cannot be blank to be a valid Seasonal time employee
if (lastName != "")
{
// Full time employee's Last name must only contain aplhabets, hyphen and dashes
if (Regex.IsMatch(lastName, "[^a-zA-Z-']"))
{
exceptions += "Last Name must only contain alphabets, hyphen and dashes\n";
ret = false;
}
}
else
{
exceptions += "Last Name must not be empty and must only contain alphabets, hyphen and dashes\n";
ret = false;
}
//Date of birth must not be empty to be a valid Seasonal employee
if (dateOfBirth != "")
{
bool isDateValid = validateDate(dateOfBirth);
if (!isDateValid)
{
exceptions += "The date of birth is not a valid date\n";
ret = false;
}
}
else
{
exceptions += "The date of birth is not a valid date\n";
ret = false;
}
// Seasonal employee's SIN must be valid
bool isFTSINValid = validateSIN();
if (!isFTSINValid)
{
exceptions += "The SIN is not valid\n";
ret = false;
}
if (piecePay <= 0)
{
exceptions += "The Piece pay cannot be Negative\n";
ret = false;
}
bool isDigitPresent = season.Any(c => char.IsDigit(c));
if (season == "" || isDigitPresent == true)
{
exceptions += "The Season provide is not a valid season\n";
ret = false;
}
string allSeason = "FALL WINTER SUMMER SPRING";
if (!(allSeason.Contains(season.ToUpper())))
{
exceptions += "The Season provided is not a valid season\n";
ret = false;
}
if (dateOfBirth != "")
{
int birth = Convert.ToInt32(dateOfBirth.Substring(0, 4));
if (birth > 2014)
{
ret = false;
exceptions += "Employee cannot be born on a date that has not occured\n";
}
}
if (ret)
isValidEmp = true;
else
{
isValidEmp = false;
throw new Exception(exceptions);
}
return ret;
}
///
/// \brief This function displays all attributes of an employee.
/// \details <b>Details</b> -The child function is displays all
/// the attributes and displays if the
/// Seasonal employee is valid.
/// \param no params
/// \return no returns
///
public override void Details()
{
// display employee details
string type = "";
if (employeeType == SEASONAL)
{
type = "Seasonal";
}
else
{
type += employeeType;
}
Console.WriteLine("\n************************************************************");
Console.WriteLine(" EMPLOYEE DETAILS ");
Console.WriteLine(" Is Employee Valid ? {0}", isValidEmp);
Console.WriteLine("*************************************************************");
Console.WriteLine(" |");
Console.WriteLine(" Employee Type | {0}", type);
Console.WriteLine(" |");
Console.WriteLine("-------------------------|----------------------------------");
Console.WriteLine(" |");
Console.WriteLine(" First Name | {0}", firstName);
Console.WriteLine(" |");
Console.WriteLine("-------------------------|----------------------------------");
Console.WriteLine(" |");
Console.WriteLine(" Last Name | {0}", lastName);
Console.WriteLine(" |");
Console.WriteLine("-------------------------|----------------------------------");
Console.WriteLine(" |");
Console.WriteLine(" Date Of Birth | {0}", dateOfBirth);
Console.WriteLine(" |");
Console.WriteLine("-------------------------|----------------------------------");
Console.WriteLine(" |");
Console.WriteLine(" Social Insurance Number | {0}", socialInsuranceNumber);
Console.WriteLine(" |");
Console.WriteLine("-------------------------|----------------------------------");
Console.WriteLine(" |");
Console.WriteLine(" Season | {0}", season);
Console.WriteLine(" |");
Console.WriteLine("-------------------------|----------------------------------");
Console.WriteLine(" |");
Console.WriteLine(" Piece Pay | {0}", piecePay);
Console.WriteLine(" |");
Console.WriteLine("************************************************************\n");
/*Log in file after details*/
}
///
/// \brief This function puts all attributes of an employee into a string to be logged in the logfile.
/// \details <b>Details</b> - concatenates if the employee is valid, all
/// the attributes and sends them to the log file
///
/// \param no params
/// \return no returns
///
public override string ToString()
{
string empStr = "";
string type = "";
if (employeeType == SEASONAL)
{
type = "Seasonal";
}
else
{
type += employeeType;
}
empStr += "\r\n************************************************************\r\n";
empStr += " EMPLOYEE DETAILS \r\n";
empStr += " Is Employee Valid ?" + isValidEmp + "\r\n";
empStr += "*************************************************************\r\n";
empStr += " |\r\n";
empStr += " Employee Type | " + type + "\r\n";
empStr += " |\r\n";
empStr += "-------------------------|----------------------------------\r\n";
empStr += " |\r\n";
empStr += " First Name | " + firstName + "\r\n";
empStr += " |\r\n";
empStr += "-------------------------|----------------------------------\r\n";
empStr += " |\r\n";
empStr += " Last Name | " + lastName + "\r\n";
empStr += " |\r\n";
empStr += "-------------------------|----------------------------------\r\n";
empStr += " |\r\n";
empStr += " Date Of Birth | " + dateOfBirth + "\r\n";
empStr += " |\r\n";
empStr += "-------------------------|----------------------------------\r\n";
empStr += " |\r\n";
empStr += " Social Insurance Number | " + socialInsuranceNumber + "\r\n";
empStr += " |\r\n";
empStr += "-------------------------|----------------------------------\r\n";
empStr += " |";
empStr += " Season | " + season + "\r\n";
empStr += " |";
empStr += "-------------------------|----------------------------------\r\n";
empStr += " |";
empStr += " Piece Pay | "+ piecePay+ "\r\n";
empStr += " |";
empStr += "************************************************************\r\n";
return empStr;
}
}
}
|
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class BVHImporter
{
public string fileName;
public List<Bone> boneList;
public int frames;
public float frameTime;
public int frameRate;
private List<float[]> motions;
private char[] space = new char[] { ' ', '\t', '\n', '\r' };
public BVHImporter(string name)
{
this.fileName = name;
}
public class Bone
{
public string name;
public string parent;
public List<string> children;
public Vector3 offsets;
public int[] channelType;
public Channel[] channels;
public struct Channel
{
public bool enabled;
public float[] value;
}
public Bone(string name, string parent)
{
this.name = name;
this.parent = parent;
children = new List<string>();
offsets = Vector3.zero;
channelType = new int[0];
channels = new Channel[6];
}
}
public void read()
{
boneList = new List<Bone>();
motions = new List<float[]>();
string[] lines = File.ReadAllLines(fileName);
int index = 0;
string name = string.Empty;
string parent = string.Empty;
for (index = 0; index < lines.Length; index++)
{
if (lines[index] == "MOTION")
{
break;
}
string[] entries = lines[index].Split(space);
for (int entry = 0; entry < entries.Length; entry++)
{
if (entries[entry].Contains("ROOT"))
{
parent = "None";
name = entries[entry + 1];
name = fixedName(name);
boneList.Add(new Bone(name, parent));
break;
}
else if (entries[entry].Contains("JOINT"))
{
parent = name;
name = entries[entry + 1];
name = fixedName(name);
boneList.Add(new Bone(name, parent));
break;
}
else if (entries[entry].Contains("End"))
{
parent = name;
name = name + entries[entry + 1];
Bone endBone = new Bone(name, parent);
string[] offsetEntries = lines[index + 2].Split(space);
for (int offsetEntry = 0; offsetEntry < offsetEntries.Length; offsetEntry++)
{
if (offsetEntries[offsetEntry].Contains("OFFSET"))
{
endBone.offsets.x = float.Parse(offsetEntries[offsetEntry + 1]);
endBone.offsets.y = float.Parse(offsetEntries[offsetEntry + 2]);
endBone.offsets.z = float.Parse(offsetEntries[offsetEntry + 3]);
break;
}
}
boneList.Add(endBone);
index += 2;
break;
}
else if (entries[entry].Contains("OFFSET"))
{
getBone(name).offsets.x = float.Parse(entries[entry + 1]);
getBone(name).offsets.y = float.Parse(entries[entry + 2]);
getBone(name).offsets.z = float.Parse(entries[entry + 3]);
break;
}
else if (entries[entry].Contains("CHANNEL"))
{
getBone(name).channelType = new int[int.Parse(entries[entry + 1])];
for (int i = 0; i < getBone(name).channelType.Length; i++)
{
if (entries[entry + 2 + i] == "Xposition")
{
getBone(name).channelType[i] = 1;
getBone(name).channels[0].enabled = true;
}
else if (entries[entry + 2 + i] == "Yposition")
{
getBone(name).channelType[i] = 2;
getBone(name).channels[1].enabled = true;
}
else if (entries[entry + 2 + i] == "Zposition")
{
getBone(name).channelType[i] = 3;
getBone(name).channels[2].enabled = true;
}
else if (entries[entry + 2 + i] == "Xrotation")
{
getBone(name).channelType[i] = 4;
getBone(name).channels[3].enabled = true;
}
else if (entries[entry + 2 + i] == "Yrotation")
{
getBone(name).channelType[i] = 5;
getBone(name).channels[4].enabled = true;
}
else if (entries[entry + 2 + i] == "Zrotation")
{
getBone(name).channelType[i] = 6;
getBone(name).channels[5].enabled = true;
}
}
break;
}
else if (entries[entry].Contains("}"))
{
if (parent != "None")
{
getBone(parent).children.Add(name);
}
name = parent;
parent = name == "None" ? "None" : boneList.Find(x => x.name == name).parent;
break;
}
}
}
index += 1;
while (lines[index].Length == 0)
{
index += 1;
}
frames = int.Parse(lines[index].Substring(8));
index += 1;
frameTime = float.Parse(lines[index].Substring(12));
frameRate = (int)(1.0f / frameTime);
index += 1;
for (int i = index; i < lines.Length; i++)
{
motions.Add(parseFloatArray(lines[i]));
}
int channelIndex = 0;
foreach (Bone bone in boneList)
{
for (int i = 0; i < bone.channelType.Length; i++)
{
bone.channels[bone.channelType[i] - 1].value = new float[frames];
for (int j = 0; j < frames; j++)
{
bone.channels[bone.channelType[i] - 1].value[j] = motions[j][channelIndex];
}
channelIndex++;
}
}
}
public float[] parseFloatArray(string str)
{
if (str.StartsWith(" "))
{
str = str.Substring(1);
}
if (str.EndsWith(" ") || str.EndsWith(""))
{
str = str.Substring(0, str.Length - 1);
}
string[] multiStr = str.Split(space);
float[] result = new float[multiStr.Length];
for (int i = 0; i < multiStr.Length; i++)
{
result[i] = float.Parse(multiStr[i]);
}
return result;
}
public Bone getBone(string name)
{
return boneList.Find(x => x.name == name);
}
public string fixedName(string str)
{
char[] option = { '_', ':' };
string[] name = str.Split(option);
return name[name.Length - 1];
}
public int getCount()
{
return boneList.Count;
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using CORE;
using CORE.Многомерные;
using CORE.Одномерные;
using CORE.Одномерные_цепочки;
using Jace;
using MaterialSkin;
using MaterialSkin.Controls;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
namespace OptimisationCat
{
public partial class MainForm : MaterialForm
{
private readonly List<OneDimMethod> _alphaMethods = new List<OneDimMethod>();
private readonly List<string> _functions = new List<string>();
private readonly MaterialSkinManager _materialSkinManager;
private readonly List<OptimisationMethod> _methods = new List<OptimisationMethod>();
private bool _alphaMethodChosen;
private OneDimMethod _currAlphaMethod;
private Func<Vector<double>, double> _currFunction;
private OptimisationMethod _currMethod;
private bool _functionChosen;
private bool _methodChosen;
private int _varCount;
public MainForm()
{
InitializeComponent();
PopulateFunctions();
PopulateMethods();
PopulateAlphaMethods();
_materialSkinManager = MaterialSkinManager.Instance;
_materialSkinManager.AddFormToManage(this);
_materialSkinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900,
Primary.BlueGrey500,
Accent.LightBlue200, TextShade.WHITE);
}
private void UpdateForm()
{
calculateButton.Enabled = _functionChosen && _methodChosen;
testAllButton.Enabled = _functionChosen;
}
#region populating combo boxes
private void PopulateAlphaMethods()
{
//заполняем наш список
_alphaMethods.Add(new GoldenRatio1(null));
_alphaMethods.Add(new GoldenRatio2(null));
_alphaMethods.Add(new Dichotomy(null));
_alphaMethods.Add(new Fibonacci1(null));
_alphaMethods.Add(new Fibonacci2(null));
_alphaMethods.Add(new Bolzano(null, null));
_alphaMethods.Add(new Extrapolation(null));
_alphaMethods.Add(new Paul(null, null));
_alphaMethods.Add(new Dsk(null));
_alphaMethods.Add(new BoostedDavidon(null, null));
_alphaMethods.Add(new SvennDihNewt());
_alphaMethods.Add(new SvennBolzGr1());
_alphaMethods.Add(new SvennBolzFib2());
_alphaMethods.Add(new Fib1Dsk());
_alphaMethods.Add(new Fib2Dsk());
_alphaMethods.Add(new DihPaul());
_alphaMethods.Add(new BolzPaul());
_alphaMethods.Add(new Gr1Extr());
_alphaMethods.Add(new DihDav());
_alphaMethods.Add(new ExtrDav());
_alphaMethods.Add(new Gr2Paul());
foreach (var alphaMethod in _alphaMethods) alphaMethodComboBox.Items.Add(alphaMethod.Name);
}
private void PopulateMethods()
{
// _methods.Add(new Partan1());
// _methods.Add(new KvasiNewton());
// _methods.Add(new Msg());
// _methods.Add(new GenericNewton());
_methods.Add(new HookeJeeves());
_methods.Add(new HookeJeevesPs());
foreach (var method in _methods) methodComboBox.Items.Add(method.Name);
}
private void PopulateFunctions()
{
_functions.Add("10: x1^2+3*x2^2+2*x1*x2");
_functions.Add("11: 100*(x2-x1^2)^2+(1-x1)^2");
_functions.Add("12: -12*x2+4*x1^2+4*x2^2-4*x1*x2");
_functions.Add("13: (x1-2)^4+(x1-2*x2)^2");
_functions.Add("14: 4*(x1-5)^2+(x2-6)^2");
_functions.Add("15: (x1-2)^4+(x1-2*x2)^2");
_functions.Add("19: 100*(x2-x1^2)^2+(1-x1)^2");
_functions.Add("20: (x1-1)^2+(x2-3)^2+4*(x3+5)^2");
_functions.Add("21: 8*x1^2+4*x1*x2+5*x2^2");
_functions.Add("22: 4*(x1-5)^2+(x2-6)^2");
_functions.Add("27: -12*x2+4*x1^2+4*x2^2-4*x1*x2");
_functions.Add("32: 100*(x2-x1^3)^2+(1-x1)^2");
// ReSharper disable once CoVariantArrayConversion
functionComboBox.Items.AddRange(_functions.ToArray());
}
#endregion
#region Events
/// <summary>
/// Загрузка формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
materialCheckBox1_CheckedChanged(null, null);
UpdateForm();
}
/// <summary>
/// Изменение темы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void materialCheckBox1_CheckedChanged(object sender, EventArgs e)
{
switch (materialCheckBox1.Checked)
{
case false:
_materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
break;
case true:
_materialSkinManager.Theme = MaterialSkinManager.Themes.DARK;
break;
}
}
/// <summary>
/// GRAPH BUTTON CLICK
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void graphButton_Click(object sender, EventArgs e)
{
var func = _functions[functionComboBox.SelectedIndex];
if (func.Contains(':'))
func = func.Remove(0, func.IndexOf(':') + 1);
//Запускаем форму
var form = new GraphForm(func);
_materialSkinManager.AddFormToManage(form);
form.ShowDialog();
}
/// <summary>
/// CALCULATE BUTTON CLICK
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void calculateButton_Click(object sender, EventArgs e)
{
_currMethod.AlphaMethod = null;
Vector<double> start = new DenseVector(_varCount);
try
{
var text = startingPointTextBox.Text;
var textValues = text.Split(',');
for (var i = 0; i < _varCount; i++) start[i] = double.Parse(textValues[i]);
}
catch (Exception)
{
start.Clear();
}
var fh = new FunctionHolder(_currFunction, start);
_currMethod.Fh = fh;
if (_alphaMethodChosen)
{
_currAlphaMethod.F = fh.AlphaFunction;
_currAlphaMethod.Df = fh.AlphaDiffFunction;
_currMethod.AlphaMethod = _currAlphaMethod;
}
double eps;
try
{
eps = double.Parse(precisionTextBox.Text);
}
catch (Exception)
{
eps = 1e-5;
precisionTextBox.Text = @"1e-5";
}
_currMethod.Eps = eps;
//Делаем сам метод
var sw = Stopwatch.StartNew();
_currMethod.Execute();
sw.Stop();
//Вывод, Двуменрная функция
var coord = _currMethod.Answer;
answerTextBox.Text = @"Answer:" + Environment.NewLine + coord.ToString();
iterationTextBox.Text = Convert.ToString("Iterations: " + _currMethod.IterationCount);
timeTextBox.Text = @"Time (ms):" + Environment.NewLine +
(sw.ElapsedMilliseconds == 0 ? "<1" : sw.ElapsedMilliseconds.ToString());
}
/// <summary>
/// выбираем альфа метод
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void alphaMethodComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
_currAlphaMethod = _alphaMethods[alphaMethodComboBox.SelectedIndex];
_alphaMethodChosen = true;
}
/// <summary>
/// Выбираем метод
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void methodComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
_currMethod = _methods[methodComboBox.SelectedIndex];
_methodChosen = true;
UpdateForm();
}
/// <summary>
/// Выбираем функцию и парсим ее
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void functionComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var functionText = functionComboBox.Text;
try
{
ParseFunction(functionText);
}
catch (Exception exception)
{
MessageBox.Show("Ошибка парсинга: " + exception.Message);
}
finally
{
UpdateForm();
}
}
/// <summary>
/// Парсим функцию
/// </summary>
/// <param name="functionText"></param>
private void ParseFunction(string functionText)
{
if (functionText.Contains(':'))
functionText = functionText.Remove(0, functionText.IndexOf(':') + 1);
var index = 0;
_varCount = 0;
while (index != -1)
{
index = functionText.IndexOf("x", index, StringComparison.Ordinal);
if (index == -1) break;
try
{
int num;
if (int.TryParse(functionText.Substring(index + 1, 1), out num))
_varCount = _varCount < num ? num : _varCount;
index++;
}
catch (Exception)
{
index++;
}
}
var engine = new CalculationEngine();
var formula = engine.Build(functionText);
//кастим на нужную функцию
_currFunction = doubles =>
{
var variables = new Dictionary<string, double>();
for (var i = 0; i < doubles.Count; i++) variables.Add($"x{i + 1}", doubles[i]);
return formula(variables);
};
_functionChosen = true;
UpdateForm();
}
/// <summary>
/// Нажатие enter -> парсинг функции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void functionComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char) Keys.Enter) ParseFunction(functionComboBox.Text);
}
/// <summary>
/// Выбор функции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void functionComboBox_TextChanged(object sender, EventArgs e)
{
}
/// <summary>
/// Нажатие кнопки "TEST ALL"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void materialFlatButton1_Click(object sender, EventArgs e)
{
var exports = new List<TestExport>(_functions.Count * _methods.Count);
foreach (var function in _functions)
{
ParseFunction(function);
foreach (var method in _methods)
{
_currMethod = method;
_currMethod.AlphaMethod = null;
Vector<double> start = new DenseVector(_varCount);
try
{
var text = startingPointTextBox.Text;
var textValues = text.Split(',');
for (var i = 0; i < _varCount; i++) start[i] = double.Parse(textValues[i]);
}
catch (Exception)
{
start.Clear();
}
var fh = new FunctionHolder(_currFunction, start);
_currMethod.Fh = fh;
if (_alphaMethodChosen)
{
_currAlphaMethod.F = fh.AlphaFunction;
_currAlphaMethod.Df = fh.AlphaDiffFunction;
_currMethod.AlphaMethod = _currAlphaMethod;
}
double eps;
try
{
eps = double.Parse(precisionTextBox.Text);
}
catch (Exception)
{
eps = 1e-5;
precisionTextBox.Text = @"1e-5";
}
_currMethod.Eps = eps;
//Делаем сам метод
var sw = Stopwatch.StartNew();
_currMethod.Execute();
sw.Stop();
//Вывод, Двуменрная функция
var coord = _currMethod.Answer;
var vectorString = coord.ToVectorString().Replace("\r\n"," ");
exports.Add(new TestExport(method.Name, function,
vectorString,
method.IterationCount.ToString(), sw.ElapsedMilliseconds.ToString(), eps.ToString()));
}
}
var testForm = new TestForm(exports);
_materialSkinManager.AddFormToManage(testForm);
testForm.ShowDialog();
}
#endregion
}
} |
using System;
namespace Compi_segundo
{
public class Token
{
public Token ()
{
}
string lexema;
int tipoToken;
int linea;
public Token(string lexema,int tipoToken,int linea)
{
this.lexema = lexema;
this.tipoToken = tipoToken;
this.linea = linea;
}
public String getLexema()
{
return lexema;
}
public void setLexema(string lexema)
{
this.lexema = lexema;
}
public int getLinea()
{
return this.linea;
}
public void setLinea(int linea)
{
this.linea = linea;
}
public int getTipoToken()
{
return this.tipoToken;
}
public void setTipoToken(int tipoToken)
{
this.tipoToken = tipoToken;
}
}
}
|
using ArkSavegameToolkitNet.Domain.Internal;
using ArkSavegameToolkitNet.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArkSavegameToolkitNet.Domain
{
public class ArkStructureCropPlot : ArkStructure
{
private static readonly ArkName _cropPhaseFertilizerCache = ArkName.Create("CropPhaseFertilizerCache");
private static readonly ArkName _waterAmount = ArkName.Create("WaterAmount");
private static readonly ArkName _plantedCrop = ArkName.Create("PlantedCrop");
internal static readonly new ArkNameTree _dependencies = new ArkNameTree
{
{ _cropPhaseFertilizerCache, null },
{ _waterAmount, null },
{ _plantedCrop, null }
};
public ArkStructureCropPlot() : base()
{
}
public ArkStructureCropPlot(IGameObject structure, ISaveState saveState) : base(structure, saveState)
{
FertilizerAmount = structure.GetPropertyValue<float?>(_cropPhaseFertilizerCache);
WaterAmount = structure.GetPropertyValue<float>(_waterAmount);
var plantedCropBlueprintGeneratedClass = structure.GetPropertyValue<ObjectReference>(_plantedCrop)?.ObjectString?.Token;
PlantedCropClassName = plantedCropBlueprintGeneratedClass?.SubstringAfterLast('.');
}
public float? FertilizerAmount { get; set; }
public float WaterAmount { get; set; }
public string PlantedCropClassName { get; set; }
}
}
//[
// {
// "class": "CropPlotLarge_SM_C",
// "count": 12,
// "props": [
// "bHasResetDecayTime (Boolean)",
// "bIsFertilized (Boolean)",
// "bIsLocked (Boolean)",
// "bIsWatered (Boolean) [*]",
// "CropPhaseFertilizerCache (Single)",
// "CropRefreshInterval (Single)",
// "CurrentCropPhase (ArkByteValue)",
// "Health (Single) [*]",
// "IrrigationWaterTap (ObjectReference) [*]",
// "LastCropRefreshTime (Double)",
// "LastEnterStasisTime (Double)",
// "LastInAllyRangeTime (Double)",
// "MaxHealth (Single)",
// "MyCropStructure (ObjectReference)",
// "MyInventoryComponent (ObjectReference)",
// "OriginalCreationTime (Double)",
// "OwnerName (String)",
// "PlacedOnFloorStructure (ObjectReference) [*]",
// "PlantedCrop (ObjectReference)",
// "StructuresPlacedOnFloor (ArkArrayObjectReference)",
// "TargetingTeam (Int32)",
// "WaterAmount (Single)"
// ]
// },
// {
// "class": "CropPlotMedium_SM_C",
// "count": 34,
// "props": [
// "bHasFruitItems (Boolean)",
// "bHasResetDecayTime (Boolean)",
// "bIsFertilized (Boolean) [*]",
// "bIsSeeded (Boolean) [*]",
// "bIsWatered (Boolean)",
// "CropPhaseFertilizerCache (Single) [*]",
// "CropRefreshInterval (Single)",
// "CurrentCropPhase (ArkByteValue) [*]",
// "IrrigationWaterTap (ObjectReference)",
// "LastCropRefreshTime (Double)",
// "LastEnterStasisTime (Double)",
// "LastInAllyRangeTime (Double)",
// "MaxHealth (Single)",
// "MyInventoryComponent (ObjectReference)",
// "NumGreenHouseStructures (ArkByteValue)",
// "OriginalCreationTime (Double)",
// "OwnerName (String)",
// "PlacedOnFloorStructure (ObjectReference)",
// "PlantedCrop (ObjectReference) [*]",
// "TargetingTeam (Int32)",
// "WaterAmount (Single)"
// ]
// },
// {
// "class": "CropPlotSmall_SM_C",
// "count": 102,
// "props": [
// "bHasFruitItems (Boolean) [*]",
// "bHasResetDecayTime (Boolean)",
// "bIsSeeded (Boolean) [*]",
// "bIsWatered (Boolean)",
// "CropRefreshInterval (Single)",
// "IrrigationWaterTap (ObjectReference)",
// "LastCropRefreshTime (Double)",
// "LastEnterStasisTime (Double)",
// "LastInAllyRangeTime (Double)",
// "MaxHealth (Single)",
// "MyInventoryComponent (ObjectReference)",
// "NumGreenHouseStructures (ArkByteValue)",
// "OriginalCreationTime (Double)",
// "OwnerName (String)",
// "PlacedOnFloorStructure (ObjectReference)",
// "TargetingTeam (Int32)",
// "WaterAmount (Single)"
// ]
// }
//] |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using GabayManageSite.GabayDataSetTableAdapters;
namespace GabayManageSite.Services
{
/// <summary>
/// Summary description for GabayService
/// </summary>
[WebService(Namespace = "https://gabaymanagmentsite.azurewebsites.net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class GabayService : System.Web.Services.WebService
{
PrayersTableAdapter PrayersTableAdapter { get; set; }
ParashaDetailsTableAdapter ParashaTabeleAdapter { get; set; }
GabayDataSet gabayDataSet { get; set; }
PrayersTableAdapter prayersTableAdapter { get; set; }
AliyaHistoryTableAdapter AliyaHistoryAdapter { get; set; }
[WebMethod]
public string GetPrayerBySynagoge(int synid)
{
gabayDataSet = new GabayDataSet();
AliyaHistoryAdapter = new AliyaHistoryTableAdapter();
var prayers = AliyaHistoryAdapter.GetLastAliyaDate(synid);
List<Models.Prayer> prayersInfo = new List<Models.Prayer>();
foreach (var prayer in prayers.ToList())
{
prayersInfo.Add(new Models.Prayer { PrayerFirstName = prayer.PRIVATE_NAME, PrayerLastName = prayer.FAMILY_NAME, PrayerIDString = prayer.Prayer_id });
}
return new JavaScriptSerializer().Serialize(prayersInfo);
}
[WebMethod]
public void SaveAliyaHistory(int synId, string prayer_id, int kriyaId)
{
//productCode = productCode.Replace(" ", String.Empty);
//using (var db = new MyShopDataContext())
//{
// var userProduct = new UserProduct();
// userProduct.ProductCode = productCode;
// userProduct.UserName = userName;
//
// db.UserProducts.InsertOnSubmit(userProduct);
// db.SubmitChanges();
//}
AliyaHistoryTableAdapter AliyotAdapter = new AliyaHistoryTableAdapter();
AliyotAdapter.InsertQuery(prayer_id, synId, kriyaId);
}
}
}
|
using System;
using System.Windows;
using CaveDwellers.Core;
using CaveDwellers.Core.TimeManagement;
using CaveDwellers.Mathematics;
using CaveDwellers.Positionables.Monsters;
using CaveDwellers.Utility;
using CaveDwellersTest.MonstersForTest;
using Moq;
using NUnit.Framework;
namespace CaveDwellersTest.Given_a_Monster
{
public class When_the_worldMatrix_is_Notified_of_GameTimeElapsed_and_the_monsters_destination_is_EASTish : AAATest
{
private WorldMatrix _worldMatrix;
private Mock<IRnd> _rndMock;
private Monster _monster1;
private readonly Point _oldLocation1 = new Point(-50, -1);
private Monster _monster2;
private readonly Point _oldLocation2 = new Point(-50, 1);
protected override void Arrange()
{
_rndMock = new Mock<IRnd>();
_rndMock.Setup(r => r.NextX()).Returns(0);
_rndMock.Setup(r => r.NextY()).Returns(0);
_worldMatrix = new WorldMatrix();
_worldMatrix.Notify(new GameTime(new DateTime(2014, 2, 23, 20, 0, 0, 0), 100));
_monster1 = new Monster1x1(_worldMatrix, _rndMock.Object);
_monster2 = new Monster1x1(_worldMatrix, _rndMock.Object);
_worldMatrix.Add(_oldLocation1, _monster1);
_worldMatrix.Add(_oldLocation2, _monster2);
//we need a first notify in order to have a baseline
_worldMatrix.Notify(new GameTime(new DateTime(2014, 2, 23, 20, 0, 0, 100), 100));
}
protected override void Act()
{
_worldMatrix.Notify(new GameTime(new DateTime(2014, 2, 23, 20, 0, 0, 100), 100));
}
[Test]
public void The_distance_between_monster1_and_the_destination_becomes_smaller()
{
var locationOfMonster = _worldMatrix.GetLocationOf(_monster1);
Assert.IsNotNull(locationOfMonster);
Assert.True(locationOfMonster.Value.X > -50 && locationOfMonster.Value.Y >= -1, string.Format("the new location must lie closer to (0,0), but is now {0}", locationOfMonster));
}
[Test]
public void The_distance_between_monster2_and_the_destination_becomes_smaller()
{
var locationOfMonster = _worldMatrix.GetLocationOf(_monster2);
Assert.IsNotNull(locationOfMonster);
Assert.True(locationOfMonster.Value.X > -50 && locationOfMonster.Value.Y <= 1, string.Format("the new location must lie closer to (0,0), but is now {0}", locationOfMonster));
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
namespace DALLogs
{
[Table("LoggerMessages")]
public class LoggerMessages
{
public LoggerMessages()
{
}
public LoggerMessages(string type)
{
Type = type;
}
public int Id { get; set; }
public DateTime CreateDate { get; set; }
public string Type { get; set; }
public string Message { get; set; }
}
}
|
// This file is part of LAdotNET.
//
// LAdotNET is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// LAdotNET is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY, without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with LAdotNET. If not, see <https://www.gnu.org/licenses/>.
using DotNetty.Buffers;
namespace LAdotNET.Network.Encryption
{
public class LACrypt
{
// 1.6.2.3
/*
private static byte[] xorKey = new byte[]
{
0x03, 0xCB, 0xEA, 0xB6, 0x32, 0xCF, 0x2E, 0xA8, 0x78, 0x52, 0x00, 0x3A, 0x7C, 0x59, 0xC8, 0xD9,
0x98, 0x70, 0x68, 0x2D, 0x40, 0x1C, 0x18, 0xE1, 0xF8, 0xD8, 0xDC, 0xA5, 0x47, 0x9E, 0xA2, 0x8A,
0x87, 0x62, 0x77, 0x4C, 0x05, 0x5B, 0x67, 0x10, 0x22, 0x9C, 0xA0, 0x44, 0xC7, 0x63, 0x65, 0xC2,
0x11, 0x61, 0x79, 0x5E, 0x95, 0x8D, 0xA9, 0x3E, 0x49, 0x9A, 0xE9, 0x4E, 0x35, 0xE3, 0xE5, 0x14,
0xCC, 0xB6, 0x97, 0x5A, 0xA4, 0x8C, 0x06, 0x01, 0xDB, 0x31, 0x73, 0xBA, 0xB9, 0x41, 0x0E, 0x81,
0x64, 0x0C, 0xD7, 0x6D, 0xE8, 0x36, 0xD3, 0x94, 0x2B, 0x89, 0x21, 0x12, 0xA7, 0x04, 0x9F, 0x76,
0x53, 0xFD, 0x15, 0x58, 0xBE, 0x4A, 0xB4, 0x93, 0xFA, 0xE7, 0x85, 0x16, 0x23, 0x96, 0xEA, 0xC4,
0x66, 0xCB, 0xD2, 0x42, 0x0A, 0x29, 0xEF, 0xF4, 0x3C, 0x2A, 0x82, 0xAD, 0xD4, 0xBB, 0x45, 0x0B,
0x1B, 0x92, 0x28, 0xC1, 0xFF, 0x56, 0x69, 0x3D, 0x2F, 0x7A, 0xDE, 0x7E, 0xB1, 0x7B, 0x5D, 0x48,
0x39, 0x9D, 0x83, 0x17, 0x19, 0x50, 0xA1, 0x38, 0xB0, 0xBC, 0x1A, 0x26, 0x02, 0x4D, 0x34, 0x37,
0x57, 0xE2, 0xEE, 0x8F, 0x25, 0x7D, 0xF1, 0x43, 0xC3, 0x6A, 0xFB, 0x6C, 0x71, 0x08, 0xB7, 0xF2,
0x80, 0xE4, 0x03, 0x54, 0xAA, 0x3B, 0xD1, 0x2C, 0x6F, 0xEB, 0x3F, 0xD5, 0xBD, 0xF0, 0x4F, 0xA3,
0x91, 0x8E, 0xDD, 0x5C, 0xF3, 0x86, 0x5F, 0x0F, 0x60, 0xA6, 0xFC, 0xC5, 0xE6, 0xF6, 0xEC, 0xB2,
0xD6, 0x09, 0xC9, 0x4B, 0x84, 0xAF, 0xDA, 0xF7, 0x20, 0xE0, 0xED, 0x27, 0x6E, 0x6B, 0x30, 0x74,
0xD0, 0xB3, 0x9B, 0xB8, 0x24, 0x51, 0xB5, 0xCE, 0x1D, 0x99, 0x90, 0x1E, 0x33, 0xAB, 0x55, 0x13,
0xAE, 0x07, 0xDF, 0x7F, 0x75, 0x88, 0xC6, 0xCA, 0xC0, 0xBF, 0x0D, 0x1F, 0xF5, 0xFE, 0x8B, 0xCD,
0x72, 0x46, 0xF9, 0xAC
};
*/
// 1.6.4.1
private static byte[] xorKey = new byte[]
{
0x20, 0xC9, 0xA7, 0x42, 0x17, 0xEA, 0x93, 0x40, 0xF5, 0x65, 0x77, 0xC0, 0x18, 0x6E, 0x6B, 0x34,
0x14, 0xAF, 0xC8, 0x4A, 0x74, 0x61, 0x83, 0x53, 0xF2, 0x01, 0xA7, 0x31, 0x38, 0x1A, 0xC1, 0x81,
0x7A, 0xA0, 0x72, 0x5F, 0xEB, 0x89, 0x3E, 0x4B, 0xFB, 0x1F, 0x82, 0x7F, 0x90, 0xA4, 0x2A, 0x4F,
0xEC, 0xD9, 0xAE, 0x27, 0x2B, 0xE2, 0xDC, 0x23, 0xCE, 0xBA, 0x92, 0x3C, 0x7B, 0x7D, 0x86, 0x57,
0x43, 0x3D, 0x52, 0x4E, 0xD8, 0x09, 0x8B, 0x64, 0xAD, 0xCF, 0xF4, 0x68, 0x02, 0xA5, 0x99, 0x33,
0x8F, 0x49, 0x75, 0x47, 0x9B, 0x45, 0x7E, 0x66, 0x80, 0xFA, 0x46, 0xB1, 0x11, 0x55, 0xA6, 0x1B,
0xBF, 0x00, 0xC6, 0x28, 0xE7, 0x05, 0x3A, 0xB0, 0x5B, 0xCB, 0x22, 0x2F, 0x04, 0xA1, 0xB2, 0x76,
0x8A, 0x0F, 0xD5, 0x97, 0x25, 0x19, 0x1E, 0x7C, 0x94, 0xE0, 0x0B, 0xBC, 0x88, 0x8D, 0x2E, 0x5D,
0x16, 0xA2, 0x03, 0xB4, 0x87, 0xC5, 0x98, 0xC2, 0x63, 0xAC, 0x5E, 0xD0, 0x70, 0xDA, 0x9A, 0x36,
0xEE, 0x9C, 0x71, 0xF3, 0x48, 0xFD, 0xE6, 0x6D, 0xF0, 0xD2, 0xC3, 0x79, 0x08, 0x96, 0xA3, 0xBB,
0x29, 0x5A, 0x0D, 0x2C, 0xC9, 0xF6, 0xE4, 0x32, 0xAA, 0x0E, 0x4C, 0x30, 0xE1, 0x9E, 0xCC, 0xB9,
0x41, 0x24, 0x73, 0x85, 0x06, 0x2D, 0x44, 0xDD, 0xF9, 0x35, 0xFF, 0x78, 0xFE, 0x54, 0x12, 0x13,
0x58, 0x91, 0x21, 0xCD, 0x3F, 0x62, 0x37, 0xA8, 0x3B, 0xA9, 0xBE, 0xB6, 0x6F, 0x50, 0x60, 0x0C,
0x1D, 0x67, 0xB8, 0xB5, 0x15, 0x95, 0xD4, 0xDE, 0x59, 0x51, 0x26, 0xB7, 0xD1, 0xDB, 0xF7, 0x8C,
0xAB, 0xD3, 0x5C, 0x0A, 0xDF, 0x07, 0xED, 0xE5, 0x8E, 0xF1, 0x84, 0xB3, 0xC7, 0xD7, 0xC4, 0x9F,
0xE3, 0x69, 0xBD, 0xE9, 0x4D, 0xE8, 0xF8, 0x42, 0x39, 0xFC, 0x20, 0xCA, 0x56, 0xEF, 0x10, 0x1C,
0x6A, 0x9D, 0x6C, 0xD6
};
public static void Xor(IByteBuffer data, int seed)
{
for(int i = 0; i < data.ReadableBytes; i++)
{
data.SetByte(i, (byte)(data.GetByte(i) ^ xorKey[(seed & 0xFF) + 4]));
seed++;
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class Resume : MonoBehaviour {
public SpriteRenderer midScroll;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseDown(){
// At start of scene, set timescale to 1.0
Time.timeScale = 1.0f;
// Hide the components upon resuming
midScroll.enabled = false;
this.gameObject.SetActive (false);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ScoreSquid.Web.Models;
using ScoreSquid.Web.Context;
namespace ScoreSquid.Web.Repositories.Commands
{
public interface IPlayerCommands
{
Player LoginPlayer(ScoreSquidContext context, string username, string password);
Player RegisterPlayer(ScoreSquidContext context, Player player);
}
} |
namespace ProjetctTiGr13.Domain.FicheComponent
{
public class CaracteristicsManager
{
public int Force { get; set;}
public int Dexterite { get; set;}
public int Constitution { get; set;}
public int Intelligence { get; set;}
public int Sagesse { get; set;}
public int Charisme { get; set;}
public CaracteristicsManager()
{
Force = 0;
Dexterite = 0;
Constitution = 0;
Intelligence = 0;
Sagesse = 0;
Charisme = 0;
}
}
} |
using Alabo.Domains.Dtos;
using Alabo.Domains.Entities;
using Alabo.Domains.Trees;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Alabo.Domains.Services.Tree {
public interface ITreeAsync<TEntity, in TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> {
/// <summary>
/// 通过标识查找列表
/// </summary>
/// <param name="ids">标识列表</param>
Task<List<TDto>> FindByIdsAsync<TDto>(string ids) where TDto : class, IResponse, ITreeNode, new();
/// <summary>
/// 启用
/// </summary>
/// <param name="ids">标识列表</param>
Task EnableAsync(string ids);
/// <summary>
/// 冻结
/// </summary>
/// <param name="ids">标识列表</param>
Task DisableAsync(string ids);
/// <summary>
/// 交换排序
/// </summary>
/// <param name="id">标识</param>
/// <param name="swapId">目标标识</param>
Task SwapSortAsync(Guid id, Guid swapId);
/// <summary>
/// 修正排序
/// </summary>
/// <param name="parameter">查询参数</param>
Task FixSortIdAsync<TQueryParameter>(TQueryParameter parameter);
/// <summary>
/// 生成排序号
/// </summary>
/// <param name="parentId">父标识</param>
Task<int> GenerateSortIdAsync<TParentId>(TParentId parentId);
/// <summary>
/// 获取全部下级实体
/// </summary>
/// <param name="parent">父实体</param>
Task<List<TEntity>> GetAllChildrenAsync(TEntity parent);
/// <summary>
/// 更新实体及所有下级节点路径
/// </summary>
/// <param name="entity">实体</param>
Task UpdatePathAsync(TEntity entity);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem_4___We_All_Love_Bits_
{
class Program
{
static void Main()
{
Console.WriteLine("Enter how many numbers you want to transform and then the numbers:");
ushort userInput = ushort.Parse(Console.ReadLine());
int p = 0;
int pReversed = 0;
int pInversed = 0;
int [] pNew = new int [userInput];
for (int index = 0; index < userInput; index++)
{
p = int.Parse(Console.ReadLine()); // read from the concole
// turn zeroes to ones and ones to zeroes
int nextNum = p;
while (nextNum > 0)
{
pReversed <<= 1;
if ((nextNum & 1) == 1)
{
pReversed |= 1;
}
nextNum >>= 1;
}
// generate second number form userInput
pInversed = p;
int position = 0;
int n = p;
while (n >= 1)
{
int mask = 1 << position;
int nAndMask = pInversed & mask;
pInversed = pInversed ^ mask;
position++;
n >>= 1;
}
pNew[index] = (p ^ pInversed) & pReversed; // fill arrray with results
}
foreach (var num in pNew) //print new numbers
{
Console.WriteLine(num);
}
}
}
}
/* solution
using System;
02
03
class WeAllLoveBits
04
{
05
static void Main()
06
{
07
// Read N
08
int n = int.Parse(Console.ReadLine());
09
10
// For all N numbers
11
for (int i = 1; i < = n; i++)
12
{
13
// Read P
14
int p = int.Parse(Console.ReadLine());
15
16
// calculate pNew
17
int pNew = 0;
18
while (p > 0)
19
{
20
pNew < < = 1;
21
if ((p & 1) == 1)
22
{
23
pNew |= 1;
24
}
25
p > > = 1;
26
}
27
28
// Write pNew
29
Console.WriteLine(pNew);
30
}
31
}
32
}
*/ |
namespace SteamApiTest.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class hello1 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.GameLists",
c => new
{
Id = c.Int(nullable: false, identity: true),
NumOfStars = c.Int(nullable: false),
ListOwner_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.ListOwner_Id, cascadeDelete: true)
.Index(t => t.ListOwner_Id);
CreateTable(
"dbo.Games",
c => new
{
Id = c.Int(nullable: false, identity: true),
GBID = c.String(),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Users",
c => new
{
Id = c.Int(nullable: false, identity: true),
Username = c.String(),
FirstName = c.String(),
LastName = c.String(),
Password = c.String(),
Email = c.String(),
Country = c.String(),
DoB = c.DateTime(nullable: false),
Steam64 = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.GameGameLists",
c => new
{
Game_Id = c.Int(nullable: false),
GameList_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Game_Id, t.GameList_Id })
.ForeignKey("dbo.Games", t => t.Game_Id, cascadeDelete: true)
.ForeignKey("dbo.GameLists", t => t.GameList_Id, cascadeDelete: true)
.Index(t => t.Game_Id)
.Index(t => t.GameList_Id);
CreateTable(
"dbo.GameUsers",
c => new
{
Game_Id = c.Int(nullable: false),
User_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Game_Id, t.User_Id })
.ForeignKey("dbo.Games", t => t.Game_Id, cascadeDelete: true)
.ForeignKey("dbo.Users", t => t.User_Id, cascadeDelete: true)
.Index(t => t.Game_Id)
.Index(t => t.User_Id);
}
public override void Down()
{
DropForeignKey("dbo.GameUsers", "User_Id", "dbo.Users");
DropForeignKey("dbo.GameUsers", "Game_Id", "dbo.Games");
DropForeignKey("dbo.GameLists", "ListOwner_Id", "dbo.Users");
DropForeignKey("dbo.GameGameLists", "GameList_Id", "dbo.GameLists");
DropForeignKey("dbo.GameGameLists", "Game_Id", "dbo.Games");
DropIndex("dbo.GameUsers", new[] { "User_Id" });
DropIndex("dbo.GameUsers", new[] { "Game_Id" });
DropIndex("dbo.GameGameLists", new[] { "GameList_Id" });
DropIndex("dbo.GameGameLists", new[] { "Game_Id" });
DropIndex("dbo.GameLists", new[] { "ListOwner_Id" });
DropTable("dbo.GameUsers");
DropTable("dbo.GameGameLists");
DropTable("dbo.Users");
DropTable("dbo.Games");
DropTable("dbo.GameLists");
}
}
}
|
using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
using UnityEngine;
namespace Needle.Demystify
{
internal static class Hyperlinks
{
private static readonly Regex hyperlinks = new Regex(@"((?<brackets>\))?(?<prefix> in) (?<file>.*?):line (?<line>\d+)(?<post>.*))",
RegexOptions.Compiled | RegexOptions.Multiline);
public static void FixStacktrace(ref string stacktrace)
{
var lines = stacktrace.Split(new []{'\n'}, StringSplitOptions.RemoveEmptyEntries);
stacktrace = string.Empty;
foreach (var t in lines)
{
var line = t;
// hyperlinks capture
var path = Fix(ref line);
if (!string.IsNullOrEmpty(path))
{
path = path.Replace("\n", "");
line += ")" + path;
Filepaths.TryMakeRelative(ref line);
}
stacktrace += line + "\n";
}
}
/// <summary>
/// parse demystify path format and reformat to unity hyperlink format
/// </summary>
/// <param name="line"></param>
/// <returns>hyperlink that must be appended to line once further processing is done</returns>
public static string Fix(ref string line)
{
var match = hyperlinks.Match(line);
if (match.Success)
{
var file = match.Groups["file"];
var lineNr = match.Groups["line"];
var brackets = match.Groups["brackets"].ToString();
if (string.IsNullOrEmpty(brackets)) brackets = ")";
var post = match.Groups["post"];
var end = line.Substring(match.Index, line.Length - match.Index);
line = line.Remove(match.Index, end.Length) + brackets;
var newString = " (at " + file + ":" + lineNr + ")\n";
if (post.Success)
newString += post;
return newString;
}
return string.Empty;
}
public static void ApplyHyperlinkColor(ref string stacktrace)
{
if (string.IsNullOrEmpty(stacktrace)) return;
var str = stacktrace;
const string pattern = @"(?<open>\(at )(?<pre><a href=.*?>)(?<path>.*)(?<post><\/a>)(?<close>\))";
str = Regex.Replace(str, pattern, m =>
{
if (m.Success && SyntaxHighlighting.CurrentTheme.TryGetValue("link", out var col))
{
var open = "in ";// m.Groups["open"].Value;
var close = string.Empty;// m.Groups["close"].Value;
var pre = m.Groups["pre"].Value;
var post = m.Groups["post"].Value;
var path = m.Groups["path"].Value;
ModifyFilePath(ref path);
var col_0 = $"<color={col}>";
var col_1 = "</color>";
var res = $"{col_0}{open}{col_1}{pre}{col_0}{path}{col_1}{post}{col_0}{close}{col_1}";
return res;
}
return m.Value;
},
RegexOptions.Compiled);
stacktrace = str;
}
private static readonly Regex capturePackageNameInPath = new Regex(@".+[/\\](?<packageName>\w+\...+?)[/\\](.*)?[/\\](?<fileName>.*)$", RegexOptions.Compiled);
private static void ModifyFilePath(ref string path)
{
if (DemystifySettings.instance.ShortenFilePaths == false) return;
// Debug.Log(path);
// var lineNumberStart = path.LastIndexOf(':');
// if(lineNumberStart > 0)
// path = path.Substring(0, lineNumberStart);
// var fileNameIndexStart = path.LastIndexOf('/');
// if (fileNameIndexStart > 0)
// path = path.Substring(fileNameIndexStart + 1);
var isPackageCache = path.Contains("PackageCache");
var match = capturePackageNameInPath.Match(path);
if (match.Success)
{
var package = match.Groups["packageName"].Value;
var file = match.Groups["fileName"].Value;
if (!string.IsNullOrEmpty(package) && !string.IsNullOrEmpty(file))
{
path = package + "/" + file;
if (isPackageCache) path = "PackageCache/" + path;
}
}
}
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace trade.client
{
public class ConfigLoader
{
private const string FileName = "config.json";
public static ConfigLoader Load(string filename = FileName)
{
if (!File.Exists(filename)) return new ConfigLoader();
string json = File.ReadAllText(filename);
return JsonConvert.DeserializeObject<ConfigLoader>(json);
}
public static void Save(ConfigLoader configs, string filename = FileName)
{
string json = JsonConvert.SerializeObject(configs, Formatting.Indented);
File.WriteAllText(filename, json);
}
public List<Config> Configs { set; get; }
public List<string> Accounts { set; get; }
public ConfigLoader()
{
Configs = new List<Config>();
Accounts = new List<string>();
}
public void Save(string filename = FileName)
{
Save(this, filename);
}
}
public class Config
{
public string Name { set; get; }
public string TradeHost { set; get; }
public int TradeOrderPort { set; get; }
public int TradeReportPort { set; get; }
public int TradeQueryPort { set; get; }
public string ReferenceAddress { set; get; }
public string Level2Address { set; get; }
public string ComplianceHost { set; get; }
public int ComplianceReportPort { set; get; }
}
}
|
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using Microsoft.Bot.Connector;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Vision.Models;
using Vision.Extensions;
using System.Web;
namespace Vision.Dialogs
{
[LuisModel("cea37070-74fc-40e1-8b1e-1ce0d6f2be23", "e686ad6ca03b4cf29d26288783935568")]
[Serializable]
public class VisonLuisDialog : LuisDialog<object>
{
public String current = "";
public String phone = "";
public const string EntityNameCity = "location";
public const string OpenWeatherMapApiKey = "0336767b42b40c645b1e00afdd8a803";
public const string TraktApiKey = "87b237d0ecf17ee943c258835dffc5f87c4756d19f3b62c3193b128328bb0c1e";
public String getImageUrlShows(String imdb)
{
String url = "";
using (var client = new HttpClient { BaseAddress = new Uri("https://api.trakt.tv/") })
{
client.DefaultRequestHeaders.TryAddWithoutValidation("trakt-api-version", "2");
client.DefaultRequestHeaders.TryAddWithoutValidation("trakt-api-key", "468a92c26d3411be7886881b7f40afea47288963a91d9c5a0f43257521ceab74");
//client.DefaultRequestHeaders.TryAddWithoutValidation("trakt-api-version", "2");
//client.DefaultRequestHeaders.Add("trakt.api.key", "468a92c26d3411be7886881b7f40afea47288963a91d9c5a0f43257521ceab74");
using (var response = client.GetAsync("search/imdb/" + imdb + "?extended=images").Result)
{
var responseString = response.Content.ReadAsStringAsync().Result;
var responseJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<List<anticipated>>(responseString);
url = responseJSON[0].movie.images.fanart.full;
}
}
return url;
}
[LuisIntent("intent.number")]
public async Task number(IDialogContext context, LuisResult result)
{
string message = $"Selection error please try use the .Search Command";
if (current == "menu")
{
if (result.Query.ToLower().ToString().Contains("1"))
{
message = $"comming soon";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("2"))
{
message = $"Vision SMS{Environment.NewLine}{Environment.NewLine}To Send A message Simply use the following format {Environment.NewLine}{Environment.NewLine}.SMS[Space][Phone Number you wish to send to]{Environment.NewLine}{Environment.NewLine}>Note:There are limited Sms's are avalible per day";
current = "sms";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("3"))
{
message = $"{Environment.NewLine}{Environment.NewLine}Select from the following.{Environment.NewLine}{Environment.NewLine} > 1) Anticipated Movies {Environment.NewLine}{Environment.NewLine} > 2) Most Played Movies {Environment.NewLine}{Environment.NewLine} > 3) Popular Movies {Environment.NewLine}{Environment.NewLine} > 4) Trending Movies";
await context.PostAsync(message);
context.Wait(MessageReceived);
result.Query="";
current = "movies";
}
if (result.Query.ToLower().ToString().Contains("4"))
{
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("5"))
{
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("6"))
{
String helpMenu = $"{Environment.NewLine}{Environment.NewLine}Vision SupportMenu.{Environment.NewLine}{Environment.NewLine} > 1) News {Environment.NewLine}{Environment.NewLine} > 2) Sms {Environment.NewLine}{Environment.NewLine} > 3) Vision Movies {Environment.NewLine}{Environment.NewLine} > 4) Vision Weather {Environment.NewLine}{Environment.NewLine} > 5) Vision Commands {Environment.NewLine}{Environment.NewLine} > 6) Vision Support {Environment.NewLine}{Environment.NewLine} > 7) Vision Search ";
String hint = $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}HINT:" + " Please enter the number from the this menu you require help with";
message = $"" + helpMenu + hint; current = "help";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("7"))
{
message = $"Enter what you wish to search ";
current = "search";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
}
if (current == "help")
{
if (result.Query.ToLower().ToString().Contains("1"))
{
message = $"News Gives you a list of links of news papers ";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("2"))
{
message = $"comming soon";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("3"))
{
message = $"comming soon";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("4"))
{
message = $"comming soon";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("5"))
{
message = $"comming soon";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("6"))
{
message = $"comming soon";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
}
if (current == "movies")
{
if (result.Query.ToLower().ToString().Contains("1"))
{
message = $"News Gives you a list of links of news papers ";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("2"))
{
message = $"comming soon";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("3"))
{
message = $"comming soon";
await Popular(context, result);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("4"))
{
message = $"comming soon";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
}
}
[LuisIntent("")]
public async Task None(IDialogContext context, LuisResult result)
{
string message = $"Sorry I did not understand :pensive: ";
if (current == "menu")
{
message = $"Sorry view the help documentation for more assistance :pensive:";
current = "";
}
if (current == "sms")
{
String answer = result.Query.ToLower().ToString();
int n;
bool isNumeric = int.TryParse(answer, out n);
if(isNumeric==true){
if(answer.Length == 9)
{
}
else { message = $"There is a problem with the number you sent please try again or use .reset command to reset :pensive:"; }
}
}
else { message = $"There is a problem with the number you sent please try again or use .reset command to reset :pensive:"; }
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("command")]
public async Task command(IDialogContext context, LuisResult result)
{
string message = "command Unknown";
if (result.Query.ToLower().ToString().Contains("men"))
{
current = "";
String menu = $"{Environment.NewLine}{Environment.NewLine}Vision MainMenu.{Environment.NewLine}{Environment.NewLine} > 1) News {Environment.NewLine}{Environment.NewLine} > 2) Sms {Environment.NewLine}{Environment.NewLine} > 3) Vision Movies {Environment.NewLine}{Environment.NewLine} > 4) Vision Weather {Environment.NewLine}{Environment.NewLine} > 5) Vision Commands {Environment.NewLine}{Environment.NewLine} > 6) Vision Support {Environment.NewLine}{Environment.NewLine} > 7) Vision Search ";
String options = $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}HINT:"+" You can also use the .Search command as well as other commands for easy access";
message = $""+ menu + options;
current = "menu";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains("hel"))
{
String helpMenu = $"{Environment.NewLine}{Environment.NewLine}Vision SupportMenu.{Environment.NewLine}{Environment.NewLine} > 1) News {Environment.NewLine}{Environment.NewLine} > 2) Sms {Environment.NewLine}{Environment.NewLine} > 3) Vision Movies {Environment.NewLine}{Environment.NewLine} > 4) Vision Weather {Environment.NewLine}{Environment.NewLine} > 5) Vision Commands {Environment.NewLine}{Environment.NewLine} > 6) Vision Support {Environment.NewLine}{Environment.NewLine} > 7) Vision Search ";
String hint = $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}HINT:" + " Please enter the number from the this menu you require help with";
message = $"" + helpMenu+hint; current = "help";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains(".list"))
{
//5 result.Query = "";
current = "list";
await Popular(context, result);
}
if (result.Query.ToLower().ToString().Contains(".sms"))
{
await context.PostAsync(message);
context.Wait(MessageReceived);
}
if (result.Query.ToLower().ToString().Contains(".res"))
{
current = "";
message = "Sysytem has been reset...";
await context.PostAsync(message);
context.Wait(MessageReceived);
}
}
[LuisIntent("convo")]
public async Task convo(IDialogContext context, LuisResult result)
{
current = "";
String[] greet = { "Hey there :grinning: ",
"Hello can i help you with anything today",
"Hey! Its good to have you on board my friend.",
"Hey i was wondering when you would use me"};
Random rand = new Random();
int chooseGreetingMessage = rand.Next(0, 5);
String greetingMessage = greet[chooseGreetingMessage];
string message = "";
if (result.Query.ToLower().ToString().Contains("hey"))
{
message = ($"" + greetingMessage);
}
if (result.Query.ToLower().ToString().Contains("time"))
{
DateTime time = DateTime.Now;
message = ($"The Time is :" + (time.ToString("h:mm:ss tt")));
}
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("intent.vision.show")]
public async Task show(IDialogContext context, LuisResult result)
{
current = "";
//bat man
var ImagesUrl = new Uri("https://www.youtube.com/watch?v=eX_iASz1Si8");
var ImagesUrl1 = new Uri("https://i.ytimg.com/vi/AVyMJ1k2Rac/maxresdefault.jpg");
var ImagesUr2 = new Uri("https://www.youtube.com/watch?v=YoHD9XEInc0");
var ImagesUrl2 = new Uri("http://medicalfuturist.com/wp-content/media/2013/12/inception-collapsing.jpeg");
var ImagesUr3 = new Uri("https://www.youtube.com/watch?v=JAUoeqvedMo");
var ImagesUrl3 = new Uri("http://wallpapercave.com/wp/fhhj9Vv.jpg");
var ImagesUr4 = new Uri("https://www.youtube.com/watch?v=FyKWUTwSYAs");
var ImagesUrl4 = new Uri("https://i.ytimg.com/vi/yV-NnN4pOng/maxresdefault.jpg");
var ImagesUr5 = new Uri("https://www.youtube.com/watch?v=d96cjJhvlMA");
var ImagesUrl5 = new Uri("http://www.shauntmax30.com/data/out/17/1069911-pictures-of-guardians-of-the-galaxy-hd.jpeg");
var ImagesUrl9=("http://dev.virtualearth.net/REST/V1/Imagery/Map/Road/Umhlanga%20kwazulu-natal?mapLayer=TrafficFlow&key=AtJOhxfxUJ4T7fnHzflbMVKBJz4qsrcbj-tYuBXtKYewQfOr2O_Dgch2yDw36wxz");
var ImagesUrl8 = new Uri("http://dev.virtualearth.net/REST/v1/Imagery/Map/AerialWithLabels/Durban%20Center?mapSize=500,400&key=AtJOhxfxUJ4T7fnHzflbMVKBJz4qsrcbj-tYuBXtKYewQfOr2O_Dgch2yDw36wxz");
var ImagesUrl6 = new Uri("http://dev.virtualearth.net/REST/v1/Imagery/Map/AerialWithLabels/Umhlanga%20kwazulu-natal?mapSize=500,400&key=AtJOhxfxUJ4T7fnHzflbMVKBJz4qsrcbj-tYuBXtKYewQfOr2O_Dgch2yDw36wxz");
var ImagesUr6 = new Uri("https://www.youtube.com/watch?v=eX_iASz1Si8");
var ImagesUr7 = new Uri("https://www.youtube.com/watch?v=eX_iASz1Si8");
var ImagesUrl7 = new Uri("https://media.licdn.com/mpr/mpr/shrinknp_400_400/p/3/000/27d/34f/1cbc766.jpg");
string message = "";
if (result.Query.ToLower().ToString().Contains("batman"))
{
message = ($"[]");
}
if (result.Query.ToLower().ToString().Contains("inception"))
{
message = ($"[]");
}
if (result.Query.ToLower().ToString().Contains("the avengers"))
{
message = ($"[]");
}
if (result.Query.ToLower().ToString().Contains("deadpool"))
{
message = ($"[]");
}
if (result.Query.ToLower().ToString().Contains(" guardians"))
{
message = ($"[](" + ImagesUr5 + ")");
}
if (result.Query.ToLower().ToString().Contains("naik"))
{
message = ($"[]");
}
if (result.Query.ToLower().ToString().Contains("map"))
{
message = ($"[]");
}
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("intent.vision.search")]
public async Task search(IDialogContext context, LuisResult result)
{
current = "";
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString["q"] = "bill gates";
queryString["count"] = "10";
queryString["offset"] = "0";
queryString["mkt"] = "en-us";
queryString["safesearch"] = "Moderate";
// using (var client = new HttpClient { BaseAddress = new Uri("https://api.cognitive.microsoft.com/bing/v5.0/search?q=bill gates&count=10&offset=0&mkt=en-us&safesearch=Moderate") })
{
var uri = "https://api.cognitive.microsoft.com/bing/v5.0/search?" + queryString;
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "f471964855c94e518c7049820f5b8658");
var response = await client.GetAsync(uri);
// var response = await client.GetAsync("movies/trending");
var responseString = await response.Content.ReadAsStringAsync();
var responseJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<List<VisonSearch>>(responseString);
}
string message = $"lol: " + string.Join(", ", result.Intents.Select(i => i.Intent));
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("intent.vision.trending")]
public async Task Trending(IDialogContext context, LuisResult result)
{
current = "";
using (var client = new HttpClient { BaseAddress = new Uri("https://api.trakt.tv") })
{
client.DefaultRequestHeaders.Add("trakt-api-key", "87b237d0ecf17ee943c258835dffc5f87c4756d19f3b62c3193b128328bb0c1e");
var response = await client.GetAsync("movies/trending");
var responseString = await response.Content.ReadAsStringAsync();
var responseJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TrendingMovie>>(responseString);
}
string message = $"lol: " + string.Join(", ", result.Intents.Select(i => i.Intent));
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("intent.vision.anticipated")]
public async Task Anticipated(IDialogContext context, LuisResult result)
{
current = "";
using (var client = new HttpClient { BaseAddress = new Uri("https://api.trakt.tv") })
{
client.DefaultRequestHeaders.Add("trakt-api-key", "87b237d0ecf17ee943c258835dffc5f87c4756d19f3b62c3193b128328bb0c1e");
var response = await client.GetAsync("movies/anticipated");
var responseString = await response.Content.ReadAsStringAsync();
var responseJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TrendingMovie>>(responseString);
}
string message = $"lol: " + string.Join(", ", result.Intents.Select(i => i.Intent));
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("intent.vision.popular")]
public async Task Popular(IDialogContext context, LuisResult result)
{
int count = 0;
String output = "Popular movies";
using (var client = new HttpClient { BaseAddress = new Uri("https://api.trakt.tv") })
{
client.DefaultRequestHeaders.Add("trakt-api-key", "87b237d0ecf17ee943c258835dffc5f87c4756d19f3b62c3193b128328bb0c1e");
var response = await client.GetAsync("movies/popular");
var responseString = await response.Content.ReadAsStringAsync();
var responseJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Movie>>(responseString);
if(current=="list")
{
for (int i = 0; i < responseJSON.Count; i++)
{
count++;
String kk = responseJSON[i].ids.imdb;
String image = $"[ + ")](" + getImageUrlShows(kk) + ")";
output += $"{Environment.NewLine}{Environment.NewLine} > " + count + ")" + responseJSON[i].title;
current = "";
}
}
else
{
for (int i = 0; i < responseJSON.Count; i++)
{
count++;
current = "popular";
String kk = responseJSON[i].ids.imdb;
String image = $"[ + ")](" + getImageUrlShows(kk) + ")";
output += $"{Environment.NewLine}{Environment.NewLine} > " + count + ")" + responseJSON[i].title+image;
}
}
}
string message = $"" + output;
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("intent.vision.weather")]
public async Task CurrentWeather(IDialogContext context, LuisResult result)
{
current = "";
using (var client = new HttpClient())
{
int count = 0;
string output = "Ishu";
var city = result.TryFindEntity(EntityNameCity).Entity;
var url = $"http://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={OpenWeatherMapApiKey}";
var response = await client.GetAsync(url);
var res = await response.Content.ReadAsStringAsync();
var currentWeather = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentWeatherResponse>(res);
await context.PostAsync($"{currentWeather.weather.First().description} in {city} and a temperature of {currentWeather.main.temp}°C");
context.Wait(MessageReceived);
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.