text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using Chat.ViewModels;
using DAL.Models;
using DAL.UserData;
namespace Chat.UserManagement
{
internal class UserManager : IUserManager
{
private readonly UserDataProvider _userDataProvider;
private readonly List<IRegistrationHandler> _registrationHandlers;
public UserManager()//TODO add configuration and instance creating
{
_userDataProvider = new UserDataProvider();
}
public LoginResult Login(string login, string password)
{
var filter = new UserFilter();
if (login.Contains('@'))
{
filter.Email = login;
}
else
{
filter.Login = login;
}
var users = _userDataProvider.GetUsersByFilter(filter);
if (users.Count == 0)
{
return new LoginResult()
{
Error = "User does not exists",
Success = false,
UserId = 0
};
}
if (users[0].IsBlocked)
{
return new LoginResult()
{
Error = "User is blocked",
Success = false,
UserId = 0
};
}
if (!CheckUserPassword(password,users[0]))
{
return new LoginResult()
{
Error = "Invalid password",
Success = false,
UserId = 0
};
}
return new LoginResult()
{
Error = null,
Success = true,
UserId = users[0].Id,
UserName = users[0].Login
};
}
public User GetUserById(long id)
{
throw new NotImplementedException();
}
public List<User> GetUsersByFilter(UserFilter filter)
{
throw new NotImplementedException();
}
public SaveUserResult SaveUser(User user)
{
throw new NotImplementedException();
}
public SaveUserResult CreateUser(RestUserRegistrationInfo userInfo)
{
long userId = 0;
UserFilter filter = new UserFilter()
{
Email = userInfo.Email,
Login = userInfo.Login
};
if (_userDataProvider.GetUsersByFilterCountOR(filter) > 0)
{
return new SaveUserResult()
{
Error = "User already exists",
IsNew = false,
Success = false,
UserId = 0
};
}
User user = CreateUserModel(userInfo);
userId = _userDataProvider.SaveUser(user);
if (userId != 0)
{
return new SaveUserResult()
{
Error = "",
IsNew = true,
Success = true,
UserId = userId
};
}
return new SaveUserResult()
{
Error = "Unable to save user",
IsNew = false,
Success = false,
UserId = 0
};
}
private User CreateUserModel(RestUserRegistrationInfo userInfo)
{
var salt = PasswordUtil.CreateSalt(15);
var hash = PasswordUtil.GenerateSaltedHash(userInfo.Password, salt);
User user = new User()
{
Email = userInfo.Email,
Login = userInfo.Login,
Salt = Convert.ToBase64String(salt),
PasswordHash = Convert.ToBase64String(hash),
UpdDate = DateTime.Now
};
return user;
}
private bool CheckUserPassword(string password,User user)
{
var salt = Convert.FromBase64String(user.Salt);
var hash = Convert.FromBase64String(user.PasswordHash);
var newHash = PasswordUtil.GenerateSaltedHash(password, salt);
return PasswordUtil.CompareByteArrays(hash, newHash);
}
public void RegisterUser(long userId)//TODO add handler if needed
{
if (_registrationHandlers != null)
{
foreach (var rgHandler in _registrationHandlers)
{
rgHandler.Handle(userId);
}
}
}
}
}
|
using MetroFramework;
using MetroFramework.Forms;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.DB.Utils;
using PDV.DAO.Entidades.Financeiro;
using PDV.DAO.Enum;
using PDV.VIEW.App_Context;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace PDV.VIEW.Forms.Cadastro.Financeiro.Modulo
{
public partial class FCAFIN_Credito : DevExpress.XtraEditors.XtraForm
{
private string NOME_TELA = "CADASTRO DE CRÉDITO";
private List<ContaBancaria> Contas = null;
private List<Natureza> Naturezas = null;
public FCAFIN_Credito()
{
InitializeComponent();
ovTXT_Valor.AplicaAlteracoes();
Contas = FuncoesContaBancaria.GetContasBancarias();
ovCMB_ContaBancaria.DataSource = Contas;
ovCMB_ContaBancaria.DisplayMember = "nome";
ovCMB_ContaBancaria.ValueMember = "idcontabancaria";
ovCMB_ContaBancaria.SelectedItem = null;
Naturezas = FuncoesNatureza.GetNaturezasPorTipo(0);
ovCMB_Natureza.DataSource = Naturezas;
ovCMB_Natureza.DisplayMember = "descricao";
ovCMB_Natureza.ValueMember = "idnatureza";
ovCMB_Natureza.SelectedItem = null;
}
private void metroButton5_Click(object sender, EventArgs e)
{
Close();
}
private void metroButton4_Click(object sender, EventArgs e)
{
try
{
PDVControlador.BeginTransaction();
Validar();
decimal? IDNatureza = null;
if (ovCMB_Natureza.SelectedItem != null)
IDNatureza = (ovCMB_Natureza.SelectedItem as Natureza).IDNatureza;
if (!FuncoesMovimentoBancario.Salvar(new MovimentoBancario
{
IDMovimentoBancario = Sequence.GetNextID("MOVIMENTOBANCARIO", "IDMOVIMENTOBANCARIO"),
IDContaBancaria = (ovCMB_ContaBancaria.SelectedItem as ContaBancaria).IDContaBancaria,
IDNatureza = IDNatureza,
Documento = ovTXT_Documento.Text,
Historico = ovTXT_Historico.Text,
Sequencia = 1,
Valor = ovTXT_Valor.Value,
DataMovimento = DateTime.Now,
Tipo = 1
}, TipoOperacao.INSERT))
throw new Exception("Não foi possível salvar o Crédito.");
PDVControlador.Commit();
MessageBox.Show(this, "Crédito salvo com sucesso.", NOME_TELA);
Close();
}
catch (Exception Ex)
{
PDVControlador.Rollback();
MessageBox.Show(this, Ex.Message, NOME_TELA);
}
}
private void Validar()
{
if (ovCMB_ContaBancaria.SelectedItem == null)
throw new Exception("Selecione o Portador.");
if (ovTXT_Valor.Value == 0)
throw new Exception("O Valor não pode ser igual a zero.");
}
private void FCAFIN_Credito_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Escape:
this.Close();
break;
}
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Web;
namespace BetaDota2StatsMVC.Models
{
public class MatchesHistory
{
[Display(Name = "Match ID")]
public long Match_id { get; set; }
[Display(Name = "Player Slot")]//ti einai auto?
public int Player_slot { get; set; }
[Display(Name = "Who Won")]
public bool Radiant_win { get; set; }
//[Display(Name = "Match Duration")]
public int Duration { get; set; }
[Display(Name = "Game Mode")]
public int Game_mode { get; set; }
[Display(Name = "Normal or Rank")]
public int Lobby_type { get; set; }
[Display(Name = "Hero Name")]
public int Hero_id { get; set; }
public int Start_time { get; set; }
public int? Version { get; set; }
public int Kills { get; set; }
public int Deaths { get; set; }
public int Assists { get; set; }
[Display(Name = "Skill LVL")]
public int? Skill { get; set; }
[Display(Name ="Game had Leaver")]
public int Leaver_status { get; set; }
[Display(Name ="Solo or Party")]
public int? Party_size { get; set; }
//public Dictionary<int, Hero> GetAllHeroes()
//{
// string SourcePath = "C:\\Users\\sapol\\source\\repos\\BetaDota2StatsMVC\\BetaDota2StatsMVC\\Data_JSON\\heroes.json";
// using (StreamReader r = new StreamReader(SourcePath))
// {
// string json = r.ReadToEnd();
// Dictionary<int, Hero> allHeroes999 = JsonConvert.DeserializeObject<Dictionary<int, Hero>>(json);
// return allHeroes999;
// }
//}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using personal_site.Helpers;
using personal_site.Models;
using personal_site.Services;
using personal_site.ViewModels;
namespace personal_site.Areas.Admin.Controllers
{
[Authorize(Roles = "Admin")]
public class BlogController : Controller
{
public async Task<ActionResult> Index()
{
List<BlogPost> blogList = await BlogService.GetInstance().GetBlogPosts();
ViewBag.BlogList = blogList;
return View("../Blog");
}
public async Task<ActionResult> GetBlogList()
{
BlogService blogService = BlogService.GetInstance();
string blogListJson = await blogService.GetBlogsPostsJson();
return ControllerHelper.JsonObjectResponse(blogListJson);
}
public async Task<ActionResult> SaveBlogPost(AdminBlogEditViewModel model)
{
BlogService blogService = BlogService.GetInstance();
BlogPost savedBlogPost = await blogService.SaveBlogPost(model);
if (savedBlogPost != null)
return ControllerHelper.JsonActionResponse(true, "Saved Blog Post");
else
return ControllerHelper.JsonActionResponse(false, "Failed to save blog post");
}
public async Task<ActionResult> RemoveBlogPost(int blogId)
{
BlogService blogService = BlogService.GetInstance();
bool blogRemoved = await blogService.RemoveBlogPost(blogId);
if (blogRemoved)
return ControllerHelper.JsonActionResponse(true, "Blog post has been removed");
else
return ControllerHelper.JsonActionResponse(false, "Failed to remove blog post");
}
public async Task<ActionResult> RemoveBlogComment(AdminEntityRemovalViewModel model)
{
BlogService blogService = BlogService.GetInstance();
bool commentRemoved = await blogService.RemoveBlogPostComment(model.EntityId);
if (commentRemoved)
return ControllerHelper.JsonActionResponse(true, "Comment has been removed");
else
return ControllerHelper.JsonActionResponse(false, "Failed to remove comment");
}
}
} |
using System;
using AreasLib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AreasTest
{
[TestClass]
public class TriangleTests
{
private const string PrecisionArea = "E10";
[TestMethod]
public void AreaOk1()
{
var a = 3d;
var b = 4d;
var c = 5d;
var etalon = 6d;
var (area, e) = TriangleHelper.Area(a, b, c);
Console.WriteLine($"Error:{e.ToString()}\r\nAnswer:{area.ToString(PrecisionArea)}\r\nEtalon:{etalon.ToString(PrecisionArea)}");
Assert.AreEqual(Errors.None, e);
Assert.AreEqual(etalon.ToString(PrecisionArea), area.ToString(PrecisionArea));
}
[TestMethod]
public void AreaOk2()
{
var a = 5.08d;
var b = 3.94d;
var c = 8.91d;
var etalon = 3.1025589091d;
var (area, e) = TriangleHelper.Area(a, b, c);
Console.WriteLine($"Error:{e.ToString()}\r\nAnswer:{area.ToString(PrecisionArea)}\r\nEtalon:{etalon.ToString(PrecisionArea)}");
Assert.AreEqual(Errors.None, e);
Assert.AreEqual(etalon.ToString(PrecisionArea), area.ToString(PrecisionArea));
}
[TestMethod]
public void AreaFail1()
{
var a = -5.08d;
var b = 3.94d;
var c = 8.91d;
var (area, e) = TriangleHelper.Area(a, b, c);
Console.WriteLine($"Error:{e.ToString()}\r\nAnswer:{area.ToString(PrecisionArea)}");
Assert.AreEqual(Errors.NegativeSide, e);
Assert.AreEqual((-1).ToString(PrecisionArea), area.ToString(PrecisionArea));
}
[TestMethod]
public void AreaFail2()
{
var a = 5.08d;
var b = 33.94d;
var c = 8.91d;
var (area, e) = TriangleHelper.Area(a, b, c);
Console.WriteLine($"Error:{e.ToString()}\r\nAnswer:{area.ToString(PrecisionArea)}");
Assert.AreEqual(Errors.WrongSides, e);
Assert.AreEqual((-1).ToString(PrecisionArea), area.ToString(PrecisionArea));
}
}
}
|
using System.Collections.ObjectModel;
using System.Data;
using System.Reflection;
namespace Kit
{
public static class Linq
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
public static List<T>[] Divide<T>(this IEnumerable<T> lista, int dividir)
{
if (dividir <= 0)
{
throw new ArgumentOutOfRangeException("No puede dividir una lista entre:" + dividir);
}
List<T>[] resultado = new List<T>[dividir];
if (lista?.Count() < 0)
{
return resultado;
}
int xlista = lista.Count() / dividir;
if (xlista <= 0) { xlista = 1; }
int rango = 0;
for (int i = 0; i < dividir; i++)
{
if (rango + xlista > lista.Count())
{
continue;
}
resultado[i] = new List<T>(lista.GetRange(rango, xlista));
rango += xlista;
}
if (rango < lista.Count())
{
resultado[0].AddRange(lista.GetRange(rango, lista.Count() - rango));
}
return resultado;
}
public static IEnumerable<T> GetRange<T>(this IEnumerable<T> input, int start, int end)
{
int i = 0;
foreach (T item in input)
{
if (i < start) continue;
if (i > end) break;
yield return item;
i++;
}
}
public static List<T> Unir<T>(this List<T> lista, params List<T>[] listas)
{
foreach (List<T> l in listas)
{
lista.AddRange(l);
}
return lista;
}
public static List<T> Prepend<T>(this List<T> list, params T[] elements)
{
foreach (T element in elements.Reverse())
{
list.Insert(0, element);
}
return list;
}
public static int Mult(this IEnumerable<int> source, Func<int, int> sumFunc)
{
return source.Aggregate(1, (a, b) => a * sumFunc.Invoke(b));
}
public static int Mult<T>(this IEnumerable<T> source, Func<T, int> sumFunc)
{
return source.Aggregate(1, (a, b) => a * sumFunc.Invoke(b));
}
public static double Mult<T>(this IEnumerable<T> source, Func<T, double> sumFunc)
{
return source.Aggregate(1d, (a, b) => a * sumFunc.Invoke(b));
}
public static float Mult<T>(this IEnumerable<T> source, Func<T, float> sumFunc)
{
return source.Aggregate(1f, (a, b) => a * sumFunc.Invoke(b));
}
public static int FindIndexOf<T>(this IList<T> modificadoresSeleccionados, IEquatable<T> p)
{
if (p is null)
{
return modificadoresSeleccionados.FindIndexOf(x => x is null);
}
return modificadoresSeleccionados.FindIndexOf(x => p.Equals(x));
}
public static int FindIndexOf<T>(this IList<T> modificadoresSeleccionados, Func<T, bool> p)
{
for (int i = 0; i < modificadoresSeleccionados.Count; i++)
{
T elemento = modificadoresSeleccionados[i];
if (p.Invoke(elemento))
{
return i;
}
}
return -1;
}
public static int FindIndexOf<T>(this ObservableCollection<T> modificadoresSeleccionados, Func<T, bool> p)
{
for (int i = 0; i < modificadoresSeleccionados.Count; i++)
{
T elemento = modificadoresSeleccionados[i];
if (p.Invoke(elemento))
{
return i;
}
}
return -1;
}
public static int FindIndex<T>(this ObservableCollection<T> ts, Predicate<T> match)
{
return ts.FindIndex(0, ts.Count, match);
}
public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, Predicate<T> match)
{
return ts.FindIndex(startIndex, ts.Count, match);
}
public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, int count, Predicate<T> match)
{
if (startIndex < 0) startIndex = 0;
if (count > ts.Count) count = ts.Count;
for (int i = startIndex; i < count; i++)
{
if (match(ts[i])) return i;
}
return -1;
}
public static void AddRange<T>(this ICollection<T> ts, params T[] pelementos)
{
ts.AddRange<T>(elementos: pelementos);
}
public static void AddRange<T>(this ICollection<T> ts, IEnumerable<T> elementos)
{
foreach (T elemento in elementos)
{
ts.Add(elemento);
}
}
#if NETSTANDARD1_0 || NETSTANDARD2_0 || NET462
/// <summary>
/// Convierte cualquier tabla a una Lista de objectos siempre que tengan campos publicos en común y un constructor publico sin parametros
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable data)
{
List<T> lista = new List<T>();
Type t = typeof(T);
ConstructorInfo a = t.GetConstructor(new Type[0]); //Obtener el contructor por defecto
foreach (DataRow row in data.Rows)
{
int i = 0;
T valor = (T)Convert.ChangeType(a.Invoke(new object[0]), typeof(T)); //Debe regresar la instancia de clase
foreach (DataColumn column in data.Columns)
{
//Invocar la propiedad y establecer el valor que le corresponde
try
{
t.InvokeMember(
column.ColumnName,
BindingFlags.SetProperty |
BindingFlags.SetField |
BindingFlags.IgnoreCase |
BindingFlags.Public |
BindingFlags.Instance,
null,
valor,
new object[] { row[i] });
}
catch (Exception)
{
if (t.GetProperties().FirstOrDefault(x => x.Name.ToUpper() == column.ColumnName.ToUpper()) is PropertyInfo pr)
{
pr.SetValue(valor, Convert.ChangeType(row[i], pr.PropertyType));
}
}
i++;
}
lista.Add(valor);
}
return lista;
}
public static void InsertRow(this DataTable tabla, int index, DataRow fila)
{
DataRow dr = tabla.NewRow(); //Create New Row
object[] array = new object[fila.ItemArray.Length];
fila.ItemArray.CopyTo(array, 0);
dr.ItemArray = array;
tabla.Rows.InsertAt(dr, index); // InsertAt specified position
}
#endif
public static void Remove<T>(this ICollection<T> source, Func<T, bool> p)
{
for (int i = 0; i < source.Count; i++)
{
T item = source.ElementAt(i);
if (p.Invoke(item))
{
source.Remove(item: item);
}
}
}
/// <summary>
/// Randomizes position of items in a lists and returns IEnumerable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="rng"></param>
/// <returns></returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
for (int i = elements.Length - 1; i >= 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
// ... except we don't really need to swap it fully, as we can
// return it immediately, and afterwards it's irrelevant.
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
public static Dictionary<Key, Value> Merge<Key, Value>(this Dictionary<Key, Value> left, Dictionary<Key, Value> right)
{
if (left == null)
{
throw new ArgumentNullException("Can't merge into a null dictionary");
}
else if (right == null)
{
return left;
}
foreach (var kvp in right)
{
if (!left.ContainsKey(kvp.Key))
{
left.Add(kvp.Key, kvp.Value);
}
}
return left;
}
public static TSource GetLast<TSource>(this IEnumerable<TSource> source)
{
TSource last = source.TryGetLast(out bool found);
if (!found)
{
throw new Exception("No elements!");
}
return last;
}
public static TSource GetLast<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
TSource last = source.TryGetLast(predicate, out bool found);
if (!found)
{
throw new Exception("No match");
}
return last;
}
public static TSource LastDefault<TSource>(this IEnumerable<TSource> source) =>
source.TryGetLast(out bool _);
public static TSource LastDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) =>
source.TryGetLast(predicate, out bool _);
private static TSource TryGetLast<TSource>(this IEnumerable<TSource> source, out bool found)
{
if (source == null)
{
throw new NullReferenceException();
}
if (source is IList<TSource> list)
{
int count = list.Count;
if (count > 0)
{
found = true;
return list[count - 1];
}
}
else
{
using (IEnumerator<TSource> e = source.GetEnumerator())
{
if (e.MoveNext())
{
TSource result;
do
{
result = e.Current;
}
while (e.MoveNext());
found = true;
return result;
}
}
}
found = false;
return default(TSource);
}
private static TSource TryGetLast<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, out bool found)
{
if (source == null)
{
throw new NullReferenceException();
}
if (predicate == null)
{
throw new NullReferenceException();
}
if (source is IList<TSource> list)
{
for (int i = list.Count - 1; i >= 0; --i)
{
TSource result = list[i];
if (predicate(result))
{
found = true;
return result;
}
}
}
else
{
using (IEnumerator<TSource> e = source.GetEnumerator())
{
while (e.MoveNext())
{
TSource result = e.Current;
if (predicate(result))
{
while (e.MoveNext())
{
TSource element = e.Current;
if (predicate(element))
{
result = element;
}
}
found = true;
return result;
}
}
}
}
found = false;
return default(TSource);
}
}
} |
using GameStore.Domain.Identity;
using GameStore.Domain.Infrastructure;
using GameStore.WebUI.Areas.Admin.Models;
using GameStore.WebUI.Areas.Admin.Models.DTO;
using GameStore.WebUI.Helper;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace GameStore.WebUI.Apis
{
[Authorize(Roles = "Admin")]
public class UserController : BaseApiController
{
// GET api/<controller>
public List<UserDTO> Get()
{
if (HttpContext.Current.Cache["UserList"] != null)
{
return (List<UserDTO>)HttpContext.Current.Cache["UserList"];
}
else
{
List<UserDTO> users = UserManager.Users.Select(u => new UserDTO { Id = u.Id, Email = u.Email, UserName = u.UserName, Membership = u.Membership }).ToList();
HttpContext.Current.Cache["UserList"] = users;
return users;
}
}
// GET api/<controller>/5
public UserDTO Get(string id)
{
if (HttpContext.Current.Cache["User" + id] != null)
{
return (UserDTO)HttpContext.Current.Cache["User" + id];
}
else
{
AppUser u = UserManager.FindById(id);
UserDTO user = new UserDTO { Id = u.Id, Email = u.Email, UserName = u.UserName, Membership = u.Membership };
HttpContext.Current.Cache["User" + id] = user;
return user;
}
}
// GET: api/Category/GetCount/
[Route("api/User/GetCount")]
public int GetCount()
{
if (HttpContext.Current.Cache["UserList"] != null)
{
List<UserDTO> list = (List<UserDTO>)HttpContext.Current.Cache["UserList"];
return list.Count();
}
else
{
List<UserDTO> users = UserManager.Users.Select(u => new UserDTO { Id = u.Id, Email = u.Email, UserName = u.UserName, Membership = u.Membership }).ToList();
HttpContext.Current.Cache["UserList"] = users;
return users.Count();
}
}
[Route("api/User/Create")]
public async Task<HttpResponseMessage> Create([FromBody]UserViewModel value)
{
if (ModelState.IsValid)
{
var user = new AppUser { Email = value.Email, UserName = value.UserName, Membership = value.Membership };
var result = await UserManager.CreateAsync(user, ConfigurationHelper.GetDefaultPassword());
if (result.Succeeded)
{
HttpContext.Current.Cache.Remove("UserList");
return Request.CreateResponse(HttpStatusCode.OK, "Okay");
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, GetErrorMessage(result));
}
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, "ModelState.IsValid=false");
}
}
public HttpResponseMessage Post([FromBody]UserViewModel value)
{
if (ModelState.IsValid)
{
AppUser user = UserManager.FindById(value.Id);
if (user == null)
{
return Request.CreateResponse(HttpStatusCode.OK, "User [" + value.Id + "] does not exist!");
}
user.UserName = value.UserName;
user.Membership = value.Membership;
user.Roles.Clear();
var role = RoleManager.Roles.Where(r => r.Name == value.Membership).First();
user.Roles.Add(new IdentityUserRole { RoleId = role.Id, UserId = user.Id });
IdentityResult result = UserManager.Update(user);
if (result.Succeeded)
{
HttpContext.Current.Cache.Remove("UserList");
HttpContext.Current.Cache.Remove("User" + value.Id);
return Request.CreateResponse(HttpStatusCode.OK, "Okay");
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, GetErrorMessage(result));
}
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, "ModelState.IsValid=false");
}
}
// DELETE api/<controller>/5
public HttpResponseMessage Delete(string id)
{
AppUser user = UserManager.FindById(id);
if (user == null)
{
return Request.CreateResponse(HttpStatusCode.OK, "User ["+id+"] not found.");
}
else
{
IdentityResult result = UserManager.Delete(user);
if (result.Succeeded)
{
HttpContext.Current.Cache.Remove("UserList");
HttpContext.Current.Cache.Remove("User" + user.Id);
return Request.CreateResponse(HttpStatusCode.OK, "Okay");
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, GetErrorMessage(result));
}
}
}
}
}
|
using AgendaAPI.Dominio.Entidades;
using AgendaAPI.Repositorio.Maps;
using Microsoft.EntityFrameworkCore;
using System;
namespace AgendaAPI.Repositorio
{
public class AgendaContext : DbContext
{
public AgendaContext(DbContextOptions<AgendaContext> options) : base(options)
{
}
public DbSet<Contato> Contatos { get; set; }
public DbSet<Telefone> Telefones { get; set; }
public DbSet<Usuario> Usuarios { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new ContatoMap());
modelBuilder.ApplyConfiguration(new TelefoneMap());
modelBuilder.ApplyConfiguration(new UsuarioMap());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicProgramDay5
{
public class EvenAndOdd
{
public void EvenOddFunction()
{
int n;
Console.WriteLine("Enter the number");
n = Convert.ToInt32(Console.ReadLine());
if (n % 2 == 0)
Console.WriteLine("Number is Even number");
else
Console.WriteLine("Number is odd number");
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
namespace Assets.Scripts
{
public class ScoreUIManager : MonoBehaviour
{
public Text RoundText;
public Text ScoreText;
public Text GameOverText;
public GameObject GameOverUI;
public Canvas CrossHairCanvas;
public Canvas InventoryCanvas;
public GameObject mainMenuButton;
void Awake() {
mainMenuButton = GameObject.Find("MMButton");
}
void Update()
{
mainMenuButton.SetActive(false);
RoundText.text = RoundManager.Round == 0 ? $"The game will start in {RoundManager.SecondsToStart} seconds..." : $"ROUND {RoundManager.Round}";
ScoreText.text = $"score {Player.Score}";
if(Player.IsDead)
{
GameObject.Find("Main Camera").GetComponent<MouseLook>().enabled = false;
GameObject.Find("Player").GetComponent<PlayerController>().enabled = false;
GameObject.Find("Spot Light").GetComponent<MouseLook>().enabled = false;
foreach (Transform child in GameObject.Find("Enemy").transform) {
if (child.gameObject.tag == "Enemy") {
child.transform.position = new Vector3(0,0,0);
}
}
CrossHairCanvas.enabled = false;
InventoryCanvas.enabled = false;
RoundText.enabled = false;
GameOverUI.SetActive(true);
GameOverText.text = $"Game Over!\nYou survived {RoundManager.Round} rounds!\nFinal Score: {Player.Score}";
mainMenuButton.SetActive(true);
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
PlayerPrefs.SetFloat("score", Player.Score);
}
}
public void backToMainMenu() {
SceneManager.LoadScene("Main Menu");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Quinelita.Data;
namespace Quinelita.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LigasController : ControllerBase
{
private readonly QuinelitaContext _context;
public LigasController(QuinelitaContext context)
{
_context = context;
}
// GET api/customers
[HttpGet]
public IActionResult Get()
{
return Ok(_context.Ligas);
}
}
} |
// Created by Kay.
// Copyright 2013 SCIO System-Consulting GmbH & Co. KG. All rights reserved.
//
using UnityEngine;
using System.Collections;
/// <summary>
/// Callback listener for IPodHandlerPlugin. Attach this component to a GameObject named Main in your scene.
/// </summary>
public class TestIPodListener : MonoBehaviour
{
void Awake () {
IPodHandler.RegisterUnityIPodCallbackListener ();
}
public void IPodNotification (string message) {
Debug.Log ("Notification !!! " + message);
}
}
|
/*
* Copyright (c) 2017 Samsung Electronics Co., 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.
*/
using Sensor.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Sensor
{
/// <summary>
/// Interface to manage sensors.
/// </summary>
public interface ISensorManager
{
/// <summary>
/// Gets the supported sensor types on the current device.
/// </summary>
/// <returns>Supported sensor types</returns>
List<string> GetSensorTypeList();
/// <summary>
/// Gets the specific sensor information.
/// </summary>
/// <param name="type">Sensor type</param>
/// <returns>Sensor information</returns>
SensorInfo GetSensorInfo(string type);
/// <summary>
/// Starts the sensor of the specific type.
/// </summary>
/// <param name="type">Sensor type</param>
/// <param name="listener">Event handler to listen sensor events</param>
void StartSensor(string type, EventHandler<SensorEventArgs> listener);
/// <summary>
/// Stops the sensor of the specific type.
/// </summary>
/// <param name="type">Sensor type</param>
/// <param name="listener">Event handler registered</param>
void StopSensor(string type, EventHandler<SensorEventArgs> listener);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using UnityEditor;
using UnityEngine;
public class TableTools
{
private const string xmlRoot = "/StreamingAssets/ConfigXML/";
private const string scriptRoot = "/Scripts/ConfigTable/";
[MenuItem("Config/GenerateConfig[生成表模板]")]
public static void GenerateTableEntity()
{
DirectoryInfo xmlFolder = new DirectoryInfo(Application.dataPath + xmlRoot);
List<string> tableClassNames = new List<string>();
ClearTableClass();
ClearTableTypes();
foreach (FileInfo curFile in xmlFolder.GetFiles())
{
if (curFile.Name.Substring(curFile.Name.Length - 4, 4) == ".xml")
{
Dictionary<string, string> values = LoadXmlTypes(curFile.Name, "fieldType");
if (values == null)
return;
bool hasAllType = CheckTypes(curFile.Name, values);
if (hasAllType == false)
return;
string className = curFile.Name.Substring(0, curFile.Name.Length - 4);
//将类名 . 替换成_
className = className.Replace('.', '_');
tableClassNames.Add(className);
Dbg.INFO_MSG("Create TableClass :" + className + ".cs");
CreateTableClass(className, values);
}
}
CreateTableTypes(tableClassNames.ToArray());
AssetDatabase.Refresh();
Dbg.INFO_MSG("GenerateTableEntity Successfull !!!");
}
private static void ClearTableTypes()
{
CreateTableTypes(null);
}
private static void ClearTableClass()
{
if (Directory.Exists(Application.dataPath + scriptRoot + "datas/"))
{
DelectDir(Application.dataPath + scriptRoot + "datas/");
}
}
public static void DelectDir(string srcPath)
{
try
{
DirectoryInfo dir = new DirectoryInfo(srcPath);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
if (i is DirectoryInfo) //判断是否文件夹
{
DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true); //删除子目录和文件
}
else
{
File.Delete(i.FullName); //删除指定文件
}
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
public static Dictionary<string, string> LoadXmlTypes(string xmlname, string itemName = null)
{
XElement xml = XElement.Load((Application.dataPath + xmlRoot + xmlname));
if (! xml.HasElements)
{
Dbg.ERROR_MSG("xml 丢失元素");
return null;
}
Dictionary<string, string> xmltypes = new Dictionary<string, string>();
var descendants = xml.Descendants();
foreach (XElement item in descendants)
{
if (itemName == null || item.Name == itemName)
{
var attrs = item.Attributes();
foreach (XAttribute attr in attrs)
{
xmltypes.Add(attr.Name.ToString(), attr.Value);
}
}
}
return xmltypes;
}
public static void CreateTableClass(string className, Dictionary<string, string> values)
{
FileStream fs = new FileStream(Application.dataPath + scriptRoot + "datas/" + className + ".cs", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.WriteLine("//The Data is Automatic generation, Don't Modify It !!!");
sw.WriteLine("public struct " + className);
sw.WriteLine("{");
if (values != null)
{
foreach (string fileName in values.Keys)
{
sw.WriteLine(" public " + values[fileName] + " " + fileName + ";");
sw.WriteLine("");
}
}
sw.WriteLine("}");
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
public static void CreateTableTypes(string[] tableTypes)
{
FileStream fs = new FileStream(Application.dataPath + scriptRoot + "TableTypes.cs", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入 CS MOD
sw.WriteLine("//The Class is Automatic generation, Don't Modify It !!!");
sw.WriteLine("using System;");
sw.WriteLine("using System.Collections.Generic;");
sw.WriteLine("");
sw.WriteLine("");
sw.WriteLine("public static class TableTypes");
sw.WriteLine("{");
sw.WriteLine(" public static List<Type> GetTableTypes()");
sw.WriteLine(" {");
sw.WriteLine(" List<Type> tabletypes = new List<Type>();");
if (tableTypes != null)
{
foreach (string curTableType in tableTypes)
{
sw.WriteLine(" tabletypes.Add(typeof(" + curTableType + "));");
}
}
sw.WriteLine(" return tabletypes;");
sw.WriteLine(" }");
sw.WriteLine("}");
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
public static bool CheckTypes(string xmlName, Dictionary<string, string> values)
{
foreach (string type in values.Values)
{
if (Type.GetType(type) == null)
{
Dbg.ERROR_MSG("类型检测错误! 未能识别此类型:" + type + " >>" + xmlName);
return false;
}
}
return true;
}
}
|
namespace WebMarkupMin.Web.Filters
{
using System.IO;
using System.Text;
using Core.Minifiers;
/// <summary>
/// HTML minification response filter
/// </summary>
public sealed class HtmlMinificationFilterStream : MarkupMinificationFilterStreamBase<HtmlMinifier>
{
/// <summary>
/// Constructs instance of HTML minification response filter
/// </summary>
/// <param name="stream">Content stream</param>
/// <param name="minifier">HTML minifier</param>
public HtmlMinificationFilterStream(Stream stream, HtmlMinifier minifier)
: base(stream, minifier)
{ }
/// <summary>
/// Constructs instance of HTML minification response filter
/// </summary>
/// <param name="stream">Content stream</param>
/// <param name="minifier">HTML minifier</param>
/// <param name="currentUrl">Current URL</param>
/// <param name="encoding">Text encoding</param>
public HtmlMinificationFilterStream(Stream stream, HtmlMinifier minifier, string currentUrl, Encoding encoding)
: base(stream, minifier, currentUrl, encoding)
{ }
}
} |
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OpenGov.Models;
using OpenGovAlerts.Models;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace OpenGovAlerts.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
[Produces("application/json")]
public class MemberController: ControllerBase
{
private AlertsDbContext db;
public MemberController(AlertsDbContext db)
{
this.db = db;
}
public async Task<ActionResult> GetIndex()
{
MemberIndexModel result = new MemberIndexModel();
result.Observers = await db.Observers.Include(o => o.CreatedSearches).ToListAsync();
result.RecentMatches = await db.Matches
.Include(m => m.Search).ThenInclude(s => s.CreatedBy)
.Include(m => m.Meeting).ThenInclude(m => m.Source)
.Where(m => m.TimeFound > DateTime.UtcNow.Subtract(TimeSpan.FromDays(7)) && result.Observers.Contains(m.Search.CreatedBy))
.Take(10)
.ToListAsync();
return Ok(result);
}
public async Task<ActionResult> GetObserver(int id)
{
var result = new ViewObserverModel();
result.Observer = await db.Observers.Include(o => o.CreatedSearches).FirstOrDefaultAsync(o => o.Id == id);
return Ok(result);
}
public async Task<ActionResult> AddObserver(ViewObserverModel model)
{
var newObserver = db.Observers.Add(model.Observer);
await db.SaveChangesAsync();
return Ok(newObserver.Entity);
}
public async Task<ActionResult> GetSearch(int id)
{
var result = new ViewSearchModel();
result.Search = await db.Searches
.Include(s => s.Sources).ThenInclude(ss => ss.Source)
.FirstOrDefaultAsync(o => o.Id == id);
result.RecentMatches = await db.Matches
.Include(m => m.Search)
.Include(m => m.Meeting).ThenInclude(m => m.Source)
.Where(m => m.TimeFound > DateTime.UtcNow.Subtract(TimeSpan.FromDays(7)) && m.Search.Id == id)
.OrderByDescending(m => m.Meeting.Date)
.Take(10)
.ToListAsync();
result.Sources = (await db.Sources.ToListAsync()).Select(s => new ViewSearchSource { Source = s, Selected = result.Search.Sources.Any(ss => ss.Source.Id == s.Id) }).ToList();
result.Search.Sources = null;
return Ok(result);
}
public async Task<ActionResult> GetMatches(int searchId)
{
var result = new ViewMatchesModel();
result.Matches = await db.Matches
.Include(m => m.Search)
.Include(m => m.Meeting).ThenInclude(m => m.Source)
.Where(m => m.Search.Id == searchId)
.ToListAsync();
return Ok(result);
}
[HttpPost]
public async Task<ActionResult> UpdateSearch(int id, [FromBody] ViewSearchModel updated)
{
var search = await db.Searches.Include(s => s.Sources).FirstOrDefaultAsync(s => s.Id == id);
search.Name = updated.Search.Name;
search.Phrase = updated.Search.Phrase;
foreach (ViewSearchSource searchSource in updated.Sources)
{
SearchSource sourceAlreadySelected = search.Sources.FirstOrDefault(ss => ss.SourceId == searchSource.Source.Id);
if (searchSource.Selected)
{
if (sourceAlreadySelected == null)
{
await db.SearchSources.AddAsync(new SearchSource { SearchId = search.Id, SourceId = searchSource.Source.Id });
}
}
else
{
if (sourceAlreadySelected != null)
{
db.SearchSources.Remove(sourceAlreadySelected);
}
}
}
await db.SaveChangesAsync();
return await GetSearch(id);
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Sunny.Lib;
namespace Sunny.Robot.Helper
{
public class Search
{
public static string SearchSpecialAnwer(string keyWords, SearchMatchType searchMatchType)
{
string specialKeyWords = string.Empty;
if (searchMatchType == SearchMatchType.Word)
{
specialKeyWords = string.Format(Const.SearchWordPattern, Regex.Escape(keyWords));
}
else if (searchMatchType == SearchMatchType.Line)
{
specialKeyWords = string.Format(Const.SearchLinePattern, Regex.Escape(keyWords));
}
else
{
specialKeyWords = string.Format(Const.SearchSectionPattern, Regex.Escape(keyWords));
}
return SearchAnswer(specialKeyWords, GetAnswerLibraryFileFullNames());
}
public static List<string> GetAnswerLibraryFileFullNames()
{
List<string> fileFullNameList = new List<string>();
foreach (string filePath in Config.DefaultConfig.AnswerLibraryFilePaths)
{
if (!string.IsNullOrEmpty(filePath))
{
// Folder
if (System.IO.Directory.Exists(filePath))
{
System.IO.DirectoryInfo di = new DirectoryInfo(filePath);
FileInfo[] files = di.GetFiles("*.txt");
if (files != null)
{
foreach (FileInfo file in files)
{
fileFullNameList.Add(file.FullName);
}
}
}
// File
else if (File.Exists(filePath))
{
fileFullNameList.Add(filePath);
}
else
{
Logger.LogWarning(string.Format("'{0}' not exist", filePath));
continue;
}
}
}
return fileFullNameList;
}
public static string SearchAnswer(string keyWords, List<string> fileFullNameList)
{
StringBuilder sb = new StringBuilder();
string fileConentString = string.Empty;
string matchString = string.Empty;
foreach (string fileFullPath in fileFullNameList)
{
fileConentString = ReadFileContext(fileFullPath);
if (!string.IsNullOrEmpty(fileConentString))
{
matchString = IntelnelSearchAnswer(keyWords, fileConentString);
if (!string.IsNullOrEmpty(matchString))
{
sb.Append(matchString);
}
}
}
return sb.ToString();
}
private static string IntelnelSearchAnswer(string keyWords, string searchFromString)
{
StringBuilder sb = new StringBuilder();
string[] searchResult = RegexHelper.GetMatches_All_JustWantedOne(keyWords, searchFromString);
int len = searchResult.Count();
for (int i = 0; i < len - 1; i++)
{
string matchItem = searchResult[i];
if (!string.IsNullOrEmpty(matchItem))
{
sb.AppendLine(matchItem.Trim()); // Here call Trim() is to remove break line and space
}
}
if (len > 0)
{
string matchItem = searchResult[len - 1];
if (!string.IsNullOrEmpty(matchItem))
{
sb.Append(matchItem.Trim()); // Here call Trim() is to remove break line and space
}
}
return sb.ToString();
}
private static string ReadFileContext(string fileFullPath)
{
string fileContent = File.ReadAllText(fileFullPath);
return fileContent;
}
private static string RemovePrefixOrSuffix(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
else
{
return input.Replace(Config.DefaultConfig.KeyPrefix, "").Replace(Config.DefaultConfig.KeySuffix, "");
}
}
}
}
|
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== //
//
// Notes:
//
// ============================================================================ //
using System;
using System.Runtime.CompilerServices;
using UnityEngine;
[assembly: InternalsVisibleTo("EnhancedEditor.Editor")]
namespace EnhancedEditor {
/// <summary>
/// <see cref="ScriptableObject"/> database containing all <see cref="TagData"/> in the project.
/// </summary>
[NonEditable("This data is sensitive and should not be manipulated manually.")]
public class FlagDatabase : ScriptableObject {
#region Global Members
private static FlagDatabase database = null;
#if UNITY_EDITOR
/// <summary>
/// Editor internal getter for the <see cref="FlagDatabase"/> instance.
/// <para/>
/// As it needs to be set manually at runtime, it uses an internal getter when in editor mode
/// to be safely able to load it from the database, even if the user deletes it.
/// </summary>
internal static Func<FlagDatabase> EditorFlagDatabaseGetter = null;
#endif
/// <summary>
/// You have to set this reference at runtime to be properly able to use it.
/// <br/>
/// There are a variety of ways to assign its value:
/// <list type="bullet">
/// <item>by <see cref="ScriptableObject"/> reference</item>
/// <item>using <see cref="Resources.Load(string)"/></item>
/// <item><see cref="AssetBundle"/></item>
/// <item>... or any other way you'd like.</item>
/// </list><para/>
/// </summary>
public static FlagDatabase Database {
get {
#if UNITY_EDITOR
if (!Application.isPlaying && (EditorFlagDatabaseGetter != null)) {
return EditorFlagDatabaseGetter();
}
if (database == null) {
Debug.LogError($"Unassigned {typeof(FlagDatabase).Name} reference!\nYou must manually set this database " +
$"reference on game start to be able to properly use it.");
database = CreateInstance<FlagDatabase>();
}
#endif
return database;
}
set {
database = value;
}
}
// -------------------------------------------
// Database Content
// -------------------------------------------
[SerializeField] internal FlagHolder[] holders = new FlagHolder[0];
/// <summary>
/// All <see cref="FlagHolder"/> defined in the project.
/// </summary>
public FlagHolder[] Holders {
get { return holders; }
}
/// <summary>
/// Total amount of <see cref="FlagHolder"/> in the project.
/// </summary>
public int Count {
get { return holders.Length; }
}
#endregion
#region Behaviour
/// <summary>
/// Resets all in-game flags to a FALSE value.
/// </summary>
public void ResetFlags() {
foreach (FlagHolder _holder in holders) {
_holder.ResetFlags();
}
}
#endregion
#region Utility
/// <param name="_name"><inheritdoc cref="SetFlag(string, string, bool" path="/param[@name='_flagName']"/></param>
/// <inheritdoc cref="SetFlag(string, string, bool)"/>
public bool SetFlag(string _name, bool _value) {
if (FindFlag(_name, out Flag _flag)) {
_flag.Value = _value;
return true;
}
return false;
}
/// <summary>
/// Finds the first matching <see cref="Flag"/> in the database and set its value.
/// </summary>
/// <param name="_flagName">Name of the flag to find.</param>
/// <param name="_holderName">Name of the <see cref="FlagHolder"/> containing the flag.</param>
/// <param name="_value">Value to assign to the flag.</param>
/// <returns>True if a matching <see cref="Flag"/> could be found, false otherwise.</returns>
public bool SetFlag(string _flagName, string _holderName, bool _value) {
if (FindFlag(_flagName, _holderName, out Flag _flag)) {
_flag.Value = _value;
return true;
}
return false;
}
/// <param name="_name"><inheritdoc cref="FindFlag(string, string, out Flag, out FlagHolder" path="/param[@name='_flagName']"/></param>
/// <inheritdoc cref="FindFlag(string, string, out Flag)"/>
public bool FindFlag(string _name, out Flag _flag) {
foreach (FlagHolder _holder in holders) {
if (_holder.FindFlag(_name, out _flag)) {
return true;
}
}
_flag = null;
return false;
}
/// <summary>
/// Finds the first matching <see cref="Flag"/> in the database.
/// </summary>
/// <param name="_flagName">Name of the flag to find.</param>
/// <param name="_holderName">Name of the <see cref="FlagHolder"/> containing the flag.</param>
/// <param name="_flag">Found matching flag (null if none).</param>
/// <param name="_flag"><see cref="FlagHolder"/> of the matching flag (null if none).</param>
/// <returns>True if a matching <see cref="Flag"/> could be found, false otherwise.</returns>
public bool FindFlag(string _flagName, string _holderName, out Flag _flag) {
if (FindHolder(_holderName, out FlagHolder _holder) && _holder.FindFlag(_flagName, out _flag)) {
return true;
}
_flag = null;
return false;
}
/// <summary>
/// Finds the first <see cref="FlagHolder"/> in the database matching a given name.
/// </summary>
/// <param name="_name">Name of the <see cref="FlagHolder"/> to find.</param>
/// <param name="_holder"><see cref="FlagHolder"/> with the given name (null if none).</param>
/// <returns>True if a <see cref="FlagHolder"/> with the given name could be successfully found, false otherwise.</returns>
public bool FindHolder(string _name, out FlagHolder _holder) {
foreach (FlagHolder _temp in holders) {
if (_temp.name == _name) {
_holder = _temp;
return true;
}
}
_holder = null;
return false;
}
/// <summary>
/// Get the <see cref="FlagHolder"/> at the given index.
/// <br/> Use <see cref="Count"/> to get the total amount of <see cref="FlagHolder"/> in the database.
/// </summary>
public FlagHolder GetHolder(int _index) {
return holders[_index];
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemPage : Page_Base {
void Start () {
}
void Update () {
}
protected override void OnClose(){
print ("ItemPage關閉");
}
protected override void OnOpen(){
print ("ItemPage開啟");
}
}
|
using OrderService.Models;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
namespace OrderService.Tests
{
public class ControllerTests
{
[Fact]
public async Task CreateOrder_Returns_Created_Order()
{
using (var client = new TestClientProvoider().Client)
{
client.DefaultRequestHeaders.Add("Api_Key", "MySceretOrderApiKey");
Guid orderid = Guid.Empty;
var payload = JsonSerializer.Serialize(
new Order()
{
OrderId = Guid.Parse("2ae4bb3a-9664-4235-b721-af45dfa7d81a"),
OrderDate = DateTime.Now,
UserId=Guid.Parse("bbd9482e-1193-4545-88b7-81aa97ebfa77"),
ProductId=Guid.Parse("08b446ae-03bb-4e53-96de-c34f31a79f09")
}
);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"/api/order/createorder", content);
using (var responseStream = await response.Content.ReadAsStreamAsync())
{
var order = await JsonSerializer.DeserializeAsync<Order>(responseStream,
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
orderid = order.OrderId;
Assert.NotNull(order);
Assert.NotEqual<Guid>(Guid.Empty, orderid);
}
var deleteResponse = await client.DeleteAsync($"/api/order/deleteorder?id={orderid}");
using (var deleteStream = await deleteResponse.Content.ReadAsStreamAsync())
{
var deletedid = await JsonSerializer.DeserializeAsync<Guid>(deleteStream,
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
}
}
[Fact]
public async Task CreateOrder_Returns_BadRequest()
{
Guid orderid = Guid.Empty;
using (var client = new TestClientProvoider().Client)
{
client.DefaultRequestHeaders.Add("Api_Key", "MySceretOrderApiKey");
var payload = JsonSerializer.Serialize(
new Order()
{
});
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"/api/order/Createorder", content);
using (var responseStream = await response.Content.ReadAsStreamAsync())
{
var order = await JsonSerializer.DeserializeAsync<Order>(responseStream,
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
orderid = order.OrderId;
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
var deleteResponse = await client.DeleteAsync($"/api/order/deleteorder?id={orderid}");
using (var deleteStream = await deleteResponse.Content.ReadAsStreamAsync())
{
var deletedid = await JsonSerializer.DeserializeAsync<Guid>(deleteStream,
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
}
}
[Fact]
public async Task DeleteOrder_Returns_Deleted_Id()
{
using (var client = new TestClientProvoider().Client)
{
client.DefaultRequestHeaders.Add("Api_Key", "MySceretOrderApiKey");
Guid orderid = Guid.Empty;
var payload = JsonSerializer.Serialize(
new Order()
{
OrderId = Guid.Parse("2ae4bb3a-9664-4235-b721-af45dfa7d81a"),
OrderDate = DateTime.Now,
UserId = Guid.Parse("bbd9482e-1193-4545-88b7-81aa97ebfa77"),
ProductId = Guid.Parse("08b446ae-03bb-4e53-96de-c34f31a79f09")
}
);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"/api/order/createorder", content);
using (var responseStream = await response.Content.ReadAsStreamAsync())
{
var order = await JsonSerializer.DeserializeAsync<Order>(responseStream,
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
orderid = order.OrderId;
}
var deleteResponse = await client.DeleteAsync($"/api/order/deleteorder?id={orderid}");
using (var responseStream = await deleteResponse.Content.ReadAsStreamAsync())
{
var deletedId = await JsonSerializer.DeserializeAsync<Guid>(responseStream,
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
Assert.Equal(orderid, deletedId);
}
}
}
[Fact]
public async Task DeleteOrder_Returns_Notfound()
{
using (var client = new TestClientProvoider().Client)
{
client.DefaultRequestHeaders.Add("Api_Key", "MySceretOrderApiKey");
var response = await client.DeleteAsync("/api/order/deleteorder?id=" + Guid.Empty);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
}
}
|
namespace VideoServiceBL.Services.Interfaces
{
public interface ICryptService
{
string EncodePassword(string password);
bool VerifyPassword(string password, string enhancedHashPassword);
}
} |
using System.ComponentModel.DataAnnotations;
namespace Leads.Models
{
public class SiteLookup
{
public int Customer_Site_ID { get; set; }
public int Customer_ID { get; set; }
public int branchid { get; set; }
public string siteno { get; set; }
public string sitename { get; set; }
public string siteaddress { get; set; }
public string sitecity { get; set; }
public string sitezip { get; set; }
public string customername { get; set; }
public string systems { get; set; }
}
} |
using System;
namespace zero_to_twenty
{
class Program
{
static void Main(string[] args)
{
int number = 0;
while (number <= 20) {
System.Console.WriteLine(number);
number += 2;
}
}
}
}
|
using Enrollment.Spa.Flow.ScreenSettings.Navigation;
using LogicBuilder.Attributes;
namespace Enrollment.Spa.Flow
{
public interface ICustomActions
{
[AlsoKnownAs("SetupNavigationMenu")]
void UpdateNavigationBar(NavigationBar navBar);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NapierBank.Models
{
/*
Significant incident report subclass.
This is a subclass which handles SIR only operations.
*/
class SIR : EmailModel
{
public string Incident { get; set; }
public string SortCode { get; set; }
// Constructor
public SIR()
{
Header = "";
Body = "";
Incident = "";
SortCode = "";
}
// Constructor
public SIR(string header, string body, string sender, string subject, string incident, string sortCode)
{
Header = header;
Body = body;
Sender = sender;
Subject = subject;
Incident = incident;
SortCode = sortCode;
}
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MvcApplication.Business.InversionOfControl;
using MvcApplication.Business.StructureMap;
using StructureMap;
namespace MvcApplication
{
public class Global : HttpApplication
{
#region Methods
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
protected void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new StructureMapDependencyResolver(new Container(new Registry())));
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional});
}
#endregion
}
} |
// Target - The task you want to start. Runs the Default task if not specified.
var target = Argument("Target", "Default");
// Configuration - The build configuration (Debug/Release) to use.
// 1. If command line parameter parameter passed, use that.
// 2. Otherwise if an Environment variable exists, use that.
var configuration =
HasArgument("Configuration")
? Argument<string>("Configuration")
: EnvironmentVariable("Configuration") ?? "Release";
// A directory path to an Artifacts directory.
var artifactsDirectory = MakeAbsolute(Directory("./artifacts"));
// Deletes the contents of the Artifacts folder if it should contain anything from a previous build.
Task("Clean")
.Does(() =>
{
CleanDirectory(artifactsDirectory);
});
// Find all csproj projects and build them using the build configuration specified as an argument.
Task("Build")
.IsDependentOn("Clean")
.Does(() =>
{
var projects = GetFiles("../**/*.csproj");
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration,
ArgumentCustomization = args => args.Append("--configfile ./NuGet.config")
};
foreach(var project in projects)
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
});
// Look under a 'Tests' folder and run dotnet test against all of those projects.
// Then drop the XML test results file in the Artifacts folder at the root.
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var projects = GetFiles("../test/**/*.csproj");
var settings = new DotNetCoreTestSettings
{
Configuration = configuration,
NoRestore = true,
NoBuild = true
};
foreach(var project in projects)
DotNetCoreTest(project.FullPath, settings);
});
// The default task to run if none is explicitly specified. In this case, we want
// to run everything starting from Clean, all the way up to Test.
Task("Default")
.IsDependentOn("Test");
// Executes the task specified in the target argument.
RunTarget(target); |
namespace MFW.LALLib
{
public enum DTMFKeyEnum
{
DTMF_UNKNOWN, /**< Specifics unknown key. */
DTMF_ZERO, /**< Character Zero. */
DTMF_ONE, /**< Character One. */
DTMF_TWO, /**< Character Two. */
DTMF_THREE, /**< Character Three. */
DTMF_FOUR, /**< Character Four. */
DTMF_FIVE, /**< Character Five. */
DTMF_SIX, /**< Character Six. */
DTMF_SEVEN, /**< Character Seven. */
DTMF_EIGHT, /**< Character Eight. */
DTMF_NINE, /**< Character Nine. */
DTMF_STAR, /**< Character Star. */
DTMF_POUND, /**< Character Pound. */
DTMF_A, /**< key A . */
DTMF_B, /**< key B . */
DTMF_C, /**< key C . */
DTMF_D, /**< key D . */
DTMF_MAX /**< Upper Bound. */
}
}
|
using UnityEngine;
public class BulletController : MonoBehaviour
{
#region Fields
[SerializeField] private AudioClip _hitSound;
[SerializeField] private int _damage = 1;
private GameObject _player;
#endregion
#region UnityMethods
private void Start()
{
_player = GameObject.FindGameObjectWithTag("Player");
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Enemy") || collision.gameObject.CompareTag("Player"))
{
var healthController = collision.gameObject.GetComponent<HealthController>();
healthController.Hurt(_damage);
Destroy(gameObject);
if (_hitSound != null && _player != null)
_player.GetComponent<AudioSource>().PlayOneShot(_hitSound);
}
}
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.AppServices.DataContracts.Cashbag
{
/// <summary>
/// 积分兑换记录
/// </summary>
public class ScoreConvertLogDto
{
/// <summary>
/// 兑换时间
/// </summary>
public DateTime CreateDate { get; set; }
/// <summary>
/// 兑换积分
/// </summary>
public decimal PointAmount { get; set; }
/// <summary>
/// 剩余积分
/// </summary>
public decimal LeaveAmount { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace Calcifer.Engine.Particles
{
public class ParticlePool
{
private readonly List<Particle> pool;
private readonly Queue<int> freeIds;
private readonly int initialSize;
public ParticlePool() : this(512)
{}
public ParticlePool(int size)
{
initialSize = size;
freeIds = new Queue<int>();
pool = new List<Particle>(size);
for (var i = 0; i < size; i++)
{
pool.Add(new Particle(this, i));
freeIds.Enqueue(i);
}
}
internal IList<Particle> Particles
{
get { return pool; }
}
public Particle GetNew()
{
if (freeIds.Count == 0)
{
// Extending pool
pool.Capacity += pool.Count/2 + 1;
var extendSize = pool.Capacity - pool.Count;
for (var n = 0; n < extendSize; n++)
{
var p = new Particle(this, pool.Count);
pool.Add(p);
freeIds.Enqueue(p.ID);
}
#if DEBUG
Console.WriteLine("Particle pool upsized to {0}", pool.Capacity);
#endif
}
var index = freeIds.Dequeue();
pool[index].Destroyed = false;
return pool[index];
}
internal void Destroy(Particle particle)
{
particle.Destroyed = true;
freeIds.Enqueue(particle.ID);
}
internal void Update(float time)
{
foreach (var p in pool) p.Update(time);
}
}
} |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Text;
namespace Ayende.NHibernateQueryAnalyzer.Utilities
{
/// <summary>
/// Summary description for TextUtil.
/// </summary>
public sealed class Text
{
private Text()
{
}
/// <summary>
/// Check is the string variable is null or empty
/// </summary>
/// <param name="str">The string to check</param>
/// <returns>true is the string has value</returns>
public static bool NotNullOrEmpty(string str)
{
if (str == null || str.Length == 0)
return false;
else
return true;
}
/// <summary>
/// Parses the bool, but allows for empty string an null.
/// </summary>
/// <param name="booleanString">String containing the boolean value</param>
/// <param name="defaultValue">Default value to use if booleanString is null or empty.</param>
public static bool ParseBool(string booleanString, bool defaultValue)
{
if (!NotNullOrEmpty(booleanString))
return defaultValue;
return bool.Parse(booleanString);
}
/// <summary>
/// Objects the state to string. With the pattern of:
/// Object '[Object-Name]'
/// Property-Name: Property-Value or Type
/// </summary>
/// <param name="obj">Obj.</param>
/// <returns></returns>
public static string ObjectStateToString(object obj)
{
StringBuilder sb = new StringBuilder();
sb.Append("Object '").Append(ReflectionUtil.GetName(obj)).Append("\'\r\n");
foreach (PropertyInfo property in obj.GetType().GetProperties())
{
sb.Append('\t').Append(property.Name).Append(": ");
if (property.CanRead)
{
if (ReflectionUtil.IsSimpleType(property.PropertyType))
sb.Append(property.GetValue(obj, null));
else
sb.Append('{').Append(property.PropertyType.Name).Append('}');
sb.Append("\r\n");
}
}
return sb.ToString();
}
/// <summary>
/// This method exist because there is no method that Join a
/// StringCollection.
/// </summary>
public static string Join(string seperator, IEnumerable lines)
{
StringBuilder sb = new StringBuilder();
foreach (string line in lines)
sb.Append(line).Append(seperator);
sb.Remove(sb.Length - seperator.Length, seperator.Length);
return sb.ToString();
}
public static string ExceptionString(string name)
{
return name;
}
public static string ResourceString(string name)
{
return name;
}
}
} |
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.0.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using NUnit.Framework;
using BungieNetPlatform.Client;
using BungieNetPlatform.BungieNetPlatform.Api;
using BungieNetPlatform.BungieNetPlatform.Model;
namespace BungieNetPlatform.Test
{
/// <summary>
/// Class for testing PreviewApi
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the API endpoint.
/// </remarks>
[TestFixture]
public class PreviewApiTests
{
private PreviewApi instance;
/// <summary>
/// Setup before each unit test
/// </summary>
[SetUp]
public void Init()
{
instance = new PreviewApi();
}
/// <summary>
/// Clean up after each unit test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of PreviewApi
/// </summary>
[Test]
public void InstanceTest()
{
// TODO uncomment below to test 'IsInstanceOfType' PreviewApi
//Assert.IsInstanceOfType(typeof(PreviewApi), instance, "instance is a PreviewApi");
}
/// <summary>
/// Test Destiny2ActivateTalentNode
/// </summary>
[Test]
public void Destiny2ActivateTalentNodeTest()
{
// TODO uncomment below to test the method and replace null with proper value
//var response = instance.Destiny2ActivateTalentNode();
//Assert.IsInstanceOf<InlineResponse20015> (response, "response is InlineResponse20015");
}
/// <summary>
/// Test Destiny2GetActivityHistory
/// </summary>
[Test]
public void Destiny2GetActivityHistoryTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? characterId = null;
//long? destinyMembershipId = null;
//int? membershipType = null;
//int? count = null;
//int? mode = null;
//int? page = null;
//var response = instance.Destiny2GetActivityHistory(characterId, destinyMembershipId, membershipType, count, mode, page);
//Assert.IsInstanceOf<InlineResponse20046> (response, "response is InlineResponse20046");
}
/// <summary>
/// Test Destiny2GetClanAggregateStats
/// </summary>
[Test]
public void Destiny2GetClanAggregateStatsTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? groupId = null;
//string modes = null;
//var response = instance.Destiny2GetClanAggregateStats(groupId, modes);
//Assert.IsInstanceOf<InlineResponse20042> (response, "response is InlineResponse20042");
}
/// <summary>
/// Test Destiny2GetClanLeaderboards
/// </summary>
[Test]
public void Destiny2GetClanLeaderboardsTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? groupId = null;
//int? maxtop = null;
//string modes = null;
//string statid = null;
//var response = instance.Destiny2GetClanLeaderboards(groupId, maxtop, modes, statid);
//Assert.IsInstanceOf<InlineResponse20041> (response, "response is InlineResponse20041");
}
/// <summary>
/// Test Destiny2GetDestinyAggregateActivityStats
/// </summary>
[Test]
public void Destiny2GetDestinyAggregateActivityStatsTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? characterId = null;
//long? destinyMembershipId = null;
//int? membershipType = null;
//var response = instance.Destiny2GetDestinyAggregateActivityStats(characterId, destinyMembershipId, membershipType);
//Assert.IsInstanceOf<InlineResponse20048> (response, "response is InlineResponse20048");
}
/// <summary>
/// Test Destiny2GetHistoricalStats
/// </summary>
[Test]
public void Destiny2GetHistoricalStatsTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? characterId = null;
//long? destinyMembershipId = null;
//int? membershipType = null;
//DateTime? dayend = null;
//DateTime? daystart = null;
//List<DestinyHistoricalStatsDefinitionsDestinyStatsGroupType> groups = null;
//List<DestinyHistoricalStatsDefinitionsDestinyActivityModeType> modes = null;
//int? periodType = null;
//var response = instance.Destiny2GetHistoricalStats(characterId, destinyMembershipId, membershipType, dayend, daystart, groups, modes, periodType);
//Assert.IsInstanceOf<InlineResponse20044> (response, "response is InlineResponse20044");
}
/// <summary>
/// Test Destiny2GetHistoricalStatsForAccount
/// </summary>
[Test]
public void Destiny2GetHistoricalStatsForAccountTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? destinyMembershipId = null;
//int? membershipType = null;
//List<DestinyHistoricalStatsDefinitionsDestinyStatsGroupType> groups = null;
//var response = instance.Destiny2GetHistoricalStatsForAccount(destinyMembershipId, membershipType, groups);
//Assert.IsInstanceOf<InlineResponse20045> (response, "response is InlineResponse20045");
}
/// <summary>
/// Test Destiny2GetLeaderboards
/// </summary>
[Test]
public void Destiny2GetLeaderboardsTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? destinyMembershipId = null;
//int? membershipType = null;
//int? maxtop = null;
//string modes = null;
//string statid = null;
//var response = instance.Destiny2GetLeaderboards(destinyMembershipId, membershipType, maxtop, modes, statid);
//Assert.IsInstanceOf<InlineResponse20041> (response, "response is InlineResponse20041");
}
/// <summary>
/// Test Destiny2GetLeaderboardsForCharacter
/// </summary>
[Test]
public void Destiny2GetLeaderboardsForCharacterTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? characterId = null;
//long? destinyMembershipId = null;
//int? membershipType = null;
//int? maxtop = null;
//string modes = null;
//string statid = null;
//var response = instance.Destiny2GetLeaderboardsForCharacter(characterId, destinyMembershipId, membershipType, maxtop, modes, statid);
//Assert.IsInstanceOf<InlineResponse20041> (response, "response is InlineResponse20041");
}
/// <summary>
/// Test Destiny2GetUniqueWeaponHistory
/// </summary>
[Test]
public void Destiny2GetUniqueWeaponHistoryTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? characterId = null;
//long? destinyMembershipId = null;
//int? membershipType = null;
//var response = instance.Destiny2GetUniqueWeaponHistory(characterId, destinyMembershipId, membershipType);
//Assert.IsInstanceOf<InlineResponse20047> (response, "response is InlineResponse20047");
}
/// <summary>
/// Test Destiny2GetVendor
/// </summary>
[Test]
public void Destiny2GetVendorTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? characterId = null;
//long? destinyMembershipId = null;
//int? membershipType = null;
//uint? vendorHash = null;
//List<DestinyDestinyComponentType> components = null;
//var response = instance.Destiny2GetVendor(characterId, destinyMembershipId, membershipType, vendorHash, components);
//Assert.IsInstanceOf<InlineResponse20037> (response, "response is InlineResponse20037");
}
/// <summary>
/// Test Destiny2GetVendors
/// </summary>
[Test]
public void Destiny2GetVendorsTest()
{
// TODO uncomment below to test the method and replace null with proper value
//long? characterId = null;
//long? destinyMembershipId = null;
//int? membershipType = null;
//List<DestinyDestinyComponentType> components = null;
//var response = instance.Destiny2GetVendors(characterId, destinyMembershipId, membershipType, components);
//Assert.IsInstanceOf<InlineResponse20036> (response, "response is InlineResponse20036");
}
/// <summary>
/// Test Destiny2InsertSocketPlug
/// </summary>
[Test]
public void Destiny2InsertSocketPlugTest()
{
// TODO uncomment below to test the method and replace null with proper value
//var response = instance.Destiny2InsertSocketPlug();
//Assert.IsInstanceOf<InlineResponse20015> (response, "response is InlineResponse20015");
}
/// <summary>
/// Test Destiny2SearchDestinyEntities
/// </summary>
[Test]
public void Destiny2SearchDestinyEntitiesTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string searchTerm = null;
//string type = null;
//int? page = null;
//var response = instance.Destiny2SearchDestinyEntities(searchTerm, type, page);
//Assert.IsInstanceOf<InlineResponse20043> (response, "response is InlineResponse20043");
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Diagnostics;
using MyPersonalBlog.Business.Interfaces;
namespace MyPersonalBlog.UI.Controllers
{
public class ErrorController : Controller
{
private readonly ICustomLogger _customLogger;
public ErrorController(ICustomLogger customLogger)
{
_customLogger = customLogger;
}
//Bulunamayan Sayfa
public IActionResult StatusCode(int? code)
{
if (code == 404)
{
ViewBag.Code = code;
ViewBag.Message = "Sayfa Bulunamadı";
}
return View();
}
//Bulunamayan Id vs Hatalar
public IActionResult ErrorPage()
{
var exceptionHandler = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
_customLogger.LogError($"Hatanın oluştuğu yer:{exceptionHandler.Path}\nHatanın mesajı:{exceptionHandler.Error.Message}\nStack Trace:{exceptionHandler.Error.StackTrace}");
ViewBag.Path = exceptionHandler.Path;
ViewBag.Message = exceptionHandler.Error.Message;
return View();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Src.Models
{
public static class SuperString
{
#region Snippet_PowerfulMethods
/// <summary>Takes a string and change its order like a zig zag</summary>
/// <params name="str">String to change</params>
/// <params name="rows">Number of rows used to zig zag</params>
/// <returns>A string with their elements in zig zag order</returns>
public static string ConvertToZigZag(string str, int rows)
{
if (rows == 1) return str;
var linesList = new List<StringBuilder>();
for (int i = 0; i < Math.Min(rows, str.Length); i++)
{
linesList.Add(new StringBuilder());
}
var currentRow = 0;
var goingDown = false;
var linesArray = linesList.ToArray();
foreach (var @char in str.ToCharArray())
{
linesArray[currentRow].Append(@char);
if (currentRow == 0 || currentRow == rows - 1)
{
goingDown = !goingDown;
}
currentRow += goingDown ? 1 : -1;
}
var retention = new StringBuilder();
foreach (var line in linesList) retention.Append(line);
return retention.ToString();
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Asm.Assembler.Parsing;
namespace Asm.Assembler
{
public partial class Assembler
{
/*
#define HLT 0b10000000000000000000000000000000 // Halt clock
#define MI 0b01000000000000000000000000000000 // Memory address register in
#define RI 0b00100000000000000000000000000000 // RAM data in
#define RO 0b00010000000000000000000000000000 // RAM data out
#define IO 0b00001000000000000000000000000000 // Instruction register out
#define II 0b00000100000000000000000000000000 // Instruction register in
#define AI 0b00000010000000000000000000000000 // A register in
#define AO 0b00000001000000000000000000000000 // A register out
#define EO 0b00000000100000000000000000000000 // ALU out
#define SU 0b00000000010000000000000000000000 // ALU subtract
#define BI 0b00000000001000000000000000000000 // B register in
#define OI 0b00000000000100000000000000000000 // Output register in
#define CE 0b00000000000010000000000000000000 // Program counter enable
#define CO 0b00000000000001000000000000000000 // Program counter out
#define J 0b00000000000000100000000000000000 // Jump (program counter in)
#define JC 0b00000000000000010000000000000000 // Jump if carry (program counter in)
#define IIO 0b00000000000000001000000000000000 // Intermediate out
#define III 0b00000000000000000100000000000000 // Intermediate in
#define ORS 0b00000000000000000010000000000000 // Output register select
#define OE 0b00000000000000000001000000000000 // Output enable
#define FETCH0 MI|CO
#define FETCH1 RO|II|CE
unsigned long data[] = {
FETCH0, FETCH1, 0, 0, 0, 0, 0, 0, // 0000 - NOP
FETCH0, FETCH1, IO|MI, RO|AI, 0, 0, 0, 0, // 0001 - LDA
FETCH0, FETCH1, IO|MI, RO|BI, EO|AI, 0, 0, 0, // 0010 - ADD
FETCH0, FETCH1, IO|MI, RO|BI, EO|AI|SU, 0, 0, 0, // 0011 - SUB
FETCH0, FETCH1, IO|MI, AO|RI, 0, 0, 0, 0, // 0100 - STA
FETCH0, FETCH1, IO|AI, 0, 0, 0, 0, 0, // 0101 - LDI
FETCH0, FETCH1, IO|J, 0, 0, 0, 0, 0, // 0110 - JMP
FETCH0, FETCH1, IO|JC, 0, 0, 0, 0, 0, // 0111 - JC
FETCH0, FETCH1, AO|MI, RO|BI, 0, 0, 0, 0, // 1000 - LDAB
FETCH0, FETCH1, EO|AI, 0, 0, 0, 0, 0, // 1001 - ADDA
FETCH0, FETCH1, FETCH0, RO|III|CE, IIO|AI, 0, 0, 0, // 1010 - LDII
FETCH0, FETCH1, FETCH0, RO|III|CE, IIO|ORS|OE,0, 0, 0, // 1011 - OUT COMMAND
FETCH0, FETCH1, FETCH0, RO|III|CE, IIO|OE, 0, 0, 0, // 1100 - OUT DATA
FETCH0, FETCH1, 0, 0, 0, 0, 0, 0, // 1101
FETCH0, FETCH1, AO|OI, 0, 0, 0, 0, 0, // 1110 - OUT
FETCH0, FETCH1, HLT, 0, 0, 0, 0, 0, // 1111 - HLT
};
*/
private abstract class OpCode
{
public abstract int Pass0(Parser parser);
public abstract void Pass1(Stream stream);
protected void ExpectRegName(Token regNameToken)
{
if (_regNames.Contains(regNameToken.Text))
{
return;
}
throw new Exception($"Bad register name {regNameToken.Text} on line {regNameToken.LineNumber}");
}
protected bool TokenIsRegName(Token regNameToken) => _regNames.Contains(regNameToken.Text);
}
// nop
private class Nop : OpCode
{
public override int Pass0(Parser parser)
{
return 1;
}
public override void Pass1(Stream stream)
{
stream.Emit8(0x00);
}
}
// ldsp absolute
// ldsp const symbol
private class Ldsp : OpCode
{
private int _absolute;
private Token _symbol;
public override int Pass0(Parser parser)
{
var token = parser.NextToken();
if (token.Type == TokenType.Number)
{
_absolute = token.ToNumber();
}
/*else if (token.Type == const symbol)
{
}*/
else
{
throw new Exception("TODO: should be number or symbol");
}
return 3;
}
public override void Pass1(Stream stream)
{
stream.Emit8(0x01);
if (_symbol != null)
{
// TODO:
}
else
{
stream.Emit16(_absolute);
}
}
}
private static Dictionary<string, Func<OpCode>> _opTableFactory = new Dictionary<string, Func<OpCode>>(StringComparer.OrdinalIgnoreCase)
{
{ nameof(Nop), () => new Nop() },
{ nameof(Ldsp), () => new Ldsp() }
};
private static HashSet<string> _regNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"a"
};
private readonly List<OpCode> _opCodes = new List<OpCode>();
}
}
|
using System.Collections.Generic;
using System.Linq;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace TestingUtils
{
public class RetryFactDiscoverer : IXunitTestCaseDiscoverer
{
private readonly IMessageSink _messageSink;
public RetryFactDiscoverer(IMessageSink messageSink)
{
_messageSink = messageSink;
}
public IEnumerable<IXunitTestCase> Discover(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod,
IAttributeInfo factAttribute)
{
IXunitTestCase testCase;
if (testMethod.Method.GetParameters().Any())
{
testCase = new ExecutionErrorTestCase(_messageSink, discoveryOptions.MethodDisplayOrDefault(),
discoveryOptions.MethodDisplayOptionsOrDefault(), testMethod,
"[Fact]//[RetryFact] methods are not allowed to have parameters. Did you mean to use [RetryTheory]?");
}
else if (testMethod.Method.IsGenericMethodDefinition)
{
testCase = new ExecutionErrorTestCase(_messageSink, discoveryOptions.MethodDisplayOrDefault(),
discoveryOptions.MethodDisplayOptionsOrDefault(), testMethod,
"[Fact]//[RetryFact] methods are not allowed to be generic.");
}
else
{
var maxRetries = factAttribute.GetNamedArgument<int>(nameof(RetryFactAttribute.MaxRetries));
var delayBetweenRetriesMs =
factAttribute.GetNamedArgument<int>(nameof(RetryFactAttribute.DelayBetweenRetriesMs));
testCase = new RetryTestCase(_messageSink, discoveryOptions.MethodDisplayOrDefault(),
discoveryOptions.MethodDisplayOptionsOrDefault(), testMethod, maxRetries, delayBetweenRetriesMs);
}
return new[] { testCase };
}
}
}
|
using UnityEngine;
using UnityEngine.Events;
[CreateAssetMenu(menuName = "Events/Camera Zoom Event Channel")]
public class CameraZoomEventChannelSO : EventChannelBaseSO
{
public UnityAction<GameObject, bool, float> OnEventRaised;
public void RaiseEvent(GameObject sender, bool state, float value)
{
OnEventRaised.Invoke(sender, state, value);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccessLayer.Interfaces
{
public interface IRepository<T>
{
int Them(T t);
int Xoa(T t);
int CapNhat(T t);
Object Xem(T t);
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.UI.WebControls
{
/// -----------------------------------------------------------------------------
/// Namespace: DotNetNuke.UI.WebControls
/// Project: DotNetNuke
/// Enum: ImageCommandColumnEditMode
/// -----------------------------------------------------------------------------
/// <summary>
/// The ImageCommandColumnEditMode Enum provides an enumeration of the types
/// for how the Grid responds to an Edit Command
/// </summary>
/// <remarks>
/// </remarks>
/// -----------------------------------------------------------------------------
public enum ImageCommandColumnEditMode
{
Command,
URL
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_UnityEngine_Events_UnityEventCallState : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UnityEngine.Events.UnityEventCallState");
LuaObject.addMember(l, 0, "Off");
LuaObject.addMember(l, 1, "EditorAndRuntime");
LuaObject.addMember(l, 2, "RuntimeOnly");
LuaDLL.lua_pop(l, 1);
}
}
|
namespace Domain.Repository
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Dapper;
using Domain.Entities;
public abstract class Repository<TEntity> : IDisposable
where TEntity : BaseEntity, new()
{
private IDbConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
/// <summary>
/// Connection to database
/// </summary>
protected IDbConnection DbConnection => this.dbConnection;
/// <summary>
/// Adds a collection of TEntity
/// </summary>
/// <param name="entities"><see cref="IEnumerable{T}"/>the collection to be added</param>
public abstract void Add(IEnumerable<TEntity> entities);
/// <summary>
/// Adds an TEnitity
/// </summary>
/// <param name="entity">The TEntity to be added</param>
public abstract void Add(TEntity entity);
/// <summary>
/// Returns a TEntity by id
/// </summary>
/// <param name="id">the TEntity id</param>
/// <returns><see cref="TEntity"/>entity</returns>
public abstract TEntity GetById(Guid id);
/// <summary>
/// Updates a TEntity
/// </summary>
/// <param name="entity"><see cref="TEntity"/>the entity to be updated</param>
public abstract void Update(TEntity entity);
/// <summary>
/// Updated a collection of TEntity
/// </summary>
/// <param name="entities"><see cref="IEnumerable{T}"/>the collection to be updated</param>
public abstract void Update(IEnumerable<TEntity> entities);
/// <summary>
/// Deletes a collection of TEntity
/// </summary>
/// <param name="entities"><see cref="IEnumerable{T}"/>the collection to be deleted</param>
public abstract void Delete(IEnumerable<TEntity> entities);
/// <summary>
/// Deletes a TEntity
/// </summary>
/// <param name="entity">the entity to be deleted</param>
public abstract void Delete(TEntity entity);
/// <summary>
/// Disposes the connection to database
/// </summary>
public void Dispose()
{
this.dbConnection?.Dispose();
}
}
} |
using UnityEngine;
using GoogleMobileAds.Api;
using System;
//Banner ad
public class Admob : MonoBehaviour
{
private BannerView adBanner;
private string idApp, idBanner;
void Start ()
{
idApp = "ca-app-pub-3940256099942544~3347511713";
idBanner = "ca-app-pub-3940256099942544/6300978111";
MobileAds.Initialize (idApp);
RequestBannerAd ();
}
#region Banner Methods --------------------------------------------------
public void RequestBannerAd ()
{
adBanner = new BannerView (idBanner, AdSize.Banner, AdPosition.Bottom);
AdRequest request = AdRequestBuild ();
adBanner.LoadAd (request);
}
public void DestroyBannerAd ()
{
if (adBanner != null)
adBanner.Destroy ();
}
#endregion
//------------------------------------------------------------------------
AdRequest AdRequestBuild ()
{
return new AdRequest.Builder ().Build ();
}
void OnDestroy ()
{
DestroyBannerAd ();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RecipeApp.DataModels
{
public class Ingredient
{
public int Id { get; set; }
public string Name { get; set; }
public string Quantity { get; set; }
public string Yield { get; set; }
public string Time { get; set; }
public int RecipeId { get; set; }
}
}
|
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using DevExpress.XtraReports.UI;
using ControlLocalizer;
using BUS;
using System.Windows.Forms;
namespace GUI
{
public partial class r_dm_thets : DevExpress.XtraReports.UI.XtraReport
{
public r_dm_thets()
{
InitializeComponent();
LanguageHelper.Translate(this);
changeFont.Translate(this);
tran_rp.tran_ngay(ngay2, xrPageInfo2);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace HomeworkFour
{
class Program
{
public class AlarmEventArgs : EventArgs
{
public string Time { get; set; }
}
public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);
public class Alarmclock
{
public event AlarmEventHandler alarming;
public void Alarm(string a)
{
AlarmEventArgs arg = new AlarmEventArgs();
arg.Time = a;
string b = DateTime.Now.ToShortTimeString().ToString();
Thread.Sleep(1000);
if (arg.Time.Equals(b))
{
alarming(this, arg);
}
else
{
Alarm(a);
}
}
}
static void Main(string[] args)
{
Alarmclock oneclock = new Alarmclock();
oneclock.alarming += new AlarmEventHandler(Timeup);
oneclock.Alarm("18:08");//设置提醒的时间
}
static void Timeup(object sender, AlarmEventArgs e)
{
Console.WriteLine("It's time now!");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace console
{
public class _038_AddOne
{
/// <summary>
/// Given a number represented as an array of digits, plus one to the number.
/// Not hard at all just make sure carry the carry.
/// </summary>
/// <param name="digits"></param>
/// <returns></returns>
public List<int> AddOne(List<int> digits)
{
int carry = 0;
for (int i = digits.Count - 1; i >= 0; i--)
{
int tmp = digits[i];
if (i == digits.Count - 1) tmp++;
tmp += carry;
if (tmp >= 10)
{
digits[i] = tmp - 10;
carry = 1;
}
else
{
digits[i] = tmp;
carry = 0;
break;
}
}
if (carry > 0)
digits.Insert(0, carry);
return digits;
}
}
}
|
using System;
namespace backenddata
{
public class Class1
{
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Effect : MonoBehaviour
{
public float duration;
public bool replaceSelf = true;
public List<Type> cancelEffects = new List<Type>();
protected EnemyController enemy;
protected virtual void Awake()
{
enemy = transform.parent.gameObject.GetComponent<EnemyController>();
}
private void Start()
{
if(enemy != null)
StartCoroutine("ApplyEffectCoroutine");
}
public abstract void Interrupt();
public abstract IEnumerator ApplyEffectCoroutine();
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace SpecflowBDD.TAF.NUFramework
{
/// <summary>
/// Capture run time data.
/// </summary>
public class CaptureData
{
string testId;
Dictionary<string, string> data;
public bool HasData { get { return data.Count > 0; } }
public string TestId { get { return testId; } set { testId = value; } }
public CaptureData()
{
this.testId = null;
data = new Dictionary<string, string>();
}
public CaptureData(string testId) : this()
{
this.testId = testId;
}
public void Save(string name, string value)
{
data.Add(name, value);
}
public string Load(string name)
{
return data[name];
}
public void Export(string filename)
{
using (StreamWriter sw = new StreamWriter(filename, true))
{
if (!String.IsNullOrEmpty(testId))
{
sw.WriteLine("TestId={0}", testId);
}
foreach (KeyValuePair<string, string> entry in data)
{
sw.WriteLine("{0}={1}", entry.Key, entry.Value);
}
}
}
}
}
|
// Copyright (c) Micro Support Center, Inc. All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
namespace CodeGenHero.Core.Metadata
{
/// <summary>
/// Represents a type in an <see cref="IModel" />.
/// </summary>
public interface ITypeBase
{
/// <summary>
/// <para>
/// Gets the CLR class that is used to represent instances of this type.
/// Returns <c>null</c> if the type does not have a corresponding CLR class (known as a shadow type).
/// </para>
/// </summary>
Type ClrType { get; set; }
/// <summary>
/// Gets the model that this type belongs to.
/// </summary>
//IModel Model { get; set; }
/// <summary>
/// Gets the name of this type.
/// </summary>
string Name { get; set; }
}
} |
#region License
// Copyright (C) 2017 AlienGames
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
// USA
#endregion
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace AlienEngine
{
/// <summary>
/// Represents a four dimensional vector.
/// </summary>
[Serializable]
[TypeConverter(typeof(StructTypeConverter<Vector4b>))]
[StructLayout(LayoutKind.Sequential)]
public struct Vector4b : IEquatable<Vector4b>, ILoadFromString
{
/// <summary>
/// The X component of the Vector4b.
/// </summary>
public bool X;
/// <summary>
/// The Y component of the Vector4b.
/// </summary>
public bool Y;
/// <summary>
/// The Z component of the Vector4b.
/// </summary>
public bool Z;
/// <summary>
/// The W component of the Vector4b.
/// </summary>
public bool W;
/// <summary>
/// Defines a unit-length <see cref="Vector4b"/> that points towards the X-axis.
/// </summary>
public static readonly Vector4b UnitX = new Vector4b(true, false, false, false);
/// <summary>
/// Defines a unit-length <see cref="Vector4b"/> that points towards the Y-axis.
/// </summary>
public static readonly Vector4b UnitY = new Vector4b(false, true, false, false);
/// <summary>
/// Defines a unit-length <see cref="Vector4b"/> that points towards the Z-axis.
/// </summary>
public static readonly Vector4b UnitZ = new Vector4b(false, false, true, false);
/// <summary>
/// Defines a unit-length <see cref="Vector4b"/> that points towards the W-axis.
/// </summary>
public static readonly Vector4b UnitW = new Vector4b(false, false, false, true);
/// <summary>
/// Defines a zero-length <see cref="Vector4b"/>.
/// </summary>
public static readonly Vector4b Zero = new Vector4b(false);
/// <summary>
/// Defines a <see cref="Vector4b"/> populated with true.
/// </summary>
public static readonly Vector4b One = new Vector4b(true);
/// <summary>
/// Defines the size of the Vector2f struct in bytes.
/// </summary>
public const int SizeInBytes = sizeof(bool) * 4;
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector4b(bool value)
{
X = Y = Z = W = value;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="x">The x coordinate of the net Vector4b.</param>
/// <param name="y">The y coordinate of the net Vector4b.</param>
/// <param name="z">The z coordinate of the net Vector4b.</param>
/// <param name="w">The w coordinate of the net Vector4b.</param>
public Vector4b(bool x, bool y, bool z, bool w)
{
X = x;
Y = y;
Z = z;
W = w;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="v">The Vector3b to copy.</param>
public Vector4b(Vector3b v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
W = false;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="v">The Vector3b to copy.</param>
/// <param name="w">The w coordinate.</param>
public Vector4b(Vector3b v, bool w)
{
X = v.X;
Y = v.Y;
Z = v.Z;
W = w;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="v">The Vector4b to copy.</param>
public Vector4b(Vector4b v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
W = v.W;
}
/// <summary>
/// Gets or sets the value at the index of the Vector.
/// </summary>
public bool this[int index]
{
get
{
if (index == 0) return X;
else if (index == 1) return Y;
else if (index == 2) return Z;
else if (index == 3) return W;
else throw new IndexOutOfRangeException();
}
set
{
if (index == 0) X = value;
else if (index == 1) Y = value;
else if (index == 2) Z = value;
else if (index == 3) W = value;
else throw new IndexOutOfRangeException();
}
}
/// <summary>
/// Compares the specified instances for inequality.
/// </summary>
/// <param name="left">Left operand.</param>
/// <param name="right">Right operand.</param>
/// <returns>True if both instances are not equal; false otherwise.</returns>
public static bool operator !=(Vector4b left, Vector4b right)
{
return (left.X != right.X || left.Y != right.Y || left.Z != right.Z || left.W != right.W);
}
/// <summary>
/// Compares the specified instances for equality.
/// </summary>
/// <param name="left">Left operand.</param>
/// <param name="right">Right operand.</param>
/// <returns>True if both instances are not equal; false otherwise.</returns>
public static bool operator ==(Vector4b left, Vector4b right)
{
return (left.X == right.X && left.Y == right.Y && left.Z == right.Z && left.W == right.W);
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
return (obj is Vector4b) && (Equals((Vector4b)obj));
}
/// <summary>Indicates whether the current vector is equal to another vector.</summary>
/// <param name="other">A vector to compare with this vector.</param>
/// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns>
public bool Equals(Vector4b other)
{
return (X == other.X && Y == other.Y && Z == other.Z && W == other.W);
}
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return ToString().GetHashCode();
}
/// <summary>
/// Load this instance from the <see cref="System.String"/> representation.
/// </summary>
/// <param name="value">The <see cref="System.String"/> value to convert.</param>
void ILoadFromString.FromString(string value)
{
string[] parts = value.Trim('(', ')').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
bool.TryParse(parts[0], out X);
bool.TryParse(parts[1], out Y);
bool.TryParse(parts[2], out Z);
bool.TryParse(parts[3], out W);
}
/// <summary>
/// Gets the array representation of the Vector2f.
/// </summary>
public bool[] ToArray()
{
return new bool[] { X, Y, Z, W };
}
/// <summary>
/// Returns a string that represents the current Vector4b.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("({0} , {1} , {2} , {3})", X, Y, Z, W);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// INHERITANCE
// AbstractBaseTurret is the parent of FollowingTurret, RotatingTurret and StaticTurret.
// Turrets have 2 abstract behaviors, Move and Attack.
public abstract class AbstractBaseTurret : MonoBehaviour
{
[SerializeField] private float attackRate;
private static readonly float firstAttackDelay = 2.0f;
private ProjectileObjectPool projectileObjectPool;
private GameObject currentProjectile;
void Start()
{
projectileObjectPool = GetComponent<ProjectileObjectPool>();
InvokeRepeating("Attack", firstAttackDelay, attackRate);
}
protected virtual void FixedUpdate()
{
if (GameManager.instance.isGameActive)
{
Move();
}
}
// POLYMORPHISM + ABSTRACTION
// Attack method is overloaded
// This one spawns the projectile in the looking direction of the attached projectile spawn game object.
// This method also represents one of the basic behaviors of turrets, that's why it's abstracted.
protected virtual void Attack()
{
Attack(transform.Find("Body/ProjectileSpawn"));
}
// POLYMORPHISM + ABSTRACTION
// Attack method is overloaded
// This one spawns the projectile in the looking direction of a specified Transform object.
protected virtual void Attack(Transform projectileSpawn)
{
if (!GameManager.instance.isGameActive)
{
return;
}
currentProjectile = projectileObjectPool.GetProjectile();
if (currentProjectile != null)
{
currentProjectile.transform.position = projectileSpawn.position;
currentProjectile.GetComponent<SimpleProjectile>().FireProjectile(projectileSpawn.right);
}
}
// POLYMORPHISM + ABSTRACTION
// This method is abstract, every concrete implementation must override it.
// This method also represents one of the basic behaviors of turrets, that's why it's abstracted.
protected abstract void Move();
}
|
using System;
namespace Dietando.ViewModel
{
public class CadastroUsuarioViewModel : BaseViewModel
{
private String _nome;
public String Nome{
get{
return _nome;
}
set{
_nome = value;
NotifyPropertyChange ("Nome");
}
}
private String _email;
public String Email{
get{
return _email;
}
set{
_email = value;
NotifyPropertyChange ("Email");
}
}
private String _senha;
public String Senha{
get{
return _senha;
}
set{
_senha = value;
NotifyPropertyChange ("Senha");
}
}
public CadastroUsuarioViewModel ()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ExpenseTracker.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SettingsPage : ContentPage
{
ViewModels.SettingsViewModel viewModel;
public SettingsPage()
{
InitializeComponent();
this.BindingContext = viewModel = new ViewModels.SettingsViewModel();
}
async void OnAdd(object sender, EventArgs e)
{
String userID = Preferences.Get("ExpenseT_UserID", "NULL");
viewModel.IsBusy = true;
try
{
if (viewModel.CategoryPicker == "Expense")
{
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
viewModel.DataQuery.expenseSelect = "INSERT INTO ExpenseCategory VALUES ";
viewModel.DataQuery.expenseWhere = "('" + viewModel.CategoryName + "', 'New User Category', '" + userID + "')";
viewModel.ExpenseCategoryInfo = viewModel.DataQuery.ExecuteAQuery<Exp_Inc_Category>();
DependencyService.Get<IToast>().Show("New Category " + viewModel.CategoryName + " Created");
}
}
else if (viewModel.CategoryPicker == "Income")
{
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
viewModel.DataQuery.expenseSelect = "INSERT INTO IncomeCategory VALUES ";
viewModel.DataQuery.expenseWhere = "('" + viewModel.CategoryName + "', 'New User Category', '" + userID + "')";
viewModel.ExpenseCategoryInfo = viewModel.DataQuery.ExecuteAQuery<Exp_Inc_Category>();
DependencyService.Get<IToast>().Show("New Category " + viewModel.CategoryName + " Created");
}
}
}
catch (Exception ex)
{
await DisplayAlert("Adding account failed", ex.Message, "OK");
viewModel.IsBusy = false;
}
}
private void OnSave(object sender, EventArgs e)
{
Preferences.Set("start_date", viewModel.PickerStartDate);
if (viewModel.PickerEndDate != DateTime.Now)
Preferences.Set("end_date", viewModel.PickerEndDate);
else
{
Preferences.Remove("end_date");
}
Navigation.PopAsync();
}
private void OnCancel(object sender, EventArgs e)
{
Navigation.PopAsync();
}
}
} |
using Athena.Data.Books;
namespace Athena.Messages {
public class EditBookMessage {
public BookView BookView { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Quit : MonoBehaviour
{
public void startGame()
{
SceneManager.LoadScene("Main");
Time.timeScale = 1;
}
public void BackToReality()
{
Application.Quit();
}
public void goToScores()
{
SceneManager.LoadScene("Scores");
}
public void goToMainMenu()
{
SceneManager.LoadScene("Menu");
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using OmniSharp.Extensions.JsonRpc.Generators.Contexts;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static OmniSharp.Extensions.JsonRpc.Generators.Helpers;
using static OmniSharp.Extensions.JsonRpc.Generators.DelegateHelpers;
namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies
{
internal class OnRequestMethodGeneratorWithoutRegistrationOptionsStrategy : IExtensionMethodContextGeneratorStrategy
{
private readonly bool _doResolve;
public OnRequestMethodGeneratorWithoutRegistrationOptionsStrategy(bool doResolve)
{
_doResolve = doResolve;
}
public IEnumerable<MemberDeclarationSyntax> Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item)
{
if (item is { RegistrationOptions: { } }) yield break;
if (item is not RequestItem request) yield break;
if (extensionMethodContext is not { IsRegistry: true }) yield break;
var resolve = GeneratorData.CreateForResolver(item);
if (!_doResolve) resolve = null;
if (_doResolve && resolve is null) yield break;
var allowDerivedRequests = item.JsonRpcAttributes.AllowDerivedRequests && !_doResolve;
var method = MethodDeclaration(extensionMethodContext.Item, item.JsonRpcAttributes.HandlerMethodName)
.WithModifiers(
TokenList(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword)
)
)
.WithExpressionBody(GetRequestHandlerExpression(request, GetJsonRpcMethodName(extensionMethodContext.TypeDeclaration)))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
if (item is RequestItem { Response: { Symbol: ITypeParameterSymbol } } ri)
{
method = method.AddTypeParameterListParameters(TypeParameter(ri.Response.Symbol.Name));
}
var methodFactory = MakeFactory(extensionMethodContext.GetRegistryParameterList());
var factory = methodFactory(method);
yield return factory(
CreateAsyncFunc(request.Response.Syntax, false, request.Request.Syntax),
resolve.ReturnIfNotNull(static r => CreateAsyncFunc(r.Response.Syntax, false, r.Request.Syntax))
);
yield return factory(
CreateAsyncFunc(request.Response.Syntax, true, request.Request.Syntax),
resolve.ReturnIfNotNull(static r => CreateAsyncFunc(r.Response.Syntax, false, r.Request.Syntax))
);
if (allowDerivedRequests)
{
var genericFactory = MakeGenericFactory(factory, request.Request.Syntax);
yield return genericFactory(
CreateAsyncFunc(request.Response.Syntax, false, IdentifierName("T")), null
);
yield return genericFactory(CreateAsyncFunc(request.Response.Syntax, true, IdentifierName("T")), null);
}
{
if (request.Capability is { } capability)
{
if (request.IsUnit)
{
factory = methodFactory(
method.WithExpressionBody(
GetVoidRequestCapabilityHandlerExpression(
GetJsonRpcMethodName(extensionMethodContext.TypeDeclaration), request.Request.Syntax, capability.Syntax
)
)
);
}
else
{
factory = methodFactory(
method.WithExpressionBody(
GetRequestCapabilityHandlerExpression(
GetJsonRpcMethodName(extensionMethodContext.TypeDeclaration), request.Request.Syntax, request.Response.Syntax, capability.Syntax
)
)
);
}
yield return factory(
CreateAsyncFunc(request.Response.Syntax, true, request.Request.Syntax, capability.Syntax),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, true, r.Request.Syntax, capability.Syntax))
);
if (allowDerivedRequests)
{
var genericFactory = MakeGenericFactory(factory, request.Request.Syntax);
yield return genericFactory(
CreateAsyncFunc(request.Response.Syntax, true, IdentifierName("T"), capability.Syntax),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, true, r.Request.Syntax, capability.Syntax))
);
}
}
}
if (request.PartialItems is { } partialItems)
{
var partialItemsSyntax = GenericName("IEnumerable").WithTypeArgumentList(TypeArgumentList(SeparatedList(new[] { partialItems.Syntax })));
factory = methodFactory(
method
.WithIdentifier(Identifier(item.JsonRpcAttributes.PartialHandlerMethodName))
.WithExpressionBody(
GetPartialResultsHandlerExpression(
GetJsonRpcMethodName(extensionMethodContext.TypeDeclaration), request.Request.Syntax, partialItems.Syntax, request.Response.Syntax
)
)
);
yield return factory(
CreatePartialAction(request.Request.Syntax, partialItemsSyntax, false),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, false, r.Request.Syntax))
);
yield return factory(
CreatePartialAction(request.Request.Syntax, partialItemsSyntax, true),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, true, r.Request.Syntax))
);
if (allowDerivedRequests)
{
var genericFactory = MakeGenericFactory(factory, request.Request.Syntax);
yield return genericFactory(
CreatePartialAction(IdentifierName("T"), partialItemsSyntax, false),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, false, r.Request.Syntax))
);
yield return genericFactory(
CreatePartialAction(IdentifierName("T"), partialItemsSyntax, true),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, true, r.Request.Syntax))
);
}
if (request.Capability is { } capability)
{
factory = methodFactory(
method
.WithIdentifier(Identifier(item.JsonRpcAttributes.PartialHandlerMethodName))
.WithExpressionBody(
GetPartialResultsCapabilityHandlerExpression(
GetJsonRpcMethodName(extensionMethodContext.TypeDeclaration), request.Request.Syntax, request.Response.Syntax,
partialItems.Syntax, capability.Syntax
)
)
);
yield return factory(
CreatePartialAction(request.Request.Syntax, partialItemsSyntax, true, capability.Syntax),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, true, r.Request.Syntax, capability.Syntax))
);
if (allowDerivedRequests)
{
var genericFactory = MakeGenericFactory(factory, request.Request.Syntax);
yield return genericFactory(
CreatePartialAction(IdentifierName("T"), partialItemsSyntax, true, capability.Syntax),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, true, r.Request.Syntax, capability.Syntax))
);
}
}
}
if (request.PartialItem is { } partialItem)
{
factory = methodFactory(
method.WithExpressionBody(
GetPartialResultHandlerExpression(
GetJsonRpcMethodName(extensionMethodContext.TypeDeclaration), request.Request.Syntax, partialItem.Syntax, request.Response.Syntax
)
)
);
yield return factory(
CreatePartialAction(request.Request.Syntax, partialItem.Syntax, false),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, false, r.Request.Syntax))
);
yield return factory(
CreatePartialAction(request.Request.Syntax, partialItem.Syntax, true),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, true, r.Request.Syntax))
);
if (allowDerivedRequests)
{
var genericFactory = MakeGenericFactory(factory, request.Request.Syntax);
yield return genericFactory(CreatePartialAction(IdentifierName("T"), partialItem.Syntax, false), null);
yield return genericFactory(CreatePartialAction(IdentifierName("T"), partialItem.Syntax, true), null);
}
if (request.Capability is { } capability)
{
factory = methodFactory(
method.WithExpressionBody(
GetPartialResultCapabilityHandlerExpression(
GetJsonRpcMethodName(extensionMethodContext.TypeDeclaration), request.Request.Syntax, partialItem.Syntax, request.Response.Syntax, capability.Syntax
)
)
);
yield return factory(
CreatePartialAction(request.Request.Syntax, partialItem.Syntax, true, capability.Syntax),
resolve.ReturnIfNotNull(r => CreateAsyncFunc(r.Response.Syntax, true, r.Request.Syntax, capability.Syntax))
);
if (allowDerivedRequests)
{
var genericFactory = MakeGenericFactory(factory, request.Request.Syntax);
yield return genericFactory(CreatePartialAction(IdentifierName("T"), partialItem.Syntax, true, capability.Syntax), null);
}
}
}
}
private static Func<MethodDeclarationSyntax, Func<TypeSyntax, TypeSyntax?, MethodDeclarationSyntax>> MakeFactory(
ParameterListSyntax preParameterList
)
{
return method => (syntax, resolveSyntax) => GenerateMethods(method, syntax, resolveSyntax);
MethodDeclarationSyntax MethodFactory(MethodDeclarationSyntax method, TypeSyntax syntax, TypeSyntax? resolveSyntax)
{
return method
.WithParameterList(
preParameterList
.AddParameters(Parameter(Identifier("handler")).WithType(syntax))
.AddParameters(
resolveSyntax is { }
? new[] {
Parameter(Identifier("resolveHandler"))
.WithType(resolveSyntax)
}
: new ParameterSyntax[] { }
)
);
}
MethodDeclarationSyntax GenerateMethods(MethodDeclarationSyntax method, TypeSyntax syntax, TypeSyntax? resolveSyntax) => MethodFactory(method, syntax, resolveSyntax);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Networking;
public class LevelLayout : NetworkBehaviour {
public GameObject ObstacleParent;
public GameObject _spawnArea;
public GameObject[] RockGameObjects;
protected string[,] GeneratedLevelLayout;
protected string[,] EmptyLevelLayout;
// Our boundaries, set using the GameObject positions in scene
protected float MinX;
protected float MinZ;
protected float MaxX;
protected float MaxZ;
public virtual void Setup<T>(int num, T info)
{
_spawnArea = transform.Find("SpawnArea").gameObject;
MinX = _spawnArea.transform.Find("BottomLeft").position.x;
MinZ = _spawnArea.transform.Find("BottomLeft").position.z;
MaxX = _spawnArea.transform.Find("TopRight").position.x;
MaxZ = _spawnArea.transform.Find("TopRight").position.z;
SetLevelLayout();
}
public virtual void NewSetup<T>(int num, T info)
{
GeneratePath();
}
private void SetLevelLayout()
{
// Get the width available
// Each block is 1x1x1
var blockWidth = 1;
var width = MaxX - MinX;
var height = MaxZ - MinZ;
// Get the intervals
var widthSpace = Mathf.RoundToInt(width / blockWidth);
// Add 1 to width for block at 0 pos
widthSpace += 1;
var heightSpece = Mathf.RoundToInt(height / blockWidth);
if (GeneratedLevelLayout == null)
{
GeneratedLevelLayout = new string[widthSpace, heightSpece];
ResetLevelArray(widthSpace, heightSpece);
}
GeneratePath();
}
public void ResetLevelArray(int width, int height)
{
for (var i = 0; i < width; i++)
{
for (var j = 0; j < height; j++)
{
// Set char to clear
GeneratedLevelLayout[i, j] = "c";
}
}
}
/// <summary>
/// Generate a path that the players can follow from start to finish
/// </summary>
public void GeneratePath()
{
ResetLevelArray(GeneratedLevelLayout.GetLength(0), GeneratedLevelLayout.GetLength(1));
// Set the start and end positions
var width = GeneratedLevelLayout.GetLength(0);
var midpoint = (width / 2);
// Set midpoint of first row as start point
GeneratedLevelLayout[midpoint, 0] = "+";
GeneratedLevelLayout[midpoint - 1, 0] = "+";
// Set midpoint of the last row as end point
GeneratedLevelLayout[midpoint, GeneratedLevelLayout.GetLength(1) - 1] = "s";
GeneratedLevelLayout[midpoint - 1, GeneratedLevelLayout.GetLength(1) - 1] = "s";
var previousPosition = midpoint;
var centerX = GeneratedLevelLayout.GetLength(0) / 2;
var centerZ = GeneratedLevelLayout.GetLength(1) / 2;
GeneratedLevelLayout[centerX + 1, centerZ] = "s";
GeneratedLevelLayout[centerX - 2, centerZ] = "s";
GeneratedLevelLayout[centerX + 1, centerZ - 1] = "s";
GeneratedLevelLayout[centerX - 2, centerZ - 1] = "s";
// Iterate through the array to create a path
for (var j = 1; j < GeneratedLevelLayout.GetLength(1); j++)
{
var pathPosition = previousPosition + Random.Range(-1, 2);
if (pathPosition < 0)
{
pathPosition = 0;
}
if (pathPosition >= width)
{
pathPosition = width - 1;
}
// allow for some space to move from the previous position to the new path position
GeneratedLevelLayout[previousPosition, j] = "+";
GeneratedLevelLayout[pathPosition, j] = "+";
//// HACK allow game be completed solo
//GeneratedLevelLayout[midpoint, j] = '+';
//GeneratedLevelLayout[midpoint - 1, j] = '+';
//// END HACK
previousPosition = pathPosition;
}
// Block the path so players must work together s = sign location
GeneratedLevelLayout[centerX, centerZ] = "s";
GeneratedLevelLayout[centerX - 1, centerZ] = "s";
// Make sure that their is still a path around the blocked area
//bool right = GeneratedLevelLayout[centerX, centerZ - 2] == "s" ||
// GeneratedLevelLayout[centerX + 1, centerZ - 2] == "s";
GeneratedLevelLayout[centerX, centerZ - 1] = "s";
GeneratedLevelLayout[centerX - 1, centerZ - 1] = "s";
GeneratedLevelLayout[centerX, centerZ + 1] = "s";
GeneratedLevelLayout[centerX - 1, centerZ + 1] = "s";
GeneratedLevelLayout[centerX - 2, centerZ + 1] = "s";
GeneratedLevelLayout[centerX + 1, centerZ + 1] = "s";
//// Left/Right
//if (right)
//{
// GeneratedLevelLayout[centerX + 1, centerZ] = "+";
//}
//else
//{
// GeneratedLevelLayout[centerX - 2, centerZ] = "+";
//}
//// Up/Down
//if (right)
//{
// GeneratedLevelLayout[centerX, centerZ - 1] = "+";
//}
//else
//{
// GeneratedLevelLayout[centerX - 1, centerZ - 1] = "+";
//}
//// Diagonals
//if (right)
//{
// GeneratedLevelLayout[centerX + 1, centerZ + 1] = "s";
// GeneratedLevelLayout[centerX + 1, centerZ - 1] = "s";
//}
//else
//{
// GeneratedLevelLayout[centerX - 2, centerZ + 1] = "s";
// GeneratedLevelLayout[centerX - 2, centerZ - 1] = "s";
//}
}
public string GetArrayString()
{
var arrayString = "";
for (var i = 0; i < GeneratedLevelLayout.GetLength(1); i++)
{
var rowString = "{";
for (var j = 0; j < GeneratedLevelLayout.GetLength(0); j++)
{
rowString += " " + GeneratedLevelLayout[j, i] + ",";
}
rowString = rowString.Substring(0, rowString.Length - 1) + " }";
arrayString += "\n" + rowString;
}
return arrayString;
}
public int GetAvailableSpaces()
{
var available = 0;
foreach (var c in GeneratedLevelLayout)
{
if (c == "c")
{
// Clear position
available++;
}
}
return available;
}
[ServerAccess]
public void ClearChildren()
{
var method = MethodBase.GetCurrentMethod();
var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0];
if (!attr.HasAccess)
{
return;
}
var children = ObstacleParent.GetComponentsInChildren<Transform>();
foreach (var child in children)
{
if (child.GetComponent<NetworkIdentity>() == null)
continue;
if (child != ObstacleParent.transform)
{
NetworkServer.UnSpawn(child.gameObject);
Destroy(child.gameObject);
}
}
}
[ServerAccess]
public void GenerateObstacles()
{
var method = MethodBase.GetCurrentMethod();
var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0];
if (!attr.HasAccess)
{
return;
}
for (var i = 0; i < GeneratedLevelLayout.GetLength(0); i++)
{
for (var j = 0; j < GeneratedLevelLayout.GetLength(1); j++)
{
if (GeneratedLevelLayout[i, j] == "x")
{
// Create an object
var location = new Vector3(MinX + i, -0.5f, MinZ + j);
CreateObstacle(location, ObstacleParent.transform);
}
}
}
}
[ServerAccess]
private void CreateObstacle(Vector3 position, Transform parent)
{
var method = MethodBase.GetCurrentMethod();
var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0];
if (!attr.HasAccess)
{
return;
}
var rockNumber = Random.Range(0, RockGameObjects.Length);
var yRotation = Random.Range(0, 4) * 90f;
var go = Instantiate(RockGameObjects[rockNumber], position, Quaternion.identity);
go.transform.SetParent(parent, false);
go.transform.eulerAngles = new Vector3(0f, yRotation, 0f);
if (!SP_Manager.Instance.IsSinglePlayer())
{
NetworkServer.Spawn(go);
}
}
[ServerAccess]
public void GenerateCollectibles(GameObject collectible)
{
var method = MethodBase.GetCurrentMethod();
var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0];
if (!attr.HasAccess)
{
return;
}
for (var i = 0; i < GeneratedLevelLayout.GetLength(0); i++)
{
for (var j = 0; j < GeneratedLevelLayout.GetLength(1); j++)
{
// Check that the space has extra content that should be shown for the collectible
if (GeneratedLevelLayout[i, j] != "c" && GeneratedLevelLayout[i,j] != "x" && GeneratedLevelLayout[i,j] != "+" && GeneratedLevelLayout[i, j] != "s")
{
// Create an object
var location = new Vector3(MinX + i, -0.5f, MinZ + j);
CreateCollectible(collectible, location, ObstacleParent.transform, GeneratedLevelLayout[i, j]);
}
}
}
}
[ServerAccess]
private void CreateCollectible(GameObject gameObject, Vector3 position, Transform parent, string info)
{
var method = MethodBase.GetCurrentMethod();
var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0];
if (!attr.HasAccess)
{
return;
}
var go = Instantiate(gameObject, position, Quaternion.identity);
go.transform.SetParent(parent, false);
go.transform.eulerAngles = new Vector3(0f, 0f, 0f);
go.GetComponent<MathsCollectible>().Set(info);
if (!SP_Manager.Instance.IsSinglePlayer())
{
NetworkServer.Spawn(go);
}
}
public void GenerateNewLevel(int obstacles)
{
//StartCoroutine(ChangeBlocks(obstacles, 0.8f));
ChangeBlocksImmediate(obstacles);
}
public void ChangeBlocksImmediate(int obstacles)
{
NewSetup(obstacles, "");
}
public IEnumerator ChangeBlocks(int obstacles, float time)
{
var initialPos = transform.position;
var hiddenPos = new Vector3(transform.position.x, transform.position.y - 2f, transform.position.z);
yield return Move(initialPos, hiddenPos, time);
NewSetup(obstacles, "");
yield return Move(hiddenPos, initialPos, time);
}
public IEnumerator Move(Vector3 from, Vector3 to, float time)
{
var elapsed = 0f;
while (elapsed < time)
{
transform.position = Vector3.Lerp(from, to, elapsed / time);
elapsed += Time.deltaTime;
yield return null;
}
transform.position = to;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Trettim.Settings;
using Trettim.Sicredi.DocumentLibrary.Services;
namespace Trettim.Sicredi.DocumentLibrary.DocumentLibrary.HTML
{
public partial class ViewHTML : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
String path = Param.SiteURL + Param.DocumentLibrary.Replace("~", "") + base.GetString("path");
litIFrame.Text = "<iframe src='" + path + "' frameborder='0' style='border:none; width:100%; height:900px;' allowTransparency='true'></iframe>";
}
}
} |
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace CloudinaryDotNet.Actions
{
[DataContract]
public class StreamingProfileResult : BaseResult
{
[DataMember(Name = "message")]
public string Message { get; protected set; }
[DataMember(Name = "data")]
public StreamingProfileData Data { get; protected set; }
}
[DataContract]
public class StreamingProfileData : StreamingProfileBaseData
{
/// <summary>
/// A collection of Representations that defines a custom streaming profile
/// </summary>
[DataMember(Name = "representations")]
public List<Representation> Representations { get; set; }
}
[DataContract]
public class StreamingProfileListResult : BaseResult
{
[DataMember(Name = "data")]
public IEnumerable<StreamingProfileBaseData> Data { get; protected set; }
}
[DataContract]
public class StreamingProfileBaseData
{
/// <summary>
/// The identification name of the new streaming profile.
/// </summary>
[DataMember(Name = "name")]
public string Name { get; protected set; }
/// <summary>
/// A descriptive name for the profile.
/// </summary>
[DataMember(Name = "display_name")]
public string DisplayName { get; protected set; }
/// <summary>
/// True if streaming profile is defined
/// </summary>
[DataMember(Name = "predefined")]
public bool Predefined { get; protected set; }
}
}
|
namespace DevDevDev.Models
{
public static class EventConfig
{
public const string EventTitle = "DDD Sydney";
public const string EventDateDescription = "15th July 2017";
public const int TotalVotes = 10;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tripper.Services.Entities.Abstract;
namespace Tripper.Services.Core
{
public class RouteService : IRouteService
{
}
}
|
#region Usings
using IQuery=NHibernate.IQuery;
using ISession=NHibernate.ISession;
using ITransaction=NHibernate.ITransaction;
#endregion
namespace NDDDSample.Persistence.NHibernate.Utils
{
#region Usings
using System;
using System.Collections.Generic;
using Domain.Model.Cargos;
using Domain.Model.Handlings;
using Domain.Model.Locations;
using Domain.Model.Voyages;
using Infrastructure;
using Rhino.Commons;
#endregion
/// <summary>
/// Provides sample data.
/// </summary>
public static class SampleDataGenerator
{
private static DateTime BaseTime;
static SampleDataGenerator()
{
BaseTime = new DateTime(2008, 01, 01).AddDays(-100);
}
private static void LoadHandlingEventData(ISession session)
{
const string handlingEventSql =
"insert into HandlingEvent (completionTime, registrationTime, type, location_id, voyage_id, cargo_id) " +
"values (?, ?, ?, ?, ?, ?)";
var handlingEventArgs = new[]
{
//XYZ (SESTO-FIHEL-DEHAM-CNHKG-JPTOK-AUMEL)
new object[] {Ts(0), Ts((0)), "RECEIVE", 1, null, 1},
new object[] {Ts((4)), Ts((5)), "LOAD", 1, 1, 1},
new object[] {Ts((14)), Ts((14)), "UNLOAD", 5, 1, 1},
new object[] {Ts((15)), Ts((15)), "LOAD", 5, 1, 1},
new object[] {Ts((30)), Ts((30)), "UNLOAD", 6, 1, 1},
new object[] {Ts((33)), Ts((33)), "LOAD", 6, 1, 1},
new object[] {Ts((34)), Ts((34)), "UNLOAD", 3, 1, 1},
new object[] {Ts((60)), Ts((60)), "LOAD", 3, 1, 1},
new object[] {Ts((70)), Ts((71)), "UNLOAD", 4, 1, 1},
new object[] {Ts((75)), Ts((75)), "LOAD", 4, 1, 1},
new object[] {Ts((88)), Ts((88)), "UNLOAD", 2, 1, 1},
new object[] {Ts((100)), Ts((102)), "CLAIM", 2, null, 1},
//ZYX (AUMEL - USCHI - DEHAM -)
new object[] {Ts((200)), Ts((201)), "RECEIVE", 2, null, 3},
new object[] {Ts((202)), Ts((202)), "LOAD", 2, 2, 3},
new object[] {Ts((208)), Ts((208)), "UNLOAD", 7, 2, 3},
new object[] {Ts((212)), Ts((212)), "LOAD", 7, 2, 3},
new object[] {Ts((230)), Ts((230)), "UNLOAD", 6, 2, 3},
new object[] {Ts((235)), Ts((235)), "LOAD", 6, 2, 3},
//ABC
new object[] {Ts((20)), Ts((21)), "CLAIM", 2, null, 2},
//CBA
new object[] {Ts((0)), Ts((1)), "RECEIVE", 2, null, 4},
new object[] {Ts((10)), Ts((11)), "LOAD", 2, 2, 4},
new object[] {Ts((20)), Ts((21)), "UNLOAD", 7, 2, 4},
//FGH
new object[] {Ts(100), Ts(160), "RECEIVE", 3, null, 5},
new object[] {Ts(150), Ts(110), "LOAD", 3, 3, 5},
//JKL
new object[] {Ts(200), Ts(220), "RECEIVE", 6, null, 6},
new object[] {Ts(300), Ts(330), "LOAD", 6, 3, 6},
new object[] {Ts(400), Ts(440), "UNLOAD", 5, 3, 6} // Unexpected event
};
ExecuteUpdate(session, handlingEventSql, handlingEventArgs);
}
private static void LoadCarrierMovementData(ISession session)
{
const string voyageSql = "insert into Voyage (id, voyage_number) values (?, ?)";
var voyageArgs = new[]
{
new object[] {1, "0101"},
new object[] {2, "0202"},
new object[] {3, "0303"}
};
ExecuteUpdate(session, voyageSql, voyageArgs);
const string carrierMovementSql =
"insert into CarrierMovement (id, voyage_id, departure_location_id, arrival_location_id, departure_time, arrival_time, cm_index) " +
"values (?,?,?,?,?,?,?)";
var carrierMovementArgs = new[]
{
// SESTO - FIHEL - DEHAM - CNHKG - JPTOK - AUMEL (voyage 0101)
new object[] {1, 1, 1, 5, Ts(1), Ts(2), 0},
new object[] {2, 1, 5, 6, Ts(1), Ts(2), 1},
new object[] {3, 1, 6, 3, Ts(1), Ts(2), 2},
new object[] {4, 1, 3, 4, Ts(1), Ts(2), 3},
new object[] {5, 1, 4, 2, Ts(1), Ts(2), 4},
// AUMEL - USCHI - DEHAM - SESTO - FIHEL (voyage 0202)
new object[] {7, 2, 2, 7, Ts(1), Ts(2), 0},
new object[] {8, 2, 7, 6, Ts(1), Ts(2), 1},
new object[] {9, 2, 6, 1, Ts(1), Ts(2), 2},
new object[] {6, 2, 1, 5, Ts(1), Ts(2), 3},
// CNHKG - AUMEL - FIHEL - DEHAM - SESTO - USCHI - JPTKO (voyage 0303)
new object[] {10, 3, 3, 2, Ts(1), Ts(2), 0},
new object[] {11, 3, 2, 5, Ts(1), Ts(2), 1},
new object[] {12, 3, 6, 1, Ts(1), Ts(2), 2},
new object[] {13, 3, 1, 7, Ts(1), Ts(2), 3},
new object[] {14, 3, 7, 4, Ts(1), Ts(2), 4}
};
ExecuteUpdate(session, carrierMovementSql, carrierMovementArgs);
}
private static void LoadCargoData(ISession session)
{
const string cargoSql =
"insert into Cargo (id, tracking_id, origin_id, spec_origin_id, spec_destination_id, spec_arrival_deadline, transport_status, current_voyage_id, last_known_location_id, is_misdirected, routing_status, calculated_at, unloaded_at_dest) " +
"values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
var cargoArgs = new[]
{
new object[]
{
1, "XYZ", 1, 1, 2, Ts(10), "IN_PORT", null, 1, false, "ROUTED", Ts(100),
false
},
new object[]
{
2, "ABC", 1, 1, 5, Ts(20), "IN_PORT", null, 1, false, "ROUTED", Ts(100),
false
},
new object[]
{
3, "ZYX", 2, 2, 1, Ts(30), "IN_PORT", null, 1, false, "NOT_ROUTED", Ts(100),
false
},
new object[]
{
4, "CBA", 5, 5, 1, Ts(40), "IN_PORT", null, 1, false, "MISROUTED", Ts(100),
false
},
new object[]
{
5, "FGH", 1, 3, 5, Ts(50), "IN_PORT", null, 1, false, "ROUTED", Ts(100),
false
}, // Cargo origin differs from spec origin
new object[]
{
6, "JKL", 6, 6, 4, Ts(60), "IN_PORT", null, 1, true, "ROUTED", Ts(100),
false
}
};
ExecuteUpdate(session, cargoSql, cargoArgs);
}
private static void LoadLocationData(ISession session)
{
const string locationSql = "insert into Location (id, unlocode, name) " +
"values (?, ?, ?)";
var locationArgs = new[]
{
new object[] {1, "SESTO", "Stockholm"},
new object[] {2, "AUMEL", "Melbourne"},
new object[] {3, "CNHKG", "Hongkong"},
new object[] {4, "JPTOK", "Tokyo"},
new object[] {5, "FIHEL", "Helsinki"},
new object[] {6, "DEHAM", "Hamburg"},
new object[] {7, "USCHI", "Chicago"}
};
ExecuteUpdate(session, locationSql, locationArgs);
}
private static void LoadItineraryData(ISession session)
{
const string legSql =
"insert into Leg (id, cargo_id, voyage_id, load_location_id, unload_location_id, load_time, unload_time, leg_index) " +
"values (?,?,?,?,?,?,?,?)";
var legArgs = new[]
{
// Cargo 5: Hongkong - Melbourne - Stockholm - Helsinki
new object[] {1, 5, 1, 3, 2, Ts(1), Ts(2), 0},
new object[] {2, 5, 1, 2, 1, Ts(3), Ts(4), 1},
new object[] {3, 5, 1, 1, 5, Ts(4), Ts(5), 2},
// Cargo 6: Hamburg - Stockholm - Chicago - Tokyo
new object[] {4, 6, 2, 6, 1, Ts(1), Ts(2), 0},
new object[] {5, 6, 2, 1, 7, Ts(3), Ts(4), 1},
new object[] {6, 6, 2, 7, 4, Ts(5), Ts(6), 2}
};
ExecuteUpdate(session, legSql, legArgs);
}
//TODO:atrosin Revise where and how is used the method
public static void LoadHibernateData(ISession session, HandlingEventFactory handlingEventFactory,
IHandlingEventRepository handlingEventRepository)
{
Console.WriteLine("*** Loading Hibernate data ***");
foreach (Location location in SampleLocations.GetAll())
{
session.Save(location);
}
foreach (Voyage voyage in SampleVoyages.GetAll())
{
session.Save(voyage);
}
/*session.Save(SampleVoyages.HONGKONG_TO_NEW_YORK);
session.Save(SampleVoyages.NEW_YORK_TO_DALLAS);
session.Save(SampleVoyages.DALLAS_TO_HELSINKI);
session.Save(SampleVoyages.HELSINKI_TO_HONGKONG);
session.Save(SampleVoyages.DALLAS_TO_HELSINKI_ALT);*/
var routeSpecification = new RouteSpecification(SampleLocations.HONGKONG,
SampleLocations.HELSINKI,
DateUtil.ToDate("2009-03-15"));
var trackingId = new TrackingId("ABC123");
var abc123 = new Cargo(trackingId, routeSpecification);
var itinerary = new Itinerary(
new List<Leg>
{
new Leg(SampleVoyages.HONGKONG_TO_NEW_YORK, SampleLocations.HONGKONG, SampleLocations.NEWYORK,
DateUtil.ToDate("2009-03-02"), DateUtil.ToDate("2009-03-05")),
new Leg(SampleVoyages.NEW_YORK_TO_DALLAS, SampleLocations.NEWYORK, SampleLocations.DALLAS,
DateUtil.ToDate("2009-03-06"), DateUtil.ToDate("2009-03-08")),
new Leg(SampleVoyages.DALLAS_TO_HELSINKI, SampleLocations.DALLAS, SampleLocations.HELSINKI,
DateUtil.ToDate("2009-03-09"), DateUtil.ToDate("2009-03-12"))
});
abc123.AssignToRoute(itinerary);
session.Save(abc123);
HandlingEvent event1 = handlingEventFactory.CreateHandlingEvent(
new DateTime(), DateUtil.ToDate("2009-03-01"), trackingId, null, SampleLocations.HONGKONG.UnLocode,
HandlingType.RECEIVE
);
session.Save(event1);
HandlingEvent event2 = handlingEventFactory.CreateHandlingEvent(
new DateTime(), DateUtil.ToDate("2009-03-02"), trackingId,
SampleVoyages.HONGKONG_TO_NEW_YORK.VoyageNumber, SampleLocations.HONGKONG.UnLocode,
HandlingType.LOAD
);
session.Save(event2);
HandlingEvent event3 = handlingEventFactory.CreateHandlingEvent(
new DateTime(), DateUtil.ToDate("2009-03-05"), trackingId,
SampleVoyages.HONGKONG_TO_NEW_YORK.VoyageNumber, SampleLocations.NEWYORK.UnLocode,
HandlingType.UNLOAD
);
session.Save(event3);
HandlingHistory handlingHistory = handlingEventRepository.LookupHandlingHistoryOfCargo(trackingId);
abc123.DeriveDeliveryProgress(handlingHistory);
session.Update(abc123);
// Cargo JKL567
var routeSpecification1 = new RouteSpecification(SampleLocations.HANGZOU,
SampleLocations.STOCKHOLM,
DateUtil.ToDate("2009-03-18"));
var trackingId1 = new TrackingId("JKL567");
var jkl567 = new Cargo(trackingId1, routeSpecification1);
var itinerary1 = new Itinerary(new List<Leg>
{
new Leg(SampleVoyages.HONGKONG_TO_NEW_YORK,
SampleLocations.HANGZOU, SampleLocations.NEWYORK,
DateUtil.ToDate("2009-03-03"),
DateUtil.ToDate("2009-03-05")),
new Leg(SampleVoyages.NEW_YORK_TO_DALLAS,
SampleLocations.NEWYORK, SampleLocations.DALLAS,
DateUtil.ToDate("2009-03-06"),
DateUtil.ToDate("2009-03-08")),
new Leg(SampleVoyages.DALLAS_TO_HELSINKI,
SampleLocations.DALLAS, SampleLocations.STOCKHOLM,
DateUtil.ToDate("2009-03-09"),
DateUtil.ToDate("2009-03-11"))
});
jkl567.AssignToRoute(itinerary1);
session.Save(jkl567);
HandlingEvent event21 = handlingEventFactory.CreateHandlingEvent(
new DateTime(), DateUtil.ToDate("2009-03-01"), trackingId1, null, SampleLocations.HANGZOU.UnLocode,
HandlingType.RECEIVE);
session.Save(event21);
HandlingEvent event22 = handlingEventFactory.CreateHandlingEvent(
new DateTime(), DateUtil.ToDate("2009-03-03"), trackingId1,
SampleVoyages.HONGKONG_TO_NEW_YORK.VoyageNumber, SampleLocations.HANGZOU.UnLocode,
HandlingType.LOAD
);
session.Save(event22);
HandlingEvent event23 = handlingEventFactory.CreateHandlingEvent(
new DateTime(), DateUtil.ToDate("2009-03-05"), trackingId1,
SampleVoyages.HONGKONG_TO_NEW_YORK.VoyageNumber, SampleLocations.NEWYORK.UnLocode,
HandlingType.UNLOAD
);
session.Save(event23);
HandlingEvent event24 = handlingEventFactory.CreateHandlingEvent(
new DateTime(), DateUtil.ToDate("2009-03-06"), trackingId1,
SampleVoyages.HONGKONG_TO_NEW_YORK.VoyageNumber, SampleLocations.NEWYORK.UnLocode,
HandlingType.LOAD
);
session.Save(event24);
HandlingHistory handlingHistory1 = handlingEventRepository.LookupHandlingHistoryOfCargo(trackingId1);
jkl567.DeriveDeliveryProgress(handlingHistory1);
session.Update(jkl567);
}
private static DateTime Ts(int hours)
{
return BaseTime.AddHours(hours);
}
public static void LoadTestSampleData()
{
using (ITransaction transaction = UnitOfWork.CurrentSession.BeginTransaction())
{
ISession session = UnitOfWork.CurrentSession;
LoadLocationData(session);
LoadCarrierMovementData(session);
LoadCargoData(session);
LoadItineraryData(session);
LoadHandlingEventData(session);
transaction.Commit();
}
}
public static void LoadSampleData()
{
using (ITransaction transaction = UnitOfWork.CurrentSession.BeginTransaction())
{
LoadHibernateData(UnitOfWork.CurrentSession,
new HandlingEventFactory(new CargoRepositoryHibernate(),
new VoyageRepositoryHibernate(),
new LocationRepositoryHibernate()),
new HandlingEventRepositoryHibernate());
transaction.Commit();
}
}
private static void ExecuteUpdate(ISession session, string sql, object[][] dataTable)
{
for (int i = 0; i < dataTable.GetLength(0); i++)
{
IQuery query = session.CreateSQLQuery(sql);
for (int j = 0; j < dataTable[i].GetLength(0); j++)
{
object objValue = dataTable[i][j];
if (objValue == null)
{
//Workaround: cant set NULL value for int type
query.SetBinary(j, null);
}
else
{
query.SetParameter(j, objValue);
}
}
query.ExecuteUpdate();
}
}
public static DateTime Offset(int hours)
{
return Ts(hours);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using UtilitiesNameSpace;
namespace DHS
{
public static class Eligiblity_Errors
{
public static string RequiredPayer_Error = "This field is required.";
public static string RequiredNationalId_Error = "National Identity is Required";
public static string InvalidNationalId_Error = "Invalid National Identity";
public static string RequiredSpeciality_Error = "Speciality is Required";
public static string RequiredSubSpeciality_Error = "Sub Speciality is Required";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void Main()
{
List<string> theWholeText = new List<string>();
string entries = Console.ReadLine();
while (entries != "END")
{
theWholeText.Add(entries);
entries = Console.ReadLine();
}
int longestLenght = 0;
for (int i = 0; i < theWholeText.Count; i++)
{
if (theWholeText[i].Length > longestLenght)
longestLenght = theWholeText[i].Length;
}
for (int i = 0; i < theWholeText.Count; i++)
{
if (theWholeText[i].Length < longestLenght)
{
theWholeText[i] = string.Format("{0}{1}", theWholeText[i],
(new string(' ', longestLenght - theWholeText[i].Length)));
}
}
char[,] matrix = new char[theWholeText.Count, theWholeText[0].Length];
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = theWholeText[i].ToUpper()[j];
}
}
List<string> possitionsOfX = new List<string>();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < matrix.GetLength(0) - 2; i++)
{
for (int j = 0; j < matrix.GetLength(1) - 2; j++)
{
bool possibleStartForX = (matrix[i + 1, j + 1].CompareTo(matrix[i, j]) == 0 && matrix[i + 1, j + 1].CompareTo(matrix[i, j + 2]) == 0);
if(!possibleStartForX)
{
continue;
}
else
{
string topSide = string.Format("{0}{1}{2}", matrix[i, j], matrix[i + 1, j + 1], matrix[i, j + 2]);
string leftSide = string.Format("{0}{1}{2}", matrix[i, j], matrix[i + 1, j + 1], matrix[i + 2, j]);
string bottomSide = string.Format("{0}{1}{2}", matrix[i + 2, j], matrix[i + 1, j + 1], matrix[i + 2, j + 2]);
string rightSide = string.Format("{0}{1}{2}", matrix[i, j + 2], matrix[i + 1, j + 1], matrix[i + 2, j + 2]);
if(string.Compare(topSide, leftSide, StringComparison.Ordinal) == 0 && string.Compare(topSide, bottomSide, StringComparison.Ordinal) == 0 && string.Compare(topSide, rightSide, StringComparison.Ordinal) == 0)
{
possitionsOfX.Add(string.Format("{0} {1}", i, j));
possitionsOfX.Add(string.Format("{0} {1}", i, j + 2));
possitionsOfX.Add(string.Format("{0} {1}", i + 1, j + 1));
possitionsOfX.Add(string.Format("{0} {1}", i + 2, j));
possitionsOfX.Add(string.Format("{0} {1}", i + 2, j + 2));
}
}
}
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = theWholeText[i][j];
}
}
for (int i = 0; i < possitionsOfX.Count; i++)
{
int row = int.Parse(possitionsOfX[i].Split(' ')[0]);
int col = int.Parse(possitionsOfX[i].Split(' ')[1]);
matrix[row, col] = ' ';
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
if(!char.IsWhiteSpace(matrix[i, j]))
{
builder.Append(matrix[i, j]);
}
}
if (i != matrix.GetLength(0) - 1)
builder.Append('\n');
}
Console.WriteLine(builder);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireController : MonoBehaviour {
public bool isGravityReversed = false;
public float lifeTime = 15.0f;
public float speed = 2.0f;
private Rigidbody rb;
private void Start()
{
//lifetime timer
StartCoroutine(startLifeTime());
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if (isGravityReversed)
{
rb.AddForce(Vector3.up * speed * (-1));
}
else
{
rb.AddForce(Vector3.up * speed * (1));
}
}
private void OnTriggerEnter(Collider coll)
{
//Hit by GEB
if (coll.gameObject.tag == "GEB")
{
Debug.Log("Fire hits GEB!!!!");
if (isGravityReversed == false)
{
isGravityReversed = true;
}
else
{
isGravityReversed = false;
}
}
}
IEnumerator startLifeTime()
{
yield return (new WaitForSeconds(lifeTime));
if (this.gameObject != null)
{
Destroy(gameObject);
}
}
}
|
using System;
namespace AsyncProgramming
{
public class Toast
{
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SchoolDiary.Data;
using SchoolDiary.Data.Entities;
using SchoolDiary.Models;
namespace SchoolDiary.Controllers
{
[ApiController]
[Route("[controller]")]
public class GradesController : ControllerBase
{
private readonly SchoolDiaryDbContext _dataContext;
private readonly IMapper _mapper;
public GradesController(SchoolDiaryDbContext dataContext, IMapper mapper)
{
_dataContext = dataContext;
_mapper = mapper;
}
[HttpGet]
public async Task<IEnumerable<GradeMinDto>> GetAllAsync(CancellationToken cancellationToken = default)
{
var grades = await _dataContext.Grades.ToListAsync(cancellationToken);
return grades.Select(grade => _mapper.Map<GradeMinDto>(grade));
}
[HttpPost]
public async Task PostAsync(GradeDto gradeDto, CancellationToken cancellationToken = default)
{
var grade = new Grade
{
Value = gradeDto.Value,
Student = gradeDto.StudentId != null
? await _dataContext.Students.SingleAsync(student => student.Id == gradeDto.StudentId,
cancellationToken)
: null,
Subject = gradeDto.SubjectId != null
? await _dataContext.Subjects.SingleAsync(subject => subject.Id == gradeDto.SubjectId,
cancellationToken)
: null,
Teacher = gradeDto.TeacherId != null
? await _dataContext.Teachers.SingleAsync(teacher => teacher.Id == gradeDto.TeacherId,
cancellationToken)
: null
};
await _dataContext.Grades.AddAsync(grade, cancellationToken);
await _dataContext.SaveChangesAsync(cancellationToken);
}
[HttpGet("{id}")]
public async Task<GradeDto> GetAsync(int id, CancellationToken cancellationToken = default)
{
return _mapper.Map<GradeDto>(
await _dataContext.Grades
.Include(grade => grade.Student)
.Include(grade => grade.Teacher)
.Include(grade => grade.Subject)
.SingleAsync(grade => grade.Id == id, cancellationToken)
);
}
[HttpPut("{id}")]
public async Task PutAsync(int id, GradeDto gradeDto, CancellationToken cancellationToken = default)
{
var gradeToUpdate = await _dataContext.Grades
.Include(grade => grade.Student)
.Include(grade => grade.Teacher)
.Include(grade => grade.Subject)
.SingleAsync(grade => grade.Id == id, cancellationToken);
gradeToUpdate.Value = gradeDto.Value;
gradeToUpdate.Student = gradeDto.StudentId != null
? await _dataContext.Students.SingleAsync(student => student.Id == gradeDto.StudentId,
cancellationToken)
: null;
gradeToUpdate.Subject = gradeDto.SubjectId != null
? await _dataContext.Subjects.SingleAsync(subject => subject.Id == gradeDto.SubjectId,
cancellationToken)
: null;
gradeToUpdate.Teacher = gradeDto.TeacherId != null
? await _dataContext.Teachers.SingleAsync(teacher => teacher.Id == gradeDto.TeacherId,
cancellationToken)
: null;
await _dataContext.SaveChangesAsync(cancellationToken);
}
[HttpDelete("{id}")]
public async Task DeleteAsync(int id, CancellationToken cancellationToken = default)
{
_dataContext.Grades.Remove(
await _dataContext.Grades.SingleAsync(grade => grade.Id == id, cancellationToken)
);
await _dataContext.SaveChangesAsync(cancellationToken);
}
}
} |
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using Xamarin.Forms;
namespace Liddup.Controls
{
public class SegmentedTabControl : StackLayout
{
public static readonly BindableProperty SelectedSegmentProperty = BindableProperty.Create(nameof(SelectedSegment), typeof(int), typeof(SegmentedTabControl), 0, BindingMode.TwoWay, propertyChanged: SelectedSegmentChanged);
public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(SegmentedTabControl), null, propertyChanged: (bo, o, n) => ((SegmentedTabControl)bo).OnCommandChanged());
public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create(nameof(CommandParameter), typeof(object), typeof(SegmentedTabControl), null, propertyChanged: (bindable, oldvalue, newvalue) => ((SegmentedTabControl)bindable).CommandCanExecuteChanged(bindable, EventArgs.Empty));
private static void TintColorChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (SegmentedTabControl)bindable;
control.BackgroundColor = (Color)newValue;
}
public int SelectedSegment
{
get { return (int)GetValue(SelectedSegmentProperty); }
set { SetValue(SelectedSegmentProperty, value); }
}
private static void SelectedSegmentChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (SegmentedTabControl)bindable;
var selection = (int)newValue;
control.UpdateSelectedItem(selection);
}
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
protected override void OnPropertyChanging([CallerMemberName] string propertyName = null)
{
if (propertyName == CommandProperty.PropertyName)
{
ICommand cmd = Command;
if (cmd != null)
cmd.CanExecuteChanged -= CommandCanExecuteChanged;
}
base.OnPropertyChanging(propertyName);
}
void CommandCanExecuteChanged(object sender, EventArgs eventArgs)
{
ICommand cmd = Command;
if (cmd != null)
IsVisible = cmd.CanExecute(CommandParameter);
}
void OnCommandChanged()
{
if (Command != null)
{
Command.CanExecuteChanged += CommandCanExecuteChanged;
CommandCanExecuteChanged(this, EventArgs.Empty);
}
else
IsVisible = true;
}
public event EventHandler<int> ItemTapped = (e, a) => { };
private void UpdateSelectedItem(int index)
{
for (var i = 0; i < Children.Count(); i++)
if (Children[i] is MusicProviderTab tab)
tab.IsActive = false;
if (index < Children.Count() && index >= 0)
{
if (Children[index] is MusicProviderTab selectedTab)
selectedTab.IsActive = true;
ItemTapped(this, index);
CommandParameter = index;
Command?.Execute(CommandParameter);
}
else
SelectedSegment = -1;
}
private void ItemTappedCommand(int index)
{
SelectedSegment = index;
}
protected override void OnChildAdded(Element child)
{
base.OnChildAdded(child);
var currentCount = Children.Count() - 1;
if (child is MusicProviderTab tab && currentCount >= 0)
{
tab.GestureRecognizers.Add(new TapGestureRecognizer()
{
Command = new Command<int>(ItemTappedCommand),
CommandParameter = currentCount
});
if (currentCount == SelectedSegment)
tab.IsActive = true;
}
}
public SegmentedTabControl()
{
}
}
}
|
//
// Copyright 2020 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using Carbonfrost.Commons.PropertyTrees;
using Carbonfrost.Commons.Spec;
namespace Carbonfrost.UnitTests.PropertyTrees {
public class ValueSerializerTests : TestClass {
[Fact]
public void FromName_should_get_hex() {
Assert.Same(ValueSerializer.Base16, ValueSerializer.FromName("hex"));
}
[Theory]
[InlineData("base16")]
[InlineData("base64")]
[InlineData("invalid")]
[InlineData("percentage")]
[InlineData("percentageRange")]
[InlineData("timeout")]
[InlineData("default")]
public void FromName_should_get_builtin_serializers(string name) {
Assert.NotNull(ValueSerializer.FromName(name));
}
public void ConvertFromString_should_throw_InvalidOperationException_by_default() {
var subject = new DefaultValueSerializer();
Assert.Throws<InvalidOperationException>(
() => subject.ConvertFromString("-", typeof(object), null)
);
}
public void ConvertToString_should_throw_InvalidOperationException_by_default() {
var subject = new DefaultValueSerializer();
Assert.Throws<InvalidOperationException>(
() => subject.ConvertToString("-", null)
);
}
class DefaultValueSerializer : ValueSerializer {}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace Microsoft.EntityFrameworkCore.Metadata
{
/// <summary>
/// Represents a navigation property which can be used to navigate a relationship.
/// </summary>
public interface IReadOnlyNavigationBase : IReadOnlyPropertyBase
{
/// <summary>
/// Gets the entity type that this navigation property belongs to.
/// </summary>
IReadOnlyEntityType DeclaringEntityType { get; }
/// <summary>
/// Gets the entity type that this navigation property will hold an instance(s) of.
/// </summary>
IReadOnlyEntityType TargetEntityType { get; }
/// <summary>
/// Gets the inverse navigation.
/// </summary>
IReadOnlyNavigationBase? Inverse { get; }
/// <summary>
/// Gets a value indicating whether the navigation property is a collection property.
/// </summary>
bool IsCollection { get; }
/// <summary>
/// Gets a value indicating whether this navigation should be eager loaded by default.
/// </summary>
bool IsEagerLoaded
=> (bool?)this[CoreAnnotationNames.EagerLoaded] ?? false;
}
}
|
using System;
namespace App1.Services
{
public interface AudioPlayer
{
void PlayAudio();
void StopAudio();
void PauseAudio();
string AudioFileName { get; set; }
string AudioFilePath { get; set; }
double Duration { get; }
double CurrentPosition { get; }
bool IsPlaying { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvvmTest.HtmlAgility
{
public enum UrlEnum
{
CNBLOGS = 1,
OSCHINA = 2,
CSDN = 3,
QIUBAI = 4
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief 2D描画。サイズ。
*/
/** Rect2D
*/
namespace NRender2D
{
/** Size2D
*/
public struct Size2D<Type>
{
/** wh
*/
public Type w;
public Type h;
/** constructor
*/
public Size2D(Type a_w,Type a_h)
{
this.w = a_w;
this.h = a_h;
}
/** Set
*/
public void Set(Type a_w,Type a_h)
{
this.w = a_w;
this.h = a_h;
}
}
}
|
//
// commercio.sdk - Sdk for Commercio Network
//
// Riccardo Costacurta
// Dec. 30, 2019
// BlockIt s.r.l.
//
/// Allows to easily perform signature-related operations.
//
using System;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;
using commercio.sacco.lib;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
namespace commercio.sdk
{
public class SignHelper
{
#region Properties
#endregion
#region Constructors
#endregion
#region Public Methods
/// Takes the given [data], converts it to an alphabetically sorted
/// JSON object and signs its content using the given [wallet].
public static byte[] signSorted(Object data, Wallet wallet)
{
//Dictionary<String, Object> sorted = null;
//if (data is Dictionary<String, Object>)
//{
// sorted = MapSorter.sort((Dictionary<String, Object>)data);
//}
//String jsonData = JsonConvert.SerializeObject(sorted);
// Encode the sorted JSON to a string
String jsonData = JsonConvert.SerializeObject(data);
byte[] utf8Bytes = Encoding.UTF8.GetBytes(jsonData);
//// *** Create a Sha256 of the message - Method Microsoft
// SHA256 sha256Hash = SHA256.Create();
// byte[] hashBytes = sha256Hash.ComputeHash(utf8Bytes);
// *** Create a Sha256 of the message - Method BouncyCastle
Sha256Digest sha256 = new Sha256Digest();
sha256.BlockUpdate(utf8Bytes, 0, utf8Bytes.Length);
byte[] hashBytes = new byte[sha256.GetDigestSize()];
sha256.DoFinal(hashBytes, 0);
// Sign and return the message
return wallet.sign(hashBytes);
}
/// Takes [senderDid], [pairwiseDid], [timestamp] and:
/// 1. Concatenate senderDid, pairwiseDid and timestamp as payload
/// 2. Returns the RSA PKCS1v15 (the SHA256 digest is calculated inside the
/// signer) and sign using the [rsaPrivateKey]
public static byte[] signPowerUpSignature(String senderDid, String pairwiseDid, String timestamp, RSAPrivateKey rsaPrivateKey)
{
String concat = senderDid + pairwiseDid + timestamp;
ISigner sig = SignerUtilities.GetSigner("SHA256WithRSA");
// Populate key
sig.Init(true, rsaPrivateKey.secretKey);
// Get the bytes to be signed from the string
byte[] buffer = Encoding.UTF8.GetBytes(concat);
// Calc the signature
sig.BlockUpdate(buffer, 0, buffer.Length);
byte[] signature = sig.GenerateSignature();
return signature;
}
#endregion
#region Helpers
#endregion
}
}
|
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
namespace Hompus.VideoInputDevices
{
[ComImport, Guid("29840822-5B84-11D0-BD3B-00A0C911CE86"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface ICreateDevEnum
{
[PreserveSig]
int CreateClassEnumerator([In] ref Guid deviceClass, [Out] out IEnumMoniker enumMoniker, [In] int flags);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kowalski.BusinessLayer
{
public static class Messages
{
public const string NotUnderstood = "Mi dispiace, non ho capito di cosa hai bisogno. Hai detto '{0}'.";
public const string NotFound = "Mi dispiace, non ho trovato nessuna informazione utile su '{0}'.";
public const string Time = "Sono le ore {0}.";
public const string TodayDate = "Oggi è {0}.";
public const string TomorrowDate = "Domani sarà {0}.";
public const string WeatherSingular = "A {0} oggi c'è {1}, con una temperatura di {2} gradi.";
public const string WeatherPlural = "A {0} oggi ci sono {1}, con una temperatura di {2} gradi.";
}
} |
using FatCat.Nes.OpCodes.AddressingModes;
namespace FatCat.Nes.OpCodes.SettingFlags
{
public class SettingCarryFlag : SettingFlag
{
public override string Name => "SEC";
protected override CpuFlag Flag => CpuFlag.CarryBit;
public SettingCarryFlag(ICpu cpu, IAddressMode addressMode) : base(cpu, addressMode) { }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nim
{
public abstract class Player
{
public abstract int[] GetMove();
public abstract string GetName();
}
}
|
using System;
namespace d02_statements
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Demo Day 2");
Console.WriteLine("==========");
//demoIF();
//demoIF2();
//demoIF3();
//demoSwitch();
DemoLoop demo = new DemoLoop();
//demo.testFOR();
//demo.testWHILE();
demo.testFOREACH();
}
static void demoIF()
{
//kiem tra 3 canh a, b, c co phai la 3 canh hop le cua 1 tam giac ko ?
Console.Write("nhap canh a: ");
int a = int.Parse(Console.ReadLine());
Console.Write("nhap canh b: ");
int b = int.Parse(Console.ReadLine());
Console.Write("nhap canh c: ");
int c = int.Parse(Console.ReadLine());
if (a + b <= c || a + c <= b || b + c <= a)
{
Console.WriteLine("Cac canh a, b, c ko du dieu kien de tao 1 tam giac");
}
else
{
Console.WriteLine("Day la 3 canh cua 1 tam giac");
}
}
static void demoIF2()
{
//kiem tra 3 canh a, b, c co phai la 3 canh hop le cua 1 tam giac ko ?
Console.Write("nhap canh a: ");
int a = int.Parse(Console.ReadLine());
Console.Write("nhap canh b: ");
int b = int.Parse(Console.ReadLine());
Console.Write("nhap canh c: ");
int c = int.Parse(Console.ReadLine());
if (a + b <= c || a + c <= b || b + c <= a)
{
Console.WriteLine("Cac canh a, b, c ko du dieu kien de tao 1 tam giac");
}
else if (a == b && b == c)
{
Console.WriteLine("Day la tam giac deu");
}
else if (a == b || a == c || b == c)
{
Console.WriteLine("Day la tam giac can");
}
else
{
Console.WriteLine("Day la tam giac");
}
}
static void demoIF3()
{
//kiem tra 1 thang bat ky trong nam co toi da bn ngay
Console.Write("Nhap thang can kiem tra [1-12]: ");
int mm = int.Parse(Console.ReadLine());
int dd = 0;
if (mm == 1 || mm == 3 || mm == 5 || mm == 7 || mm == 8 || mm == 10 || mm == 12)
{
dd = 31;
}
else if (mm == 4 || mm == 6 || mm == 9 || mm == 11)
{
dd = 30;
}
else if (mm == 2)
{
Console.Write("Nhap nam: ");
int yy = int.Parse(Console.ReadLine().Trim());
//kiem tra nam nhuan
//if(isLeapYear(yy))
//{
// dd = 29;
//}
//else
//{
// dd = 28;
//}
dd = isLeapYear(yy) ? 29 : 28;
}
if (dd == 0)
{
Console.WriteLine("Thang {0} la thang hop le !!!", mm);
}
else
{
Console.WriteLine("Thang {0} co {1} ngay !!!", mm, dd);
}
}
private static bool isLeapYear(int yy)
{
//if( (yy%400==0) || (yy%4==0 && yy%100!=0))
//{
// return true;
//}
//return false;
return (yy % 4 == 0 && yy % 100 != 0) || (yy % 400 == 0);
}
static void demoSwitch()
{
Console.Write("Nhap thang can kiem tra [1-12]: ");
int mm = int.Parse(Console.ReadLine());
int dd = 0;
switch (mm)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
dd = 31;
break;
case 4:
case 6:
case 9:
case 11:
dd = 30;
break;
case 2:
Console.Write("Nhap nam: ");
int yy = int.Parse(Console.ReadLine().Trim());
dd = isLeapYear(yy) ? 29 : 28;
break;
default:
dd = 0;
break;
}
if (dd == 0)
{
Console.WriteLine("Thang {0} la thang hop le !!!", mm);
}
else
{
Console.WriteLine("Thang {0} co {1} ngay !!!", mm, dd);
}
}
}
}
|
using UnityEngine;
using UnityEngineExtended;
using System.Collections.Generic;
namespace AntColony
{
/// <summary>
/// Script handles collisions between this object and objects with complex colliders. Script holds references to all contacted
/// colliders belong to a complex collider. Script will notify handler script only when a collision with a unique complex
/// collider occurs.
/// Collisions with non-complex colliders are assumed to be unique.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(IComplexCollidable))]
public class ComplexCollisionHandler : MonoBehaviour
{
private IComplexCollidable handler; // Class that is interested in unique collisions
private Dictionary<GameObject, HashSet<Collider>> triggeredColliders;
void Awake()
{
handler = GetComponent<IComplexCollidable>();
triggeredColliders = new Dictionary<GameObject, HashSet<Collider>>();
}
bool Register(Collider other)
{
// Check if object contains complex collider
GameObject complexCollider = other.GetObjectWithTagInParent("ComplexCollider");
if (complexCollider != null)
{
// Check if the contacted collider is from complex collider that has already been contacted
bool unique = !triggeredColliders.ContainsKey(complexCollider); // unique if NOT contained in collider dict
if (unique)
{
// Create new dict entry for complex collider and add collider to values set
triggeredColliders.Add(complexCollider, new HashSet<Collider>() { other });
// First time contacting a collider attached to complex collider parent, collision is unique
return true;
}
else
{
// Already present in dict: add the collider to values set
triggeredColliders[complexCollider].Add(other);
// Collision with complex collider that is already in dictionary, collision is not unique
return false;
}
}
// All non-complex collider collisions are assumed to be unique
else return true;
}
bool Deregister(Collider other)
{
// Check if object contains complex collider
GameObject complexCollider = other.GetObjectWithTagInParent("ComplexCollider");
if (complexCollider != null)
{
// No idea how it couldn't be in the dictionary... but throws exceptions without this check
if (triggeredColliders.ContainsKey(complexCollider))
{
// Remove exited collider from dict values set
triggeredColliders[complexCollider].Remove(other);
// If set is empty
if (triggeredColliders[complexCollider].Count == 0)
{
// Remove entry from dict
triggeredColliders.Remove(complexCollider);
// Complex collider not resgistered in set of triggered colliders, collision exit was unique
return true;
}
// Complex collider already registered in set of triggered colliders, collision exit was not unique
else return false;
}
// Complex collider was not in triggered colliders dictionary (no idea how); assume collision exit is unique
else return true; // TODO: Should this be false?
}
// All non-complex collider collision exits are assumed to be unique
else return true;
}
void OnCollisionEnter(Collision collision)
{
bool unique = Register(collision.collider);
if (unique)
handler.OnUniqueCollisionEnter(collision);
}
void OnCollisionExit(Collision collision)
{
bool unique = Register(collision.collider);
if (unique)
handler.OnUniqueCollisionExit(collision);
}
void OnTriggerEnter(Collider other)
{
bool unique = Register(other);
if (unique)
handler.OnUniqueTriggerEnter(other);
}
void OnTriggerExit(Collider other)
{
bool unique = Deregister(other);
if (unique)
handler.OnUniqueTriggerExit(other);
}
}
} |
// AForge Neural Net Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2007-2012
// contacts@aforgenet.com
//
namespace Accord.Neuro.Learning
{
using System;
using System.Diagnostics;
using Accord;
using Accord.Genetic;
using Accord.Math.Random;
/// <summary>
/// Neural networks' evolutionary learning algorithm, which is based on Genetic Algorithms.
/// </summary>
///
/// <remarks><para>The class implements supervised neural network's learning algorithm,
/// which is based on Genetic Algorithms. For the given neural network, it create a population
/// of <see cref="DoubleArrayChromosome"/> chromosomes, which represent neural network's
/// weights. Then, during the learning process, the genetic population evolves and weights, which
/// are represented by the best chromosome, are set to the source neural network.</para>
///
/// <para>See <see cref="Population"/> class for additional information about genetic population
/// and evolutionary based search.</para>
///
/// <para>Sample usage (training network to calculate XOR function):</para>
/// <code>
/// // initialize input and output values
/// double[][] input = new double[4][] {
/// new double[] {-1, 1}, new double[] {-1, 1},
/// new double[] { 1, -1}, new double[] { 1, 1}
/// };
/// double[][] output = new double[4][] {
/// new double[] {-1}, new double[] { 1},
/// new double[] { 1}, new double[] {-1}
/// };
/// // create neural network
/// ActivationNetwork network = new ActivationNetwork(
/// BipolarSigmoidFunction( 2 ),
/// 2, // two inputs in the network
/// 2, // two neurons in the first layer
/// 1 ); // one neuron in the second layer
/// // create teacher
/// EvolutionaryLearning teacher = new EvolutionaryLearning( network,
/// 100 ); // number of chromosomes in genetic population
/// // loop
/// while ( !needToStop )
/// {
/// // run epoch of learning procedure
/// double error = teacher.RunEpoch( input, output );
/// // check error value to see if we need to stop
/// // ...
/// }
///
/// </code>
/// </remarks>
///
/// <seealso cref="BackPropagationLearning"/>
///
public class EvolutionaryLearning : ISupervisedLearning
{
// designed network for training which have to matach inputs and outputs
private ActivationNetwork network;
// number of weight in the network to train
private int numberOfNetworksWeights;
// genetic population
private Population population;
// size of population
private int populationSize;
// generator for newly generated neurons
private IRandomNumberGenerator chromosomeGenerator;
// mutation generators
private IRandomNumberGenerator mutationMultiplierGenerator;
private IRandomNumberGenerator mutationAdditionGenerator;
// selection method for chromosomes in population
private ISelectionMethod selectionMethod;
// crossover probability in genetic population
private double crossOverRate;
// mutation probability in genetic population
private double mutationRate;
// probability to add newly generated chromosome to population
private double randomSelectionRate;
/// <summary>
/// Initializes a new instance of the <see cref="EvolutionaryLearning"/> class.
/// </summary>
///
/// <param name="activationNetwork">Activation network to be trained.</param>
/// <param name="populationSize">Size of genetic population.</param>
/// <param name="chromosomeGenerator">Random numbers generator used for initialization of genetic
/// population representing neural network's weights and thresholds (see <see cref="DoubleArrayChromosome.chromosomeGenerator"/>).</param>
/// <param name="mutationMultiplierGenerator">Random numbers generator used to generate random
/// factors for multiplication of network's weights and thresholds during genetic mutation
/// (ses <see cref="DoubleArrayChromosome.mutationMultiplierGenerator"/>.)</param>
/// <param name="mutationAdditionGenerator">Random numbers generator used to generate random
/// values added to neural network's weights and thresholds during genetic mutation
/// (see <see cref="DoubleArrayChromosome.mutationAdditionGenerator"/>).</param>
/// <param name="selectionMethod">Method of selection best chromosomes in genetic population.</param>
/// <param name="crossOverRate">Crossover rate in genetic population (see
/// <see cref="Population.CrossoverRate"/>).</param>
/// <param name="mutationRate">Mutation rate in genetic population (see
/// <see cref="Population.MutationRate"/>).</param>
/// <param name="randomSelectionRate">Rate of injection of random chromosomes during selection
/// in genetic population (see <see cref="Population.RandomSelectionPortion"/>).</param>
///
public EvolutionaryLearning(ActivationNetwork activationNetwork, int populationSize,
IRandomNumberGenerator chromosomeGenerator,
IRandomNumberGenerator mutationMultiplierGenerator,
IRandomNumberGenerator mutationAdditionGenerator,
ISelectionMethod selectionMethod,
double crossOverRate, double mutationRate, double randomSelectionRate)
{
// Check of assumptions during debugging only
Debug.Assert(activationNetwork != null);
Debug.Assert(populationSize > 0);
Debug.Assert(chromosomeGenerator != null);
Debug.Assert(mutationMultiplierGenerator != null);
Debug.Assert(mutationAdditionGenerator != null);
Debug.Assert(selectionMethod != null);
Debug.Assert(crossOverRate >= 0.0 && crossOverRate <= 1.0);
Debug.Assert(mutationRate >= 0.0 && crossOverRate <= 1.0);
Debug.Assert(randomSelectionRate >= 0.0 && randomSelectionRate <= 1.0);
// networks's parameters
this.network = activationNetwork;
this.numberOfNetworksWeights = CalculateNetworkSize(activationNetwork);
// population parameters
this.populationSize = populationSize;
this.chromosomeGenerator = chromosomeGenerator;
this.mutationMultiplierGenerator = mutationMultiplierGenerator;
this.mutationAdditionGenerator = mutationAdditionGenerator;
this.selectionMethod = selectionMethod;
this.crossOverRate = crossOverRate;
this.mutationRate = mutationRate;
this.randomSelectionRate = randomSelectionRate;
}
/// <summary>
/// Initializes a new instance of the <see cref="EvolutionaryLearning"/> class.
/// </summary>
///
/// <param name="activationNetwork">Activation network to be trained.</param>
/// <param name="populationSize">Size of genetic population.</param>
///
/// <remarks><para>This version of constructor is used to create genetic population
/// for searching optimal neural network's weight using default set of parameters, which are:
/// <list type="bullet">
/// <item>Selection method - elite;</item>
/// <item>Crossover rate - 0.75;</item>
/// <item>Mutation rate - 0.25;</item>
/// <item>Rate of injection of random chromosomes during selection - 0.20;</item>
/// <item>Random numbers generator for initializing new chromosome -
/// <c>UniformGenerator( new Range( -1, 1 ) )</c>;</item>
/// <item>Random numbers generator used during mutation for genes' multiplication -
/// <c>ExponentialGenerator( 1 )</c>;</item>
/// <item>Random numbers generator used during mutation for adding random value to genes -
/// <c>UniformGenerator( new Range( -0.5f, 0.5f ) )</c>.</item>
/// </list></para>
///
/// <para>In order to have full control over the above default parameters, it is possible to
/// used extended version of constructor, which allows to specify all of the parameters.</para>
/// </remarks>
///
public EvolutionaryLearning(ActivationNetwork activationNetwork, int populationSize)
{
// Check of assumptions during debugging only
Debug.Assert(activationNetwork != null);
Debug.Assert(populationSize > 0);
// networks's parameters
this.network = activationNetwork;
this.numberOfNetworksWeights = CalculateNetworkSize(activationNetwork);
// population parameters
this.populationSize = populationSize;
this.chromosomeGenerator = new UniformGenerator(new Range(-1, 1));
this.mutationMultiplierGenerator = new ExponentialGenerator(1);
this.mutationAdditionGenerator = new UniformGenerator(new Range(-0.5f, 0.5f));
this.selectionMethod = new EliteSelection();
this.crossOverRate = 0.75;
this.mutationRate = 0.25;
this.randomSelectionRate = 0.2;
}
// Create and initialize genetic population
private int CalculateNetworkSize(ActivationNetwork activationNetwork)
{
// caclculate total amount of weight in neural network
int networkSize = 0;
for (int i = 0; i < network.Layers.Length; i++)
{
Layer layer = network.Layers[i];
for (int j = 0; j < layer.Neurons.Length; j++)
{
// sum all weights and threshold
networkSize += layer.Neurons[j].Weights.Length + 1;
}
}
return networkSize;
}
/// <summary>
/// Runs learning iteration.
/// </summary>
///
/// <param name="input">Input vector.</param>
/// <param name="output">Desired output vector.</param>
///
/// <returns>Returns learning error.</returns>
///
/// <remarks><note>The method is not implemented, since evolutionary learning algorithm is global
/// and requires all inputs/outputs in order to run its one epoch. Use <see cref="RunEpoch"/>
/// method instead.</note></remarks>
///
/// <exception cref="NotImplementedException">The method is not implemented by design.</exception>
///
public double Run(double[] input, double[] output)
{
throw new NotImplementedException("The method is not implemented by design.");
}
/// <summary>
/// Runs learning epoch.
/// </summary>
///
/// <param name="input">Array of input vectors.</param>
/// <param name="output">Array of output vectors.</param>
///
/// <returns>Returns summary squared learning error for the entire epoch.</returns>
///
/// <remarks><para><note>While running the neural network's learning process, it is required to
/// pass the same <paramref name="input"/> and <paramref name="output"/> values for each
/// epoch. On the very first run of the method it will initialize evolutionary fitness
/// function with the given input/output. So, changing input/output in middle of the learning
/// process, will break it.</note></para></remarks>
///
public double RunEpoch(double[][] input, double[][] output)
{
Debug.Assert(input.Length > 0);
Debug.Assert(output.Length > 0);
Debug.Assert(input.Length == output.Length);
Debug.Assert(network.InputsCount == input.Length);
// check if it is a first run and create population if so
if (population == null)
{
// sample chromosome
DoubleArrayChromosome chromosomeExample = new DoubleArrayChromosome(
chromosomeGenerator, mutationMultiplierGenerator, mutationAdditionGenerator,
numberOfNetworksWeights);
// create population ...
population = new Population(populationSize, chromosomeExample,
new EvolutionaryFitness(network, input, output), selectionMethod);
// ... and configure it
population.CrossoverRate = crossOverRate;
population.MutationRate = mutationRate;
population.RandomSelectionPortion = randomSelectionRate;
}
// run genetic epoch
population.RunEpoch();
// get best chromosome of the population
DoubleArrayChromosome chromosome = (DoubleArrayChromosome)population.BestChromosome;
double[] chromosomeGenes = chromosome.Value;
// put best chromosome's value into neural network's weights
int v = 0;
for (int i = 0; i < network.Layers.Length; i++)
{
Layer layer = network.Layers[i];
for (int j = 0; j < layer.Neurons.Length; j++)
{
ActivationNeuron neuron = layer.Neurons[j] as ActivationNeuron;
for (int k = 0; k < neuron.Weights.Length; k++)
{
neuron.Weights[k] = chromosomeGenes[v++];
}
neuron.Threshold = chromosomeGenes[v++];
}
}
Debug.Assert(v == numberOfNetworksWeights);
return 1.0 / chromosome.Fitness;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Threading.Tasks;
namespace Hexagon.Data.DataAccess
{
public class DbHelperAsync
{
/// <summary>
/// 连接字符串
/// </summary>
public static string ConnectionString { get; set; }
/// <summary>
/// 数据库类型
/// </summary>
public static DatabaseType DbType { get; set; }
/// <summary>
/// 数据库命名参数符号
/// </summary>
public static string DbParmChar { get; set; }
public DbHelperAsync(string connstring)
{
ConnectionString = connstring;
this.DatabaseTypeEnumParse("System.Data.OracleClient");
DbParmChar = DbFactory.CreateDbParmCharacter();
}
/// <summary>
/// 执行 SQL 语句,并返回受影响的行数。
/// </summary>
/// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="cmdText">存储过程名称或者T-SQL命令行</param>
/// <param name="parameters">执行命令所需的sql语句对应参数</param>
/// <returns></returns>
public static async Task<int> ExecuteNonQuery(CommandType cmdType, string cmdText, params DbParameter[] parameters)
{
int num = 0;
try
{
DbCommand cmd = DbFactory.CreateDbCommand();
using (DbConnection conn = DbFactory.CreateDbConnection(ConnectionString))
{
await PrepareCommand(cmd, conn, null, cmdType, cmdText, parameters);
num = await cmd.ExecuteNonQueryAsync();
cmd.Parameters.Clear();
}
}
catch (Exception ex)
{
num = -1;
}
return num;
}
/// <summary>
/// 执行 SQL 语句,并返回受影响的行数。
/// </summary>
/// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="cmdText">存储过程名称或者T-SQL命令行</param>
/// <returns></returns>
public static async Task<int> ExecuteNonQuery(CommandType cmdType, string cmdText)
{
int num = 0;
try
{
DbCommand cmd = DbFactory.CreateDbCommand();
using (DbConnection conn = DbFactory.CreateDbConnection(ConnectionString))
{
await PrepareCommand(cmd, conn, null, cmdType, cmdText, null);
num = await cmd.ExecuteNonQueryAsync();
cmd.Parameters.Clear();
}
}
catch (Exception ex)
{
num = -1;
//log.Error(ex.Message);
}
return num;
}
/// <summary>
/// 执行 SQL 语句,并返回受影响的行数。
/// </summary>
/// <param name="conn">数据库连接对象</param>
/// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="cmdText">存储过程名称或者T-SQL命令行</param>
/// <param name="parameters">执行命令所需的sql语句对应参数</param>
/// <returns></returns>
public static async Task<int> ExecuteNonQuery(DbConnection connection, CommandType cmdType, string cmdText, params DbParameter[] parameters)
{
int num = 0;
try
{
DbCommand cmd = DbFactory.CreateDbCommand();
await PrepareCommand(cmd, connection, null, cmdType, cmdText, parameters);
num = await cmd.ExecuteNonQueryAsync();
cmd.Parameters.Clear();
}
catch (Exception ex)
{
num = -1;
}
return num;
}
/// <summary>
/// 执行 SQL 语句,并返回受影响的行数。
/// </summary>
/// <param name="isOpenTrans">事务对象</param>
/// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="cmdText">存储过程名称或者T-SQL命令行</param>
/// <returns></returns>
public static async Task<int> ExecuteNonQuery(DbTransaction isOpenTrans, CommandType cmdType, string cmdText)
{
int num = 0;
try
{
DbCommand cmd = DbFactory.CreateDbCommand();
await PrepareCommand(cmd, isOpenTrans.Connection, isOpenTrans, cmdType, cmdText, null);
num = await cmd.ExecuteNonQueryAsync();
cmd.Parameters.Clear();
}
catch (Exception ex)
{
num = -1;
}
return num;
}
/// <summary>
/// 执行 SQL 语句,并返回受影响的行数。
/// </summary>
/// <param name="isOpenTrans">事务对象</param>
/// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="cmdText">存储过程名称或者T-SQL命令行</param>
/// <param name="parameters">执行命令所需的sql语句对应参数</param>
/// <returns></returns>
public static async Task<int> ExecuteNonQuery(DbTransaction isOpenTrans, CommandType cmdType, string cmdText, params DbParameter[] parameters)
{
int num = 0;
try
{
DbCommand cmd = DbFactory.CreateDbCommand();
if (cmdText.Contains("Base_Subsystem_Function"))
{
//子系统功能点
using (DbConnection conn = DbFactory.CreateDbConnection(ConnectionString))
{
await PrepareCommand(cmd, conn, isOpenTrans, cmdType, cmdText, parameters);
num = await cmd.ExecuteNonQueryAsync();
}
}
else
{
if (isOpenTrans == null || isOpenTrans.Connection == null)
{
using (DbConnection conn = DbFactory.CreateDbConnection(ConnectionString))
{
await PrepareCommand(cmd, conn, isOpenTrans, cmdType, cmdText, parameters);
num = await cmd.ExecuteNonQueryAsync();
}
}
else
{
await PrepareCommand(cmd, isOpenTrans.Connection, isOpenTrans, cmdType, cmdText, parameters);
num = await cmd.ExecuteNonQueryAsync();
}
}
cmd.Parameters.Clear();
}
catch (Exception ex)
{
num = -1;
}
return num;
}
/// <summary>
/// 使用提供的参数,执行有结果集返回的数据库操作命令、并返回SqlDataReader对象
/// </summary>
/// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="commandText">存储过程名称或者T-SQL命令行<</param>
/// <param name="parameters">执行命令所需的sql语句对应参数</param>
/// <returns>返回SqlDataReader对象</returns>
public static async Task<DbDataReader> ExecuteReader(CommandType cmdType, string cmdText, params DbParameter[] parameters)
{
DbCommand cmd = DbFactory.CreateDbCommand();
DbConnection conn = DbFactory.CreateDbConnection(ConnectionString);
try
{
await PrepareCommand(cmd, conn, null, cmdType, cmdText, parameters);
DbDataReader rdr = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch (Exception ex)
{
conn.Close();
cmd.Dispose();
throw;
}
}
/// <summary>
///使用提供的参数,执行有结果集返回的数据库操作命令、并返回SqlDataReader对象
/// </summary>
/// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="commandText">存储过程名称或者T-SQL命令行<</param>
/// <returns>返回SqlDataReader对象</returns>
public static async Task<DbDataReader> ExecuteReader(CommandType cmdType, string cmdText)
{
DbCommand cmd = DbFactory.CreateDbCommand();
DbConnection conn = DbFactory.CreateDbConnection(ConnectionString);
try
{
await PrepareCommand(cmd, conn, null, cmdType, cmdText, null);
DbDataReader rdr = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch (Exception ex)
{
conn.Close();
cmd.Dispose();
throw;
}
}
/// <summary>
/// 依靠数据库连接字符串connectionString,
/// 使用所提供参数,执行返回首行首列命令
/// </summary>
/// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="commandText">存储过程名称或者T-SQL命令行</param>
/// <param name="parameters">执行命令所需的sql语句对应参数</param>
/// <returns>返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。</returns>
public static async Task<object> ExecuteScalar(CommandType cmdType, string cmdText, params DbParameter[] parameters)
{
try
{
DbCommand cmd = DbFactory.CreateDbCommand();
using (DbConnection connection = DbFactory.CreateDbConnection(ConnectionString))
{
await PrepareCommand(cmd, connection, null, cmdType, cmdText, parameters);
object val = await cmd.ExecuteScalarAsync();
cmd.Parameters.Clear();
return val;
}
}
catch (Exception ex)
{
throw;
}
}
/// <summary>
/// 为即将执行准备一个命令
/// </summary>
/// <param name="cmd">SqlCommand对象</param>
/// <param name="conn">SqlConnection对象</param>
/// <param name="isOpenTrans">DbTransaction对象</param>
/// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="cmdText">存储过程名称或者T-SQL命令行, e.g. Select * from Products</param>
/// <param name="cmdParms">SqlParameters to use in the command</param>
public static async Task PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction isOpenTrans, CommandType cmdType, string cmdText, DbParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
await conn.OpenAsync();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (isOpenTrans != null)
cmd.Transaction = isOpenTrans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
cmd.Parameters.AddRange(cmdParms);
}
}
/// <summary>
/// 用于数据库类型的字符串枚举转换
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public void DatabaseTypeEnumParse(string value)
{
try
{
switch (value)
{
case "System.Data.SqlClient":
DbType = DatabaseType.SqlServer;
break;
case "System.Data.OracleClient":
DbType = DatabaseType.Oracle;
break;
case "MySql.Data.MySqlClient":
DbType = DatabaseType.MySql;
break;
case "System.Data.OleDb":
DbType = DatabaseType.Access;
break;
case "System.Data.SQLite":
DbType = DatabaseType.SQLite;
break;
default:
break;
}
}
catch
{
throw new Exception("数据库类型\"" + value + "\"错误,请检查!");
}
}
}
}
|
using System.Linq;
namespace BookStore.Core.Domain
{
public class CategoryCrimeDiscount : IDiscount
{
private const decimal _discount = 0.05m;
public Order Apply(Order order) => new Order
{
Books = order.Books.Select(b => new Book
{
BookName = b.BookName,
Category = b.Category,
TotalCost = (b.Category == BookCategory.Crime) ? b.TotalCost - (b.TotalCost * _discount) : b.TotalCost
}).ToList()
};
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
namespace iCopy.Web.Helper
{
public static class Cookie
{
public static void SetCultureInfoCookie(this IResponseCookies cookies, RequestCulture culture)
{
cookies.Delete(Localization.CurrentCultureCookieName);
cookies.Append(Localization.CurrentCultureCookieName, CookieRequestCultureProvider.MakeCookieValue(culture));
}
}
}
|
using System.Linq;
using FluentAssertions;
using Unity.Interception.Serilog.Tests.Support;
using Xunit;
namespace Unity.Interception.Serilog.Tests
{
public class LogWithoutReturnOrParameterTypesTests : TestBase
{
public LogWithoutReturnOrParameterTypesTests()
{
GivenThereExistsAContainer()
.WithConfiguredSerilog()
.WithADummyTypeRegistered();
WhenDummyIsResolvedAnd().DoStuff();
}
[Fact]
public void ThenAnInformationWithExpectedPropertiesShouldBeLogged()
{
var properties = Log.Single().Properties;
properties.Keys.Should().NotContain("Arguments");
properties.Keys.Should().NotContain("Result");
}
}
} |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using test;
namespace WebApi.Controllers
{
public class ReturnData
{
/// <summary>
/// 0:成功,>0失败
/// </summary>
public int status { get; set; }
/// <summary>
/// 提交信息
/// </summary>
public string message { get; set; }
/// <summary>
/// 数据
/// </summary>
public object data { get; set; } = "";
public static ReturnData Success()
{
return new ReturnData()
{
status = 0,
message = "操作成功"
};
}
public static ReturnData Success(string msg, object _content)
{
return new ReturnData()
{
status = 0,
data = _content,
message = msg
};
}
public static ReturnData SuccessDelete()
{
return new ReturnData()
{
status = 0,
message = "删除成功"
};
}
public static ReturnData Error(string msg)
{
return new ReturnData()
{
status = 1,
message = msg
};
}
public static ReturnData Error(int code, string msg)
{
return new ReturnData()
{
status = code,
message = msg
};
}
public static ReturnData Error(string msg, object _content)
{
return new ReturnData()
{
status = 1,
data = _content,
message = msg
};
}
public static ReturnData Error(int code, string msg, object _content)
{
return new ReturnData()
{
status = code,
data = _content,
message = msg
};
}
public static ReturnData Success(string msg)
{
return new ReturnData()
{
status = 0,
message = msg
};
}
public static ReturnData Success(object _content)
{
return new ReturnData()
{
status = 0,
data = _content
};
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ValuesController : ApiController
{
// GET api/values
//public IEnumerable<string> Get()
//{
// return new string[] { "到底", "cc" };
//}
[HttpGet]
public IHttpActionResult ProductByID(int id)
{
List<Product> list = new List<Product>()
{
new Product { Id = 1, Name = "大哥", },
new Product { Id = 2, Name = "二哥" },
new Product { Id = 3, Name = "三哥" }
};
var product = list.FirstOrDefault(b => b.Id == id);
return Ok(list);
}
[HttpPost]
public IHttpActionResult AddProduct([FromBody] Product pars)
{
ISMSService service = new SMSService();
CoreValue value = service.GetVerifyCode("", "", "1");
string name = pars.Name;
return Ok(name);
}
[HttpPost]
public IHttpActionResult bazid(JObject pars)
{
// string ID = pars["ID"].ToString();
// return Ok(ID);
string id = pars["id"].ToString();
string name = pars["name"].ToString();
return Ok(name+":"+id);
}
[HttpPost]
public ReturnData AddProduct_bx([FromBody] Product product)
{
return ReturnData.Success("获取成功", string.Format("获取到的值:id={0},name={1}", product.Id, product.Name));
}
[HttpPost]
public ReturnData Test(JObject pars)
{
string id = pars["id"].ToString();
string name = pars["name"].ToString();
return ReturnData.Success("获取成功", string.Format("获取的参数值:id={0},name={1}", id, name));
}
// GET api/values/5
//public string Getkk(int id)
//{
// return "value";
//}
// POST api/values
[HttpPost]
public string Post([FromBody]string value)
{
return value;
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace AttackDragon.Configurations
{
public partial class Configuration
{
/// <summary>
/// Creates <see cref="Configuration"/> folder if it doesn't exist
/// </summary>
public static void InitializeLocalFolder()
{
if (!Directory.Exists(DirectoryAddress))
{
Directory.CreateDirectory(DirectoryAddress);
}
}
/// <summary>
/// Saves <see cref="Configuration"/> in <see cref="FullPath"/>
/// </summary>
public void SaveSettingsToFile()
{
XmlSerializer xsSubmit = new XmlSerializer(typeof(Configuration));
var xml = string.Empty;
using (var sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, this);
xml = sww.ToString();
}
}
File.WriteAllText(FullPath, xml);
}
/// <summary>
/// Loads <see cref="Configuration"/> from <see cref="FullPath"/> and sets to <see cref="App.Configuration"/>
/// </summary>
public static void LoadSettingsFromFile()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
using (FileStream fileStream = new FileStream(FullPath, FileMode.Open))
{
var stream = new StreamReader(fileStream, Encoding.UTF8);
App.CurrentApp.Configuration = (Configuration)serializer.Deserialize(stream);
}
}
catch
{
App.CurrentApp.Configuration = new Configuration();
App.CurrentApp.Configuration.SaveSettingsToFile();
}
}
}
}
|
using FatCat.Nes.OpCodes.AddressingModes;
namespace FatCat.Nes.OpCodes.Arithmetic
{
public class DecrementXRegister : OpCode
{
public override string Name => "DEX";
public DecrementXRegister(ICpu cpu, IAddressMode addressMode) : base(cpu, addressMode) { }
public override int Execute()
{
cpu.XRegister--;
ApplyFlag(CpuFlag.Zero, cpu.XRegister.IsZero());
ApplyFlag(CpuFlag.Negative, cpu.XRegister.IsNegative());
return 0;
}
}
} |
using Dapper;
using MISA.Core.Entities;
using MISA.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Infrastructure.Repository
{
public class StoreRepository : BaseRepository<Store>, IStoreRepository
{
public IEnumerable<Store> GetStoreFilter(string storeCode, string storeName, string address, string phoneNumber, int? status)
{
string storeNames = "Proc_GetStoreFilter";
if (status == null)
{
status = 2;
}
DynamicParameters dynamicParameters = new DynamicParameters();
dynamicParameters.Add("StoreCode", storeCode);
dynamicParameters.Add("StoreName", storeName);
dynamicParameters.Add("Address", address);
dynamicParameters.Add("PhoneNumber", phoneNumber);
dynamicParameters.Add("Status", status);
var entities = _dbConnection.Query<Store>(storeNames, param: dynamicParameters, commandType: CommandType.StoredProcedure);
return (entities);
}
public IEnumerable<Store> GetStoreByStoreCode(string storeCode)
{
string storeNames = "Proc_GetStoreByStoreCode";
DynamicParameters dynamicParameters = new DynamicParameters();
dynamicParameters.Add("StoreCode", storeCode);
var entities = _dbConnection.Query<Store>(storeNames, param: dynamicParameters, commandType: CommandType.StoredProcedure);
return (entities);
}
public IEnumerable<Store> GetStoreByIndexOffset(int positionStart, int offSet)
{
string storeNames = "Proc_GetStoreByIndexOffset";
DynamicParameters dynamicParameters = new DynamicParameters();
dynamicParameters.Add("positionStart", positionStart);
dynamicParameters.Add("offSet", offSet);
var entities = _dbConnection.Query<Store>(storeNames, param: dynamicParameters, commandType: CommandType.StoredProcedure);
return (entities);
}
public IEnumerable<Store> GetStoreFilterByIndexOffset(int positionStart, int offSet, string storeCode, string storeName, string address, string phoneNumber, int? status)
{
if (status == null)
{
status = 2;
}
string storeNames = "Proc_GetStoreFilterByIndexOffset";
DynamicParameters dynamicParameters = new DynamicParameters();
dynamicParameters.Add("positionStart", positionStart);
dynamicParameters.Add("offSet", offSet);
dynamicParameters.Add("StoreCode", storeCode);
dynamicParameters.Add("StoreName", storeName);
dynamicParameters.Add("Address", address);
dynamicParameters.Add("PhoneNumber", phoneNumber);
dynamicParameters.Add("Status", status);
var entities = _dbConnection.Query<Store>(storeNames, param: dynamicParameters, commandType: CommandType.StoredProcedure);
return (entities);
}
public int GetCountStores()
{
string storeNames = "Proc_GetCountStores";
var count = _dbConnection.ExecuteScalar<int>(storeNames, commandType: CommandType.StoredProcedure);
return count;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AiTracking : MonoBehaviour
{
public static AiTracking instance;
public int range = 0;
public int tag = 0;
public int moveSpeed = 0;
public int bounds = 0;
public int spinSpeed = 0;
public int spinType = 0;
public int route = 0;
public int rangeTotal = 0;
public int tagTotal = 0;
public int moveSpeedTotal = 0;
public int boundsTotal = 0;
public int spinSpeedTotal = 0;
public int spinTypeTotal = 0;
public int routeTotal = 0;
public bool disableRange = false;
public bool disableTag = false;
public bool disableMoveSpeed = false;
public bool disableBounds = false;
public bool disableSpinSpeed = false;
public bool disableSpinType = false;
public bool disableRoute = false;
private void Awake()
{
instance = this;
//DontDestroyOnLoad(gameObject);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(rangeTotal > tagTotal)
{
disableRange = true;
disableTag = false;
}
else if(tagTotal > rangeTotal)
{
disableRange = false;
disableTag = true;
}
if(moveSpeedTotal > routeTotal/2 && moveSpeed != 0)
{
disableMoveSpeed = true;
disableRoute = false;
}
else if(route != 0)
{
disableRoute = true;
disableMoveSpeed = false;
}
if(boundsTotal/2 > spinSpeedTotal && boundsTotal !=0)
{
disableSpinSpeed = false;
disableBounds = true;
}
else if(spinSpeed != 0)
{
disableSpinSpeed = true;
disableBounds = false;
}
if(spinTypeTotal > boundsTotal / 2 && spinType > 0)
{
disableSpinType = true;
}
else
{
disableSpinType = false;
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using MediatR;
using Microsoft.Extensions.Logging;
using Npgsql;
namespace DDDSouthWest.Domain.Features.Public.Page
{
public class GetPage
{
public class Query : IRequest<Response>
{
public string Filename { get; set; }
}
public class Handler : IRequestHandler<Query, Response>
{
private readonly ClientConfigurationOptions _options;
private readonly ILogger _logger;
public Handler(ClientConfigurationOptions options, ILogger<GetPage> logger)
{
_options = options;
_logger = logger;
}
public async Task<Response> Handle(Query message, CancellationToken cancellationToken)
{
_logger.LogInformation("Getting page {filename}", message.Filename);
using (var connection = new NpgsqlConnection(_options.Database.ConnectionString))
{
var response = await connection.QuerySingleOrDefaultAsync<PageDetailModel>(
"SELECT Id, Title, BodyHtml, IsLive, LastModified FROM pages WHERE Filename = @filename AND IsLive = TRUE LIMIT 1",
new
{
filename = message.Filename
});
if (response == null)
{
_logger.LogInformation("Page {filename} not found", message.Filename);
throw new RecordNotFoundException("Page not found");
}
return new Response
{
PageDetail = response
};
}
}
}
public class Response
{
public PageDetailModel PageDetail;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PixelAlign : MonoBehaviour
{
public int ppu = 16;
private Transform parent;
private void Start()
{
parent = transform.parent;
}
private void LateUpdate()
{
float x = (Mathf.Round(parent.position.x * ppu) / ppu) - parent.position.x;
float y = (Mathf.Round(parent.position.y * ppu) / ppu) - parent.position.y;
transform.localPosition = new Vector3(x, y, transform.position.z);
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("ConnectionIndicator")]
public class ConnectionIndicator : MonoBehaviour
{
public ConnectionIndicator(IntPtr address) : this(address, "ConnectionIndicator")
{
}
public ConnectionIndicator(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public static ConnectionIndicator Get()
{
return MonoClass.smethod_15<ConnectionIndicator>(TritonHs.MainAssemblyPath, "", "ConnectionIndicator", "Get", Array.Empty<object>());
}
public bool IsVisible()
{
return base.method_11<bool>("IsVisible", Array.Empty<object>());
}
public void OnDestroy()
{
base.method_8("OnDestroy", Array.Empty<object>());
}
public void SetIndicator(bool val)
{
object[] objArray1 = new object[] { val };
base.method_8("SetIndicator", objArray1);
}
public void Update()
{
base.method_8("Update", Array.Empty<object>());
}
public static float LATENCY_TOLERANCE
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "ConnectionIndicator", "LATENCY_TOLERANCE");
}
}
public bool m_active
{
get
{
return base.method_2<bool>("m_active");
}
}
public GameObject m_indicator
{
get
{
return base.method_3<GameObject>("m_indicator");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using APINet.Api;
using log4net;
namespace APINet.Data
{
public class XmlProcessor : IDataProcessor
{
ILog _log = LogManager.GetLogger(typeof(XmlProcessor));
private XmlNode _nodes;
/// <summary>
/// Initializes a new instance of the <see cref="XmlProcessor" /> class.
/// </summary>
/// <param name="data">The XML data to be processed.</param>
public XmlProcessor(string data)
{
try
{
var doc = new XmlDocument();
doc.LoadXml(data);
_nodes = doc;
}
catch (XmlException ex)
{
_log.ErrorFormat("Error with {0} loading the Xml Document: {1}", ex.Source, ex.Message);
}
catch (XPathException ex)
{
_log.ErrorFormat("Error in {0} finding XPath expression: {1}", ex.Source, ex.Message);
}
catch (NullReferenceException ex)
{
_log.ErrorFormat("Null reference in {0} parsing XML: {1}", ex.TargetSite.Name, ex.Message);
}
catch (Exception ex)
{
_log.ErrorFormat("Unspecified error: {0}", ex.Message);
}
}
public List<ApiResponseItem> FindRelevantResults(ICollection<string> parentNodes, string resultName,
ICollection<string> resultNodes)
{
var results = new List<ApiResponseItem>();
ParseNodes(parentNodes);
foreach (XmlNode node in _nodes)
{
var apiResponseItem = new ApiResponseItem(resultNodes);
foreach (string resultNode in resultNodes)
{
XmlNode selectSingleNode = node.SelectSingleNode(resultNode);
if (selectSingleNode != null)
apiResponseItem.SetSubItem(resultNode, selectSingleNode.InnerText);
}
results.Add(apiResponseItem);
}
return results;
}
public List<ApiResponseItem<TR>> FindRelevantResults<TR>(ICollection<string> parentNodes, string resultName)
where TR : struct
{
var results = new List<ApiResponseItem<TR>>();
ParseNodes(parentNodes);
var responseValues = (TR[]) Enum.GetValues(typeof (TR));
foreach (XmlNode node in _nodes)
{
var item = new ApiResponseItem<TR>();
foreach (TR r in responseValues)
{
XmlNode selectSingleNode = node.SelectSingleNode(r.ToString());
if (selectSingleNode != null)
item.SetSubItem(r, selectSingleNode.InnerText);
}
results.Add(item);
}
return results;
}
/// <summary>
/// Moves to the desired result node.
/// </summary>
/// <param name="parents">The parents of the result node.</param>
private void ParseNodes(IEnumerable<string> parents)
{
foreach (string s in parents)
if (_nodes != null) _nodes = _nodes.SelectSingleNode(s);
}
}
} |
using System;
using System.Collections.Generic;
using System.Windows.Markup;
namespace Hsp.Mvvm
{
public class EnumValuesSource : MarkupExtension
{
public Type EnumType { get; set; }
public bool IncludeNull { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (EnumType == null) return null;
var ls = new List<object>();
if (IncludeNull)
ls.Add(null);
foreach (var item in Enum.GetValues(EnumType))
ls.Add(item);
return ls.ToArray();
}
}
}
|
using System;
using SLua;
using System.Collections.Generic;
[UnityEngine.Scripting.Preserve]
public class Lua_LTBezierPath : LuaObject {
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int constructor(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
LTBezierPath o;
if(argc==1){
o=new LTBezierPath();
pushValue(l,true);
pushValue(l,o);
return 2;
}
else if(argc==2){
UnityEngine.Vector3[] a1;
checkArray(l,2,out a1);
o=new LTBezierPath(a1);
pushValue(l,true);
pushValue(l,o);
return 2;
}
return error(l,"New object failed.");
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int setPoints(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
UnityEngine.Vector3[] a1;
checkArray(l,2,out a1);
self.setPoints(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int point(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
System.Single a1;
checkType(l,2,out a1);
var ret=self.point(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int place2d(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
UnityEngine.Transform a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
self.place2d(a1,a2);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int placeLocal2d(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
UnityEngine.Transform a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
self.placeLocal2d(a1,a2);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int place(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==3){
LTBezierPath self=(LTBezierPath)checkSelf(l);
UnityEngine.Transform a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
self.place(a1,a2);
pushValue(l,true);
return 1;
}
else if(argc==4){
LTBezierPath self=(LTBezierPath)checkSelf(l);
UnityEngine.Transform a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
UnityEngine.Vector3 a3;
checkType(l,4,out a3);
self.place(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function place to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int placeLocal(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==3){
LTBezierPath self=(LTBezierPath)checkSelf(l);
UnityEngine.Transform a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
self.placeLocal(a1,a2);
pushValue(l,true);
return 1;
}
else if(argc==4){
LTBezierPath self=(LTBezierPath)checkSelf(l);
UnityEngine.Transform a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
UnityEngine.Vector3 a3;
checkType(l,4,out a3);
self.placeLocal(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function placeLocal to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int getRationInOneRange(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
System.Single a1;
checkType(l,2,out a1);
var ret=self.getRationInOneRange(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int gizmoDraw(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
System.Single a1;
checkType(l,2,out a1);
self.gizmoDraw(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_pts(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
pushValue(l,true);
pushValue(l,self.pts);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_pts(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
UnityEngine.Vector3[] v;
checkArray(l,2,out v);
self.pts=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_length(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
pushValue(l,true);
pushValue(l,self.length);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_length(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
System.Single v;
checkType(l,2,out v);
self.length=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_orientToPath(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
pushValue(l,true);
pushValue(l,self.orientToPath);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_orientToPath(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
System.Boolean v;
checkType(l,2,out v);
self.orientToPath=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_orientToPath2d(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
pushValue(l,true);
pushValue(l,self.orientToPath2d);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_orientToPath2d(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
System.Boolean v;
checkType(l,2,out v);
self.orientToPath2d=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_distance(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTBezierPath self=(LTBezierPath)checkSelf(l);
pushValue(l,true);
pushValue(l,self.distance);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[UnityEngine.Scripting.Preserve]
static public void reg(IntPtr l) {
getTypeTable(l,"LTBezierPath");
addMember(l,setPoints);
addMember(l,point);
addMember(l,place2d);
addMember(l,placeLocal2d);
addMember(l,place);
addMember(l,placeLocal);
addMember(l,getRationInOneRange);
addMember(l,gizmoDraw);
addMember(l,"pts",get_pts,set_pts,true);
addMember(l,"length",get_length,set_length,true);
addMember(l,"orientToPath",get_orientToPath,set_orientToPath,true);
addMember(l,"orientToPath2d",get_orientToPath2d,set_orientToPath2d,true);
addMember(l,"distance",get_distance,null,true);
createTypeMetatable(l,constructor, typeof(LTBezierPath));
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game.Mono;
[Attribute38("FontTableEntry")]
public class FontTableEntry : MonoClass
{
public FontTableEntry(IntPtr address) : this(address, "FontTableEntry")
{
}
public FontTableEntry(IntPtr address, string className) : base(address, className)
{
}
public string m_FontDefName
{
get
{
return base.method_4("m_FontDefName");
}
}
public string m_FontName
{
get
{
return base.method_4("m_FontName");
}
}
}
}
|
//using SIGA.Models.ViewModels;
//using SIGA_Model;
//using SIGA_Model.StoredProcContexts;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Web;
//using System.Web.Http;
//using System.Web.Http.Description;
//namespace SIGA.Controllers_Api
//{
// public class UsuarioController : ApiController
// {
// public UsuarioController()
// {
// AutoMapper.Mapper.CreateMap<Persona, UsuarioController>();
// AutoMapper.Mapper.CreateMap<UsuarioController, Persona>();
// AutoMapper.Mapper.CreateMap<Usuario, UsuarioController>();
// AutoMapper.Mapper.CreateMap<UsuarioController, Usuario>();
// AutoMapper.Mapper.CreateMap<Alumno, UsuarioController>();
// AutoMapper.Mapper.CreateMap<UsuarioController, Alumno>();
// //AutoMapper.Mapper.CreateMap<Persona, UsuarioController>();
// //AutoMapper.Mapper.CreateMap<UsuarioController, Persona>();
// }
// // POST: api/Authors
// //[HttpPost]
// //[Route("api/createusuario")]
// [ResponseType(typeof(UsuarioViewModel))]
// public IHttpActionResult Post(UsuarioViewModel usuarioViewModel)
// {
// var persona = AutoMapper.Mapper.Map<UsuarioViewModel, Persona>(usuarioViewModel);
// int personaIdentity = 0;
// using (var db = new SIGAEntities())
// {
// try
// {
// db.Persona.Add(persona);
// db.SaveChanges();
// personaIdentity = persona.Per_Id;
// if (personaIdentity > 0)
// {
// var usuario = AutoMapper.Mapper.Map<UsuarioViewModel, Usuario>(usuarioViewModel);
// int usuarioIdentity = 0;
// UsuarioData.Per_Id = personaIdentity;
// db.Usuario.Add(usuario);
// db.SaveChanges();
// usuarioIdentity = UsuarioData.User_Id;
// if (usuarioIdentity > 0)
// {
// var alumno = AutoMapper.Mapper.Map<UsuarioViewModel, Alumno>(usuarioViewModel);
// alumno.User_Id = usuarioIdentity;
// db.Alumno.Add(alumno);
// db.SaveChanges();
// }
// }
// }
// catch (Exception)
// {
// throw;
// }
// }
// return CreatedAtRoute("DefaultApi", new { User_Id = usuarioViewModel.User_Id }, usuarioViewModel);
// }
// }
//} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.