text stringlengths 13 6.01M |
|---|
using API.Omorfias.Domain.Base;
using API.Omorfias.Domain.Validations;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
namespace API.Omorfias.Domain.Interfaces.Services
{
public interface IService<TEntity, TOrderBy>
where TEntity : class
{
IEnumerable<TEntity> ObterTodos(bool _readonly = true);
TEntity ObterPorId(int id);
TEntity ObterPorCondicao(Expression<Func<TEntity, bool>> predicate, bool _readonly = false, params Expression<Func<TEntity, object>>[] joins);
IEnumerable<TEntity> Listar(Expression<Func<TEntity, bool>> predicate, bool _readonly = true, params Expression<Func<TEntity, object>>[] joins);
DataResults<TEntity> Listar(QueryOptions<TEntity, TOrderBy> options, bool _readonly = true, params Expression<Func<TEntity, object>>[] joins);
TEntity Adicionar(TEntity entity);
void Modificar(TEntity entity);
void Remover(TEntity entity);
string GetDescription(Enum en);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace Final_EDATOS_Tiscornia
{
class Program
{
static void Main(string[] args)
{
byte opcion;
int contador = 0;
Queue<int> coladepedidos = new Queue<int>();
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
Console.WriteLine("Bienvenido al centro de Pedidos");
Console.ReadLine();
Console.Clear();
do
{
Console.Clear();
Console.WriteLine("Para crear una cola marque 1");
Console.WriteLine("Para borrar una cola marque 2");
Console.WriteLine("Para crear un pedido marque 3");
Console.WriteLine("Para borrar un pedido marque 4");
Console.WriteLine("Para listar todos los pedidos marque 5");
Console.WriteLine("Para listar el primer pedido marque 6");
Console.WriteLine("Para listar el último pedido marque 7");
Console.WriteLine("Para ver la cantidad de pedidos marque 8");
Console.WriteLine("Para buscar un pedido marque 9");
Console.WriteLine("Para guardar la cola como archivo .txt marque 10");
Console.WriteLine("Para salir marque otro número");
opcion = Convert.ToByte(Console.ReadLine());
switch (opcion)
{
case 1:
Console.Clear();
Console.WriteLine("Crearemos una cola de pedidos: ");
coladepedidos = new Queue<int>();
Console.WriteLine("Se creo la cola de pedidos");
Console.ReadLine(); break;
case 2:
Console.Clear();
Console.WriteLine("Borraremos una cola de pedidos: ");
coladepedidos.Clear();
Console.ReadLine(); break;
case 3:
Console.Clear();
Console.WriteLine("Ingrese el número de pedido: ");
int pedido = Convert.ToInt32(Console.ReadLine());
if (pedido < 999 & pedido > 0)
{ coladepedidos.Enqueue(pedido); break; }
else
{
Console.WriteLine("El número de pedido debe ser mayor a 0 y menor a 999");
Console.ReadLine(); break;
}
case 4:
Console.Clear();
Console.WriteLine("Vamos a borrar el primer pedido de la lista: ");
coladepedidos.Dequeue();
contador = 0;
foreach (int orden in coladepedidos)
{
contador++;
Console.WriteLine("{0} - {1} ", contador, orden);
}
Console.ReadLine(); break;
case 5:
Console.Clear();
Console.WriteLine("Veamos los pedidos en la cola");
contador = 0;
foreach (int orden in coladepedidos)
{
contador++;
Console.WriteLine("{0} - {1} ", contador, orden);
}
Console.ReadLine(); break;
case 6:
Console.Clear();
int primer = coladepedidos.Peek();
Console.WriteLine("El primer pedido es {0}.", primer);
Console.ReadLine(); break;
case 7:
Console.Clear();
List<int> lista1 = new List<int>();
foreach (int ultimo in coladepedidos)
lista1.Add(ultimo);
lista1.Reverse();
int ultimopedido = lista1[0];
Console.WriteLine("El último pedido es {0} ", ultimopedido);
Console.ReadLine(); break;
case 8:
Console.Clear();
int cantidad = coladepedidos.Count;
Console.WriteLine("La cola contiene {0} elementos.", cantidad);
Console.ReadLine(); break;
case 9:
Console.Clear();
bool resultado;
Console.WriteLine("Ingrese el pedido que busca: ");
int pedidobuscado = Convert.ToInt32(Console.ReadLine());
resultado = coladepedidos.Contains(pedidobuscado);
if (resultado)
{
Console.WriteLine("El pedido {0} se encuentra en la cola", pedidobuscado);
}
else
{
Console.WriteLine("El pedido {0} no se encuentra en la cola", pedidobuscado);
}
Console.ReadLine(); break;
case 10:
Console.Clear();
Console.WriteLine("Ingresa el nombre con el que querés guardar la lista: ");
string archivo = Console.ReadLine() + ".txt";
TextWriter writer = File.CreateText(archivo);
foreach (int p in coladepedidos)
{
writer.WriteLine(p);
}
writer.Close();
Console.WriteLine("El archivo {0} ya está guardado", archivo);
Console.ReadLine(); break;
default:
Console.Clear();
Console.WriteLine("Gracias, vuelva pronto!");
Console.ReadLine(); break;
}
} while (opcion > 0 & opcion < 11);
}
}
}
|
using System;
using ShCore.Utility;
using System.Collections.Generic;
using System.Reflection;
namespace ShCore.Reflectors
{
/// <summary>
/// Reflect để lấy xem property có Attribute gì
/// </summary>
/// <typeparam name="TAttribute"></typeparam>
public class ReflectTypeListPropertyWithAttribute<TAttribute> : DictionaryCacheBase<Type, List<Pair<PropertyInfo, TAttribute>>> where TAttribute : Attribute
{
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
protected override List<Pair<PropertyInfo, TAttribute>> GetValueForDic(Type key)
{
return MemberInfoHelper.Inst.GetListPairPropertyAttribute<TAttribute>(key, true);
}
}
}
|
namespace Workout.Services.Privilege
{
/// <summary>
/// Class describing a privilege status.
/// </summary>
public class PrivilegeItem
{
#region properties
/// <summary>
/// The privilege key.
/// </summary>
public string Privilege { get; }
/// <summary>
/// Flag indicating whether the permission is granted or not.
/// </summary>
public bool Granted { get; private set; }
/// <summary>
/// Flag indicating whether the permission has been checked or not.
/// </summary>
public bool Checked { get; private set; }
#endregion
#region methods
/// <summary>
/// Initializes class instance.
/// </summary>
/// <param name="privilege">Privilege key.</param>
public PrivilegeItem(string privilege)
{
Privilege = privilege;
}
/// <summary>
/// Sets the flag indicating whether permission has been granted or not.
/// </summary>
/// <param name="value">True if permission has been granted, false otherwise.</param>
public void GrantPermission(bool value)
{
Granted = value;
Checked = true;
}
#endregion
}
}
|
using UnityEngine;
using Binocle.Processors;
using Binocle.Components;
namespace Binocle
{
public class Entity : MonoBehaviour
{
public GameObject GameObject
{
get { return _gameObject; }
set { _gameObject = value; }
}
private GameObject _gameObject;
public Scene Scene
{
get { return _scene; }
set { _scene = value; }
}
private Scene _scene;
public BitSet ComponentBits
{
get { return _componentBits; }
}
private BitSet _componentBits = new BitSet();
public Entity Parent
{
get { return _parent; }
}
private Entity _parent;
public T AddComponent<T>()
where T : UnityEngine.Component
{
var c = _gameObject.AddComponent<T>();
if (c is BaseMonoBehaviour)
{
object b = (object)c;
((BaseMonoBehaviour)b).Entity = this;
}
this.ComponentBits.set(ComponentTypeManager.GetIndexFor(typeof(T)));
_scene.EntityProcessors.onComponentAdded(this);
return c;
}
public void RemoveComponent<T>()
where T : UnityEngine.Component
{
var c = _gameObject.GetComponent<T>();
GameObject.Destroy(c);
this.ComponentBits.set(ComponentTypeManager.GetIndexFor(typeof(T)), false);
_scene.EntityProcessors.onComponentRemoved(this);
}
public void SetParent(Entity parent)
{
_parent = parent;
if (parent != null)
{
GameObject.transform.SetParent(parent.GameObject.transform);
}
else
{
GameObject.transform.SetParent(null);
}
}
public static void Destroy(Entity entity)
{
foreach (var c in entity.GameObject.GetComponents(typeof(MonoBehaviour)))
{
//Debug.Log("Removed [" + entity.name + "] " + c.GetType().ToString());
if (c is Entity) continue;
entity.ComponentBits.set(ComponentTypeManager.GetIndexFor(c.GetType()), false);
entity.Scene.EntityProcessors.onComponentRemoved(entity);
GameObject.Destroy(c);
}
GameObject.Destroy(entity.GameObject);
}
}
}
|
using ServiceDesk.Api.Systems.Common.Interfaces.Dto;
using ServiceDesk.Api.Systems.Common.Interfaces.DtoBuilder;
namespace ServiceDesk.Api.Systems.PersonalAreaSystem.DtoBuilders.Client
{
public interface IClientDtoBuilder<TDto> : IDtoBuilder<Core.Entities.PersonalAreaSystem.Client, TDto>
where TDto : class, IDto
{
}
}
|
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended.Shapes;
namespace MonoGame.Extended.SceneGraphs
{
public class SceneNode : IMovable, IRotatable, IScalable
{
public SceneNode(string name)
: this(name, Vector2.Zero, 0, Vector2.One)
{
}
public SceneNode(string name, Vector2 position, float rotation = 0)
: this(name, position, rotation, Vector2.One)
{
}
public SceneNode(string name, Vector2 position, float rotation, Vector2 scale)
{
Name = name;
Position = position;
Rotation = rotation;
Scale = scale;
Children = new SceneNodeCollection(this);
Entities = new SceneEntityCollection();
}
public SceneNode()
: this(null, Vector2.Zero, 0, Vector2.One)
{
}
public string Name { get; set; }
public Vector2 Position { get; set; }
public float Rotation { get; set; }
public Vector2 Scale { get; set; }
public SceneNode Parent { get; internal set; }
public SceneNodeCollection Children { get; }
public SceneEntityCollection Entities { get; }
public object Tag { get; set; }
public RectangleF GetBoundingRectangle()
{
Vector2 position, scale;
float rotation;
GetWorldTransform().Decompose(out position, out rotation, out scale);
var rectangles = Entities
.Select(e =>
{
var r = e.GetBoundingRectangle();
r.Offset(position);
return r;
})
.Concat(Children.Select(i => i.GetBoundingRectangle()))
.ToArray();
var x0 = rectangles.Min(r => r.Left);
var y0 = rectangles.Min(r => r.Top);
var x1 = rectangles.Max(r => r.Right);
var y1 = rectangles.Max(r => r.Bottom);
return new RectangleF(x0, y0, x1 - x0, y1 - y0);
}
public Matrix GetWorldTransform()
{
return Parent == null ? Matrix.Identity : Matrix.Multiply(GetLocalTransform(), Parent.GetWorldTransform());
}
public Matrix GetLocalTransform()
{
var rotationMatrix = Matrix.CreateRotationZ(Rotation);
var scaleMatrix = Matrix.CreateScale(new Vector3(Scale.X, Scale.Y, 1));
var translationMatrix = Matrix.CreateTranslation(new Vector3(Position.X, Position.Y, 0));
var tempMatrix = Matrix.Multiply(scaleMatrix, rotationMatrix);
return Matrix.Multiply(tempMatrix, translationMatrix);
}
public void Draw(SpriteBatch spriteBatch)
{
Vector2 offsetPosition, offsetScale;
float offsetRotation;
var worldTransform = GetWorldTransform();
worldTransform.Decompose(out offsetPosition, out offsetRotation, out offsetScale);
foreach (var drawable in Entities.OfType<ISpriteBatchDrawable>())
{
if (drawable.IsVisible)
{
var texture = drawable.TextureRegion.Texture;
var sourceRectangle = drawable.TextureRegion.Bounds;
var position = offsetPosition + drawable.Position;
var rotation = offsetRotation + drawable.Rotation;
var scale = offsetScale * drawable.Scale;
spriteBatch.Draw(texture, position, sourceRectangle, drawable.Color, rotation, drawable.Origin, scale, drawable.Effect, 0);
}
}
foreach (var child in Children)
child.Draw(spriteBatch);
}
public override string ToString()
{
return $"name: {Name}, position: {Position}, rotation: {Rotation}, scale: {Scale}";
}
}
}
|
/********************************************************************
* FulcrumWeb RAD Framework - Fulcrum of your business *
* Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED *
* *
* THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED *
* FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE *
* COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE *
* AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT *
* AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE *
* AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. *
********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using Framework.Utils;
namespace Framework.Metadata
{
/// <summary>
/// Summary description for CxMetadataObject.
/// </summary>
public class CxMetadataObject
{
//----------------------------------------------------------------------------
protected CxMetadataHolder m_Holder = null;
private Dictionary<string, string> m_PropertyValues = new Dictionary<string, string>(); // Object property/value pairs
protected string m_Id = ""; // ID of the attribute
protected string idAttribute = ""; // Default name of the ID attribute
protected Dictionary<string, string> m_InitialPropertyValues =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
protected List<string> m_NonInheritableProperties;
protected Dictionary<string, bool> m_IsPropertyLocalizableMap = new Dictionary<string, bool>();
//----------------------------------------------------------------------------
/// <summary>
/// A list of property names that are not inheritable.
/// </summary>
public virtual List<string> NonInheritableProperties
{
get
{
return new List<string>(CxNonInheritablePropertyRegistry.GetProperties(GetType()));
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Constructor.
/// </summary>
/// <param name="holder">parent metadata holder object</param>
/// <param name="element">XML element that holds metadata</param>
public CxMetadataObject(CxMetadataHolder holder, XmlElement element) :
this(holder, element, "id")
{
}
//----------------------------------------------------------------------------
/// <summary>
/// Constructor.
/// </summary>
/// <param name="holder">parent metadata holder object</param>
public CxMetadataObject(CxMetadataHolder holder)
{
m_Holder = holder;
}
//----------------------------------------------------------------------------
/// <summary>
/// Constructor.
/// </summary>
/// <param name="holder">metadata holder</param>
/// <param name="element">XML element that holds metadata</param>
/// <param name="idName">name of the ID attribute</param>
public CxMetadataObject(
CxMetadataHolder holder,
XmlElement element,
string idName) : this(holder)
{
// Invoke metadata holder event handler
holder.DoOnMetadataObjectLoading(this, element);
// Load properties
foreach (XmlAttribute attribute in element.Attributes)
{
string name = attribute.Name;
string value = attribute.Value;
value = (name == idName ? CxUtils.Nvl(value.ToUpper()) : value);
m_InitialPropertyValues[name] = value;
PropertyValues[name] = value;
}
// Initialize ID
if (CxUtils.NotEmpty(idName))
{
m_Id = this[idName].ToUpper();
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Gets a dictionary of property values exactly as they were initialized during XML loading.
/// </summary>
/// <returns></returns>
public IDictionary<string, string> GetInitialPropertyValues()
{
Dictionary<string, string> initialProperties = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> pair in m_InitialPropertyValues)
{
initialProperties.Add(pair.Key, pair.Value);
}
return initialProperties;
}
//----------------------------------------------------------------------------
/// <summary>
/// Loads custom metadata object from the given XML element.
/// </summary>
/// <param name="element">the element to load from</param>
public virtual void LoadCustomMetadata(XmlElement element)
{
Dictionary<string, bool> ignoreMap = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
ignoreMap.Add("id", true);
foreach (XmlAttribute attr in element.Attributes)
{
if (!ignoreMap.ContainsKey(attr.Name))
{
PropertyValues[attr.Name] = attr.Value;
}
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Loads metadata object override.
/// </summary>
/// <param name="element">XML element to load overridden properties from</param>
virtual public void LoadOverride(XmlElement element)
{
Dictionary<string, bool> ignoreMap = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
ignoreMap.Add("id", true);
foreach (XmlAttribute attr in element.Attributes)
{
if (!ignoreMap.ContainsKey(attr.Name))
{
m_InitialPropertyValues[attr.Name] = attr.Value;
PropertyValues[attr.Name] = attr.Value;
}
}
foreach (XmlNode node in element.ChildNodes)
{
if (node is XmlElement && !CxXml.HasChildXmlElements(node) && !ignoreMap.ContainsKey(node.Name))
{
ReplacePropertyWithNode(element, node.Name);
}
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns localized value of the property
/// or null if localized value not found (or localization is disabled)
/// </summary>
/// <param name="propertyName">name of the property</param>
/// <param name="propertyValue">value of the property</param>
public string GetLocalizedPropertyValue(
string propertyName,
string propertyValue)
{
return GetLocalizedPropertyValue(
propertyName,
propertyValue,
Holder.LanguageCode);
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns localized value of the property
/// or null if localized value not found (or localization is disabled)
/// </summary>
/// <param name="propertyName">name of the property</param>
/// <param name="propertyValue">value of the property</param>
/// <param name="languageCode">language code</param>
virtual public string GetLocalizedPropertyValue(
string propertyName,
string propertyValue,
string languageCode)
{
if (IsPropertyLocalizable(propertyName))
{
string localizedValue = Holder.Multilanguage.GetLocalizedValue(
languageCode,
LocalizationObjectTypeCode,
propertyName,
LocalizationObjectName,
propertyValue);
if (localizedValue != null)
{
// Return successfully localized value
return localizedValue;
}
else
{
// Try to find localized value from the inheritance list
IList<CxMetadataObject> inheritanceList = InheritanceList;
if (inheritanceList != null)
{
foreach (CxMetadataObject parentObject in inheritanceList)
{
// Ignore this object if somehow it is present in the list
if (parentObject != this)
{
// Search only properties non-overridden in the metadata
// Stop search when first overridden property was found
if (GetNonLocalizedPropertyValue(propertyName) != parentObject.GetNonLocalizedPropertyValue(propertyName))
{
return null;
}
localizedValue = parentObject[propertyName];
if (localizedValue != propertyValue)
{
// Localized value differs from the non-localized, localization OK
return localizedValue;
}
}
}
}
}
}
return null;
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns original value of property (without localization).
/// </summary>
/// <param name="propertyName">name of the property</param>
public string GetNonLocalizedPropertyValue(string propertyName)
{
if (PropertyValues.ContainsKey(propertyName))
return PropertyValues[propertyName];
else
return string.Empty;
}
//-------------------------------------------------------------------------
/// <summary>
/// Metadata object properties.
/// </summary>
virtual public string this[string propertyName]
{
get
{
string result = GetNonLocalizedPropertyValue(propertyName);
string localizedValue = GetLocalizedPropertyValue(propertyName, result);
if (localizedValue != null)
{
result = localizedValue;
}
return result;
}
set
{
PropertyValues[propertyName] = value;
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns initial property value, that was before DB override is loaded.
/// </summary>
/// <param name="propertyName">property name</param>
/// <param name="getNonLocalizedValueIfEmpty">indicates if the method should return
/// original property value when initial property value is empty.</param>
/// <returns>initial property value</returns>
public string GetInitialProperty(string propertyName, bool getNonLocalizedValueIfEmpty)
{
string value = string.Empty;
if (!CxUtils.IsEmpty(propertyName))
{
if (!m_InitialPropertyValues.TryGetValue(propertyName, out value))
{
if (getNonLocalizedValueIfEmpty)
value = GetNonLocalizedPropertyValue(propertyName);
else
value = string.Empty;
}
}
return value;
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns initial property value, that was before DB override is loaded or
/// original property value when initial property value is empty.
/// </summary>
/// <param name="propertyName">property name</param>
/// <returns>initial property value</returns>
public string GetInitialProperty(string propertyName)
{
return GetInitialProperty(propertyName, true);
}
//-------------------------------------------------------------------------
/// <summary>
/// Wipes the given property out from the properties map.
/// </summary>
/// <returns>true if the properties map has been changed, otherwise false</returns>
public void ResetPropertyToInitialValue(string propertyName)
{
if (m_InitialPropertyValues.ContainsKey(propertyName))
PropertyValues[propertyName] = m_InitialPropertyValues[propertyName];
else
PropertyValues.Remove(propertyName);
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns true if the metadata object contains property with the given name.
/// </summary>
/// <param name="propertyName">property name to check</param>
public bool Contains(string propertyName)
{
return PropertyValues.ContainsKey(propertyName);
}
//-------------------------------------------------------------------------
/// <summary>
/// Object ID.
/// </summary>
public string Id
{
get { return m_Id; }
set { m_Id = value.ToUpper(); }
}
//-------------------------------------------------------------------------
/// <summary>
/// Adds contents of node with the given name to the properties list.
/// </summary>
/// <param name="element">element the text node located under</param>
/// <param name="nodeName">name of the text node</param>
protected void AddNodeToProperties(XmlElement element, string nodeName)
{
XmlNode node = element.SelectSingleNode(nodeName);
if (node != null)
{
string nodeValue = CxText.TrimSpace(node.InnerText);
PropertyValues[nodeName] = nodeValue;
m_InitialPropertyValues[nodeName] = nodeValue;
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Puts contents of node with the given name to the properties list.
/// Replaces existing property value.
/// </summary>
/// <param name="element">element the text node located under</param>
/// <param name="nodeName">name of the text node</param>
protected void ReplacePropertyWithNode(XmlElement element, string nodeName)
{
XmlNode node = element.SelectSingleNode(nodeName);
if (node != null)
{
string nodeValue = CxText.TrimSpace(node.InnerText);
PropertyValues[nodeName] = nodeValue;
m_InitialPropertyValues[nodeName] = nodeValue;
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Copies all properties from the given object excluding listed ones.
/// </summary>
/// <param name="obj">object to copy properties from</param>
/// <param name="excludedProps">array with names of excluded properties</param>
public void CopyPropertiesFrom(CxMetadataObject obj, params string[] excludedProps)
{
foreach (string name in obj.PropertyValues.Keys)
{
if (name != idAttribute &&
Array.IndexOf(excludedProps, name) == -1)
{
if (!PropertyValues.ContainsKey(name))
{
PropertyValues[name] = obj.PropertyValues[name];
}
if (!m_InitialPropertyValues.ContainsKey(name) &&
obj.m_InitialPropertyValues.ContainsKey(name))
{
m_InitialPropertyValues[name] = obj.m_InitialPropertyValues[name];
}
}
}
DoAfterCopyProperties(obj);
}
//----------------------------------------------------------------------------
/// <summary>
/// Copies properties from all metadata objects present in the given list.
/// </summary>
/// <param name="metadataObjectList">list of metadata objects</param>
public void CopyPropertiesFrom(IList<CxMetadataObject> metadataObjectList)
{
if (metadataObjectList != null)
{
foreach (CxMetadataObject metadataObject in metadataObjectList)
{
CopyPropertiesFrom(metadataObject);
}
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Copies properties from all metadata objects present in the given list.
/// </summary>
/// <param name="metadataObjectList">list of metadata objects</param>
/// <param name="excludedProperties">the properties to ignore while copying</param>
public void CopyPropertiesFrom(
IList<CxMetadataObject> metadataObjectList, string[] excludedProperties)
{
if (metadataObjectList != null)
{
foreach (CxMetadataObject metadataObject in metadataObjectList)
{
CopyPropertiesFrom(metadataObject, excludedProperties);
}
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Inherits all the properties from the given list of metadata object into the current object.
/// </summary>
/// <param name="metadataObjectList">list of metadata object to inherit properties from</param>
public void InheritPropertiesFrom(IList<CxMetadataObject> metadataObjectList)
{
CopyPropertiesFrom(metadataObjectList, NonInheritableProperties.ToArray());
}
//----------------------------------------------------------------------------
/// <summary>
/// Inherits all the properties from the given metadata object into the current object.
/// </summary>
/// <param name="metadataObject">the metadata object to inherit from</param>
public void InheritPropertiesFrom(CxMetadataObject metadataObject)
{
InheritPropertiesFrom(new CxMetadataObject[] { metadataObject });
}
//----------------------------------------------------------------------------
/// <summary>
/// Method is called after properties copying.
/// </summary>
/// <param name="sourceObj">object properties were taken from</param>
virtual protected void DoAfterCopyProperties(CxMetadataObject sourceObj)
{
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns object ID.
/// </summary>
/// <returns>metadata object id</returns>
override public string ToString()
{
return Id;
}
//----------------------------------------------------------------------------
/// <summary>
/// Parent metadata holder object.
/// </summary>
public CxMetadataHolder Holder
{ get {return m_Holder;} }
//----------------------------------------------------------------------------
/// <summary>
/// User-friendly metadata object caption.
/// </summary>
virtual public string Text
{
get
{
return CxUtils.Nvl(this["text"], Id);
}
set
{
this["text"] = value;
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Group name for the metadata object (if applicable).
/// </summary>
virtual public string GroupName
{ get {return this["group_name"];} }
//-------------------------------------------------------------------------
protected CxEntityUsageMetadata m_SecurityEntityUsage_Cache;
/// <summary>
/// Returns metadata object to find permissions for the object.
/// </summary>
virtual protected CxEntityUsageMetadata GetSecurityEntityUsage()
{
if (m_SecurityEntityUsage_Cache == null)
{
string id = this["security_entity_usage_id"];
m_SecurityEntityUsage_Cache = CxUtils.NotEmpty(id) ? Holder.EntityUsages[id] : null;
}
return m_SecurityEntityUsage_Cache;
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns metadata object to find permissions for the object.
/// </summary>
public CxEntityUsageMetadata SecurityEntityUsage
{ get {return GetSecurityEntityUsage();} }
//-------------------------------------------------------------------------
/// <summary>
/// Returns collection of all property names.
/// </summary>
public ICollection PropertyNames
{ get {return PropertyValues.Keys;} }
//-------------------------------------------------------------------------
/// <summary>
/// True if metadata object is visible
/// </summary>
virtual protected bool GetIsVisible()
{
if (this["visible"].ToLower() == "false")
{
return false;
}
if (IsHiddenForUser && Holder != null && !Holder.IsDevelopmentMode)
{
return false;
}
return true;
}
//-------------------------------------------------------------------------
/// <summary>
/// Gets or sets a value that indicates if the metadata object is visible.
/// </summary>
public bool Visible
{
get { return GetIsVisible(); }
set { this["visible"] = value.ToString().ToLower(); }
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns true if metadata object is initially visible before loading
/// customizations from a database.
/// </summary>
public bool InitiallyVisible
{
get
{
string visible = GetInitialProperty("visible");
if (visible.ToLower() == "false")
{
return false;
}
if (IsHiddenForUser && Holder != null && !Holder.IsDevelopmentMode)
{
return false;
}
return true;
}
}
//----------------------------------------------------------------------------
/// <summary>
/// True if metadata object should be available only in development mode.
/// </summary>
public bool IsHiddenForUser
{
get { return CxBool.Parse(this["hidden_for_user"], false); }
set { this["hidden_for_user"] = value.ToString(); }
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns true if multilanguage is enabled.
/// </summary>
public bool IsMultilanguageEnabled
{
get
{
return Holder != null && Holder.IsMultilanguageEnabled;
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns true if property with the given name should be localizable.
/// </summary>
virtual public bool IsPropertyLocalizable(string propertyName)
{
if (!string.IsNullOrEmpty(LocalizationObjectTypeCode) &&
!string.IsNullOrEmpty(propertyName) &&
IsMultilanguageEnabled)
{
bool isLocalizible;
if (m_IsPropertyLocalizableMap.TryGetValue(propertyName, out isLocalizible))
return isLocalizible;
return
m_IsPropertyLocalizableMap[propertyName] =
Holder.Multilanguage.IsLocalizable(LocalizationObjectTypeCode, propertyName);
}
return false;
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns object type code for localization.
/// </summary>
virtual public string LocalizationObjectTypeCode
{
get
{
return null;
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns unique object name for localization.
/// </summary>
virtual public string LocalizationObjectName
{
get
{
return Id;
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns list of metadata objects properties was inherited from.
/// </summary>
virtual public IList<CxMetadataObject> InheritanceList
{
get
{
return null;
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns list of entity usages which are referenced by attribute properties.
/// </summary>
/// <returns>list of CxEntityMetadata objects or null</returns>
virtual public IList<CxEntityMetadata> GetReferencedEntities()
{
return null;
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns parent metadata object.
/// </summary>
virtual public CxMetadataObject ParentObject
{
get
{
return null;
}
}
//----------------------------------------------------------------------------
/// <summary>
/// The map of property values.
/// </summary>
public Dictionary<string, string> PropertyValues
{
get { return m_PropertyValues; }
set { m_PropertyValues = value; }
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns the XML tag name applicable for the current metadata object.
/// </summary>
public virtual string GetTagName()
{
return string.Empty;
}
//----------------------------------------------------------------------------
/// <summary>
/// Renders the metadata object to its XML representation.
/// </summary>
/// <param name="document">the document to render into</param>
/// <param name="custom">indicates whether just customization should be rendered</param>
/// <param name="tagNameToUse">the tag name to be used while rendering</param>
/// <returns>the rendered object</returns>
public virtual CxXmlRenderedObject RenderToXml(
XmlDocument document, bool custom, string tagNameToUse)
{
string tagName = tagNameToUse;
if (string.IsNullOrEmpty(tagName))
tagName = GetTagName();
if (string.IsNullOrEmpty(tagName))
throw new ExException(string.Format("Current metadata object type <{0}> does not provide a valid tag name", GetType()));
CxXmlRenderedObject result = new CxXmlRenderedObject();
if (string.IsNullOrEmpty(tagNameToUse) && custom)
tagName += "_custom";
Dictionary<string, string> propertiesToRender = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> pair in PropertyValues)
{
bool isAttributeToRender = !IsPropertyLocalizable(pair.Key);
if (isAttributeToRender && pair.Key != "id" && custom)
{
if (m_InitialPropertyValues.ContainsKey(pair.Key))
isAttributeToRender = !CxText.Equals(pair.Value, m_InitialPropertyValues[pair.Key]);
else
isAttributeToRender = !string.IsNullOrEmpty(pair.Value);
}
if (isAttributeToRender)
{
propertiesToRender[pair.Key] = pair.Value;
}
}
if (propertiesToRender.Count == 1 && propertiesToRender.ContainsKey("id"))
result.IsEmpty = true;
XmlElement element = document.CreateElement(tagName, string.Empty);
foreach (KeyValuePair<string, string> pair in propertiesToRender)
{
if (pair.Value != null)
{
XmlAttribute attribute = document.CreateAttribute(pair.Key);
attribute.Value = pair.Value;
element.Attributes.Append(attribute);
}
}
result.Element = element;
return result;
}
//----------------------------------------------------------------------------
#region Static methods to work with metadata objects
//-------------------------------------------------------------------------
/// <summary>
/// Returns a list of ids.
/// </summary>
/// <typeparam name="T">metadata object type</typeparam>
/// <param name="list">list of metadata objects</param>
/// <returns></returns>
static public IList<string> ExtractIds<T>(IList<T> list) where T : CxMetadataObject
{
if (list == null)
return null;
List<string> ids = new List<string>();
for (int i = 0; i < list.Count; i++)
{
ids.Add(list[i].Id);
}
return ids;
}
//-------------------------------------------------------------------------
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using TableTopCrucible.Domain.Models.ValueTypes;
namespace TableTopCrucible.Domain.Library
{
public interface IFileManagementService
{
FileHash HashFile(HashAlgorithm hashAlgorithm, string path);
FileHash HashFile(string path);
}
public class FileManagementService:IFileManagementService
{
public FileHash HashFile(HashAlgorithm hashAlgorithm, string path)
{
if (!File.Exists(path))
throw new FileNotFoundException($"could not find file {path}");
FileHash result;
using (FileStream stream = File.OpenRead(path))
{
byte[] data = hashAlgorithm.ComputeHash(stream);
result = new FileHash(data);
}
return result;
}
public FileHash HashFile(string path)
{
using HashAlgorithm hashAlgorithm = SHA512.Create();
return HashFile(hashAlgorithm, path);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using AorBaseUtility;
using YoukiaCore;
public class ErlEntry
{
public Connect connect;
/// <summary>
/// </summary>
public int number;
/// <summary>
/// 是否是Ping消息
/// </summary>
public bool isPing;
/// <summary>
/// 是否是断线重连消息
/// </summary>
public bool isReConnect;
/// <summary>
/// </summary>
public ReceiveFun receiveFun;
public List<Object> argus;
public ByteBuffer data;
public ErlEntry(Connect connect, int number, ReceiveFun receiveFun, List<Object> argus, bool isPing, ByteBuffer data, bool isReConnect)
{
this.isReConnect = isReConnect;
this.connect=connect;
this.number=number;
this.receiveFun=receiveFun;
this.argus=argus;
this.isPing = isPing;
this.data = data;
}
}
|
namespace VirtualSwitch
{
public interface ISwitch
{
bool CloseAll(ref string errMsg);
bool Open(int switchIndex, ref string errMsg);
bool Open(byte[] switchNum, ref string errMsg);
bool OpenS(int switchIndex, ref string errMsg);
bool OpenS(byte[] switchNum, ref string errMsg);
}
enum IndexType
{
Row,
Column
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HdmiExtenderLib
{
//public class HdmiExtenderSender
//{
///// <summary>
///// Broadcasts a Sender Control Packet, imitating an HDMI Extender Sender device. This packet should be broadcast once per second.
///// </summary>
//public void BroadcastSenderControlPacket()
//{
// try
// {
// using (Socket s = new Socket(SocketType.Dgram, ProtocolType.Udp))
// {
// string hexPacketNumber = (senderControlPacketCounter++).ToString("X").PadLeft(4, '0');
// // This number needs to be little-endian.
// hexPacketNumber = hexPacketNumber.Substring(2, 2) + hexPacketNumber.Substring(0, 2);
// string hexControlPacket = "5446367a63010000" + hexPacketNumber + "00030303002400000000000000000000001000000000000000000000007800d1a6300001";
// byte[] controlPacket = HexStringToByteArray(hexControlPacket);
// s.Bind(new IPEndPoint(IPAddress.Parse("192.168.168.57"), 48689));
// s.SendTo(controlPacket, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 48689));
// }
// }
// catch (Exception ex)
// {
// Console.WriteLine(ex.ToString());
// }
//}
//}
}
|
using UnityEngine;
using System.Collections.Generic;
using System;
public enum ProjectileHitEffect { Concrete, Metal, Wood, Dirt, Sand, Blood }
public class BulletHitPoolController : MonoSingleton<BulletHitPoolController>
{
[SerializeField]
ProjectileHitEffect m_DefaultHit = ProjectileHitEffect.Concrete;
void Start()
{
InitPoolProjectileHitEffects();
}
protected override void Destroy()
{
m_RootObjs.DestroyGO();
}
private void Update()
{
for (int i = m_Actives.Count - 1; i >= 0; i--)
{
var node = m_Actives[i];
if(node.GO == null)
{
m_Actives.RemoveAt(i);
continue;
}
if (!node.GO.activeInHierarchy)
{
m_Actives.RemoveAt(i);
m_PoolProjectileHitEffects.Return(node.ID, node.GO);
}
}
}
#region Factory
const string ProjectileHitEffectsPath = "ProjectileHitEffects/";
sealed class ProjectileHitFactory : SimplePrefabFactory<int, GameObject>
{
public static readonly int CountHitEffects = Enum.GetValues(typeof(ProjectileHitEffect)).Length;
int m_Count;
string m_Path;
Transform m_RootObjs;
public ProjectileHitFactory(string loadPath, Transform rootObjs = null)
{
m_Count = CountHitEffects;
objs = new Dictionary<int, GameObject>(m_Count);
m_Path = loadPath;
m_RootObjs = rootObjs;
}
public override bool Equals(int x, int y) { return x == y; }
public override int[] GetKeys()
{
int[] ids = new int[m_Count];
for (int i = 0; i < ids.Length; i++) ids[i] = i;
return ids;
}
protected override bool CheckKey(int key)
{
return key < -1 || key >= m_Count;
}
protected override string GetPath(int key)
{
return m_Path + ((ProjectileHitEffect)key).ToString();
}
public bool CreatePoolElem(int key, out GameObject obj)
{
GameObject go;
bool res = TryCreate(key, out go);
res = go != null;
if (res)
{
var tf = go.transform;
tf.SetParent(m_RootObjs);
}
obj = res ? go : null;
return res;
}
}
ObjectsPoolByKey<int, GameObject> m_PoolProjectileHitEffects;
ProjectileHitFactory m_Factory;
Transform m_RootObjs;
void InitPoolProjectileHitEffects()
{
//#if UNITY_EDITOR
m_RootObjs = new GameObject("ROOT_HIT_EFFECTS").transform;
//rootObjs = ConstantObjects.GetGlobalObject(ConstantObjects.ROOT_HIT_EFFECTS);
//#endif
m_Factory = new ProjectileHitFactory(ProjectileHitEffectsPath, m_RootObjs);
m_PoolProjectileHitEffects = new ObjectsPoolByKey<int, GameObject>(m_Factory.CreatePoolElem, ProjectileHitFactory.CountHitEffects, m_Factory);
}
#endregion
struct Node
{
public int ID;
public GameObject GO;
public Node(int id, GameObject go)
{
ID = id;
GO = go;
}
}
List<Node> m_Actives = new List<Node>(30);
public void CreateProjectileHitEffect(int id, Vector3 pos, Quaternion rot)
{
GameObject obj;
if (m_PoolProjectileHitEffects.TryGet(id, out obj))
{
var tf = obj.transform;
tf.position = pos;
tf.rotation = rot;
if (!obj.activeSelf) obj.SetActive(true);
m_Actives.Add(new Node(id, obj));
}
#if UNITY_EDITOR
else Debug.Log("Not " + (ProjectileHitEffect)id + " type effect");
#endif
}
public static void Static_CreateProjectileHitEffect(int id, Vector3 pos, Vector3 dir)
{
if (Can) m_I.CreateProjectileHitEffect(id, pos, dir);
#if UNITY_EDITOR
else Debug.LogError(typeof(BulletHitPoolController) + " is null");
#endif
}
public static void Static_CreateProjectileHitEffect(RaycastHit hit, Vector3 dir)
{
if (Can) m_I.CreateProjectileHitEffect(hit, dir);
#if UNITY_EDITOR
else Debug.LogError(typeof(BulletHitPoolController) + " is null");
#endif
}
public void CreateProjectileHitEffect(int id, Vector3 pos, Vector3 dir)
{
CreateProjectileHitEffect(id, pos, (dir.sqrMagnitude > 1e-5f ? Quaternion.LookRotation(-dir) : Quaternion.identity));
}
public void CreateProjectileHitEffect(RaycastHit hit, Vector3 dir)
{
var HitObj = hit.transform.gameObject;
int id;
if (Enum.IsDefined(typeof(ProjectileHitEffect), HitObj.tag))
id = (int)Enum.Parse(typeof(ProjectileHitEffect), HitObj.tag);
else id = (int)m_DefaultHit;
CreateProjectileHitEffect(id, hit.point, dir);
}
}
|
using bot_backEnd.BL.Interfaces;
using bot_backEnd.DAL.Interfaces;
using bot_backEnd.Models.AppModels;
using bot_backEnd.Models.DbModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace bot_backEnd.BL
{
public class PostReportBL : IPostReportBL
{
private readonly IPostReportDAL _iPostReportDAL;
private readonly ICommentReportDAL _iCommentReportDAL;
private readonly IPostBL _iPostBL;
public PostReportBL(IPostReportDAL iPostReportDAL, ICommentReportDAL iCommentReportDAL, IPostBL iPostBL)
{
_iPostReportDAL = iPostReportDAL;
_iCommentReportDAL = iCommentReportDAL;
_iPostBL = iPostBL;
}
public PostReport AddPostReport(PostReport report)
{
return _iPostReportDAL.AddPostReport(report).Result.Value;
}
public List<PostReport> GetAllPostReports()
{
return _iPostReportDAL.GetAllPostReports().Result.Value;
}
public List<AppReport> GetAllAppReports()
{
var _postReports = this.GetAllPostReports();
var _commentReports = _iCommentReportDAL.GetAllCommentReports();
List<AppReport> reportList = new List<AppReport>();
foreach (var item in _postReports)
{
AppReport appReport = new AppReport
{
Id = item.Id,
CommentID = null,
PostID = item.PostID,
ReportedUserID = item.ReportedUserID,
SenderID = item.SenderID,
Date = item.Date,
Read = item.Read,
Text = item.Text,
ReportedUserFullName = item.ReportedUser.FirstName + " " + item.ReportedUser.LastName,
SenderFullName = item.Sender.FirstName + " " + item.Sender.LastName,
Post = _iPostBL.GetAppPostByID(item.PostID, item.SenderID)
};
reportList.Add(appReport);
}
foreach (var item in _commentReports.Result.Value)
{
AppReport appReport = new AppReport
{
Id = item.Id,
CommentID = item.CommentID,
PostID = item.PostID,
ReportedUserID = item.ReportedUserID,
SenderID = item.SenderID,
Date = item.Date,
Read = item.Read,
Text = item.Text,
ReportedUserFullName = item.ReportedUser.FirstName + " " + item.ReportedUser.LastName,
SenderFullName = item.Sender.FirstName + " " + item.Sender.LastName,
Post = _iPostBL.GetAppPostByID(item.PostID, item.SenderID),
CommentText = item.Comment.Text
};
reportList.Add(appReport);
}
return reportList;
}
public bool MarkPostReportAsRead(int reportID)
{
return _iPostReportDAL.MarkPostReportAsRead(reportID).Result.Value;
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
#endregion
namespace DotNetNuke.Services.Analytics.Config
{
[Serializable]
public class AnalyticsRule
{
private string _label;
private int _roleId;
private int _tabId;
public int RoleId
{
get
{
return _roleId;
}
set
{
_roleId = value;
}
}
public int TabId
{
get
{
return _tabId;
}
set
{
_tabId = value;
}
}
public string Label
{
get
{
return _label;
}
set
{
_label = value;
}
}
public string Value { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PostingNews.Models
{
public class MockRepository : IPostRepository
{
public List<Post> list { get; set; }
public MockRepository()
{
if(list == null)
{
InitializePosts();
}
}
void InitializePosts()
{
list = new List<Post>();
list.Add(new Post
{
Id = 1,
Title = "Why Aren't There C Conferences?",
URL = "https://nullprogram.com/blog/2018/11/21/",
Description = "Most widely-used programming languages have at least one regular conference dedicated to discussing it.",
DateAdded = new DateTime(2018, 11, 22),
User = "alma"
});
list.Add(new Post
{
Id = 2,
Title = "Why Aren't There C Conferences?.2",
URL = "https://nullprogram.com/blog/2018/11/21/",
Description = "Most widely-used programming languages have at least one regular conference dedicated to discussing it.",
DateAdded = new DateTime(2019, 11, 22),
User = "alma"
});
}
public IEnumerable<Post> GetAllPosts()
{
return list.AsEnumerable();
//throw new NotImplementedException();
}
public Post GetPostById(int postId)
{
foreach (Post post in list)
{
if (post.Id == postId)
{
return post;
}
}
return null;
//throw new NotImplementedException();
}
public void AddNewPost(Post post)
{
throw new NotImplementedException();
}
}
}
|
// Đồng Duy Tiến - 20194381
namespace DTO
{
/// <summary>
/// Class trừu tượng mô tả 1 gian hàng nói chung
/// </summary>
public abstract class GianHangDTO
{
private string _maGianHang;
/// <summary>
/// Mã định danh cho mỗi gian hàng, không rỗng và có độ dài không nhỏ hơn 5.
/// </summary>
public string MaGianHang
{
get => _maGianHang;
set { if (!string.IsNullOrEmpty(value) && value.Length <= 5) _maGianHang = value; }
}
private double _dienTich = 5.0;
/// <summary>
/// Diện tích của gian hàng, tính theo đơn vị m2.
/// Mặc định và nhỏ nhất là 5.0 m2.
/// </summary>
public double DienTich
{
get => _dienTich;
set { if (value >= 5.0) _dienTich = value; }
}
private string _viTriGianHang;
/// <summary>
/// Vị trí của gian hàng trong khu trưng bày.
/// Quy cách : tầng + vị trí tại tầng đó.
/// Ví dụ : tầng 1, vị trí số 1 thì vị trí là 101
/// </summary>
public string ViTriGianHang
{
get => _viTriGianHang;
set { if (!string.IsNullOrEmpty(value)) _viTriGianHang = value; }
}
private bool _tinhTrangThue = false;
/// <summary>
/// Tình trạng thuê/không được thuê của gian hàng.
/// Thuê = true, không được thuê = false.
/// </summary>
public bool TinhTrangThue
{
get => _tinhTrangThue;
set { _tinhTrangThue = value; }
}
/// <summary>
/// Phương thức khởi tạo của class
/// </summary>
/// <param name="maGianHang">Mã gian hàng</param>
/// <param name="dienTich">Diện tích gian hàng</param>
/// <param name="viTriGianHang">Vị trí gian hàng</param>
/// <param name="tinhTrangThue">Tình trạng thuê của gian hàng</param>
public GianHangDTO(string maGianHang, double dienTich, string viTriGianHang, bool tinhTrangThue)
{
MaGianHang = maGianHang;
DienTich = dienTich;
ViTriGianHang = viTriGianHang;
TinhTrangThue = tinhTrangThue;
}
/// <summary>
/// Phương thức trừu tượng tính chi phí thuê gian hàng theo số ngày thuê
/// </summary>
/// <param name="soNgayThue">Số ngày thuê gian hàng</param>
/// <returns>Chi phí thuê gian hàng</returns>
public abstract decimal TinhChiPhi(int soNgayThue);
}
}
|
using UnityEngine;
using System.Collections;
namespace Minigame1
{
public class Resource : MonoBehaviour
{
#region variables
/// <summary>
/// тип инструмента
/// </summary>
public Minigame1_ResourceType type;
/// <summary>
/// Трансформ тени ресурса
/// </summary>
public Transform shadowTransform;
#endregion
/// <summary>
/// Нажатие на ресурс
/// </summary>
public void Click()
{
MiniGame1_Manager.instance.WasClickResource(this);
}
/// <summary>
/// Показывает тень под ресурсом
/// </summary>
public void ShowShadow()
{
if (shadowTransform != null)
shadowTransform.gameObject.SetActive(true);
}
/// <summary>
/// Скрывает тень под ресурсом
/// </summary>
public void HideShadow()
{
if (shadowTransform != null)
shadowTransform.gameObject.SetActive(false);
}
}
public enum Minigame1_ResourceType { Null, Paint, Slate, Tube, Glass, Putty }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ParticleSystem
{
public class ChickenParticleEmitter : ChaoticParticleEmitter
{
public ChickenParticleEmitter(MatrixCoords position, MatrixCoords speed, Random randomGenerator)
:base(position, speed, randomGenerator)
{
}
protected override Particle GetNewParticle(MatrixCoords position, MatrixCoords speed)
{
return new ChickenParticle(position, speed, this.randomGenerator);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RSMS
{
public partial class UserAddDlg : MySubDialogBase
{
private string[] roleIdList;
public void on_editCallBacAction(object o, myHelper.OPEventArgs ea)
{
if (ea.param.Length > 0) {
roleIdList = new string[ea.param.Length];
for (int i = 0, m = roleIdList.Length; i < m; i++)
roleIdList[i] = ea.param[i];
}
}
public UserAddDlg()
{
InitializeComponent();
}
private void UserAddDlg_Load(object sender, EventArgs e)
{
if (roleIdList != null)
{
DataTable dt = myHelper.getDataTable("select cUserId,cDescInfo,bFlag from Users where cUserId not in("+"SELECT [Users_cUserId] FROM [RolesUsers] where [Roles_cRoleId]='"+roleIdList[0]+"'"+") order by cUserId");
myHelper.loadDataToGridView(dt, this.infoList);
}
else
{
myHelper.emsg("提示", "获取角色编码异常!!");
Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (roleIdList != null)
{
if (infoList.SelectedRows.Count > 0)
{
string sqlExe = "";
string addpersonlog = "";
string split = "";
for (int i = 0, m = infoList.SelectedRows.Count; i < m; i++) {
sqlExe += "insert into RolesUsers([Roles_cRoleId],[Users_cUserId]) values('" + roleIdList[0] + "','" + infoList.SelectedRows[i].Cells[0].Value.ToString() + "') ;";
addpersonlog += split+infoList.SelectedRows[i].Cells[0].Value.ToString();
split = ",";
}
if (myHelper.update(sqlExe) <= 0)
{
OpLog("增加", "失败", "增加操作员(" + addpersonlog + ")至角色" + roleIdList[0]);
myHelper.emsg("错误", "添加操作异常!!");
}
else
{
OpLog("增加", "成功", "增加操作员("+addpersonlog+")至角色" + roleIdList[0]);
Close();
}
}
else myHelper.emsg("提示", "请至少选一个操作员!!");
}
else
{
myHelper.emsg("提示", "获取角色编码异常!!");
Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
}
|
using HangoutsDbLibrary.Data;
using HangoutsDbLibrary.Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace HangoutsDbLibrary.Repository
{
public class UnitOfWork : IDisposable
{
private HangoutsContext context;
private InterfaceRepository<User> userRepository;
private InterfaceRepository<Group> groupRepository;
private InterfaceRepository<UserGroup> userGroupRepository;
private InterfaceRepository<GroupAdmin> groupAdminRepository;
private InterfaceRepository<Interest> interestRepository;
private InterfaceRepository<Activity> activityRepository;
private InterfaceRepository<GroupActivity> groupActivityRepository;
private InterfaceRepository<Location> locationRepository;
private InterfaceRepository<Plan> planRepository;
private bool disposed = false;
public UnitOfWork(HangoutsContext context)
{
this.context = context;
}
public InterfaceRepository<GroupActivity> GroupActivityRepository
{
get
{
if (this.groupActivityRepository == null)
{
this.groupActivityRepository = new AbstractRepository<GroupActivity>(context);
}
return groupActivityRepository;
}
}
public InterfaceRepository<Location> LocationRepository
{
get
{
if (this.locationRepository == null)
{
this.locationRepository = new AbstractRepository<Location>(context);
}
return locationRepository;
}
}
public InterfaceRepository<Activity> ActivityRepository
{
get
{
if (this.activityRepository == null)
{
this.activityRepository = new AbstractRepository<Activity>(context);
}
return activityRepository;
}
}
public InterfaceRepository<User> UserRepository
{
get
{
if(this.userRepository == null)
{
this.userRepository = new AbstractRepository<User>(context);
}
return userRepository;
}
}
public InterfaceRepository<UserGroup> UserGroupRepository
{
get
{
if (this.userGroupRepository == null)
{
this.userGroupRepository = new AbstractRepository<UserGroup>(context);
}
return userGroupRepository;
}
}
public InterfaceRepository<Interest> InterestRepository
{
get
{
if (this.interestRepository == null)
{
this.interestRepository = new AbstractRepository<Interest>(context);
}
return interestRepository;
}
}
public InterfaceRepository<Plan> PlanRepository
{
get
{
if (this.planRepository == null)
{
this.planRepository = new AbstractRepository<Plan>(context);
}
return planRepository;
}
}
public InterfaceRepository<Group> GroupRepository
{
get
{
if (this.groupRepository == null)
{
this.groupRepository = new AbstractRepository<Group>(context);
}
return groupRepository;
}
}
public InterfaceRepository<GroupAdmin> GroupAdminRepository
{
get
{
if (this.groupAdminRepository == null)
{
this.groupAdminRepository = new AbstractRepository<GroupAdmin>(context);
}
return groupAdminRepository;
}
}
public void save()
{
context.SaveChanges();
}
public void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
this.context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainBtnsManager : MonoBehaviour
{
public MainSoundSrc Ms;
public GameObject RankingUI;
public void clickplaybtn()
{
Ms.startsound.Play();
StartCoroutine("goplay");
}
public void clickranking()
{
Ms.clicksound.Play();
RankingUI.SetActive(!RankingUI.activeSelf);
}
IEnumerator goplay()
{
yield return new WaitForSecondsRealtime(2f);
SceneManager.LoadScene("PlayScene");
}
}
|
using System.Collections;
using System.Collections.Generic;
using Photon.Pun;
using UnityEngine;
public class NotConnected : MainApplicationReference
{
string gameVersion = "1";
MainApplication application;
string playerName = "";
bool connecting = false;
public override void Init(MainApplication application)
{
this.application = application;
}
void OnGUI()
{
int y = 10;
GUI.Label(new Rect(10, y += 25, 200, 20), "RPS!");
GUI.Label(new Rect(10, y += 25, 200, 20), "User name:");
playerName = GUI.TextField(new Rect(10, y += 25, 200, 20), playerName, 25);
GUI.enabled = !connecting;
if (GUI.Button(new Rect(10, y += 25, 200, 20), "Login"))
{
Connect();
connecting = true;
}
if (connecting)
{
GUI.Label(new Rect(10, y += 25, 200, 20), "Connecting...");
}
GUI.enabled = true;
}
void Connect()
{
PhotonNetwork.NickName = playerName;
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.GameVersion = gameVersion;
}
public override void OnConnectedToMaster()
{
application.UpdateState(MainApplication.State.kConnected);
}
}
|
using Assets.Scripts.RobinsonCrusoe_Game.GameAttributes.Food;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UpdatePermantentFood : MonoBehaviour
{
public Text amountOfFood;
// Start is called before the first frame update
void Start()
{
FoodStorage.AmountOfPermanentFoodChanged += OnPermanentFoodChanged;
}
private void OnPermanentFoodChanged(object sender, System.EventArgs e)
{
int amount = (int)sender;
amountOfFood.text = amount.ToString();
}
}
|
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
lblName.Text = "Welcome : " +
" " + Session["name"].ToString();
}
catch (Exception ex)
{
}
}
//protected void Butsignout_Click(object sender, EventArgs e)
//{
// Session.Clear();
// Session["Authenticated"] = 0;
// Session["name"] = "Guest";
// Session["UserID"] = 0;
// Response.Redirect("Index.aspx");
//}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RedirectActionResult.cs" company="">
//
// </copyright>
// <summary>
// The redirect action result.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ConsoleWebServer.Framework.Actions
{
using System.Collections.Generic;
using System.Net;
using ConsoleWebServer.Framework.Http;
/// <summary>
/// The redirect action result.
/// </summary>
public class RedirectActionResult : IActionResult
{
/// <summary>
/// The model.
/// </summary>
private readonly object model;
/// <summary>
/// Initializes a new instance of the <see cref="RedirectActionResult"/> class.
/// </summary>
/// <param name="request">
/// The request.
/// </param>
/// <param name="model">
/// The model.
/// </param>
public RedirectActionResult(IHttpRequest request, object model)
{
this.model = model;
this.Request = request;
this.ResponseHeaders = new List<KeyValuePair<string, string>>();
}
/// <summary>
/// Gets the request.
/// </summary>
public IHttpRequest Request { get; }
/// <summary>
/// Gets the response headers.
/// </summary>
public List<KeyValuePair<string, string>> ResponseHeaders { get; }
/// <summary>
/// The get response.
/// </summary>
/// <returns>
/// The <see cref="HttpResponse" />.
/// </returns>
public HttpResponse GetResponse()
{
var response = new HttpResponse(this.Request.ProtocolVersion, HttpStatusCode.Redirect, string.Empty);
foreach (var responseHeader in this.ResponseHeaders)
{
response.AddHeader(responseHeader.Key, responseHeader.Value);
}
return response;
}
}
} |
using GlobalDevelopment.Interfaces;
namespace GlobalDevelopment.Models
{
public class LinkedInOAuth : ILinkedInOauth
{
public string AccessToken { get; set; }
public string PageID { get; set; }
public string AppSecret { get; set; }
public string AppId { get; set; }
public string PermissionScope { get; set; }
public string State { get; set; }
public string Url { get; set; }
public string UserID { get; set; }
public string Email { get; set; }
public string ResponseType { get; set; }
public string UserName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using HelloBug.BLL;
using HelloBug.Models;
using HelloBug.Common;
namespace HelloBug.Controllers
{
public class AccountController : Controller
{
[LoginCheckFilter(IsCheck=false)]
public ActionResult Login()
{
return View();
}
[HttpPost]
[LoginCheckFilter(IsCheck = false)]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
UserInfoBLL userInfoBLL = new UserInfoBLL();
if (userInfoBLL.Exists(model.UserName, model.Password))
{
Session["User"] = userInfoBLL.GetModel(model.UserName);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "提供的用户名或密码不正确。");
return View(model);
}
}
else
{
return View(model);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ivi.Visa.Interop;
using System.Windows.Forms;
namespace LibEqmtDriver.SG
{
public class E8257D : IISiggen
{
public static string ClassName = "E8257D Siggen Class";
private FormattedIO488 _myVisaSg = new FormattedIO488();
public string IoAddress;
/// <summary>
/// Parsing Equpment Address
/// </summary>
public string Address
{
get
{
return IoAddress;
}
set
{
IoAddress = value;
}
}
public FormattedIO488 ParseIo
{
get
{
return _myVisaSg;
}
set
{
_myVisaSg = ParseIo;
}
}
public void OpenIo()
{
if (IoAddress.Length > 3)
{
try
{
ResourceManager mgr = new ResourceManager();
_myVisaSg.IO = (IMessage)mgr.Open(IoAddress, AccessMode.NO_LOCK, 2000, "");
}
catch (SystemException ex)
{
MessageBox.Show("Class Name: " + ClassName + "\nParameters: OpenIO" + "\n\nErrorDesciption: \n"
+ ex, "Error found in Class " + ClassName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
_myVisaSg.IO = null;
return;
}
}
}
public E8257D(string ioAddress)
{
Address = ioAddress;
OpenIo();
}
~E8257D() { }
#region iSeggen
void IISiggen.Initialize()
{
try
{
_myVisaSg.WriteString("*IDN?", true);
string result = _myVisaSg.ReadString();
}
catch (Exception ex)
{
throw new Exception("EquipE8257D: Initialization -> " + ex.Message);
}
}
void IISiggen.Reset()
{
try
{
_myVisaSg.WriteString("*CLS; *RST", true);
}
catch (Exception ex)
{
throw new Exception("EquipE8257D: RESET -> " + ex.Message);
}
}
void IISiggen.EnableRf(InstrOutput onoff)
{
_myVisaSg.WriteString("POW:STAT " + onoff, true);
}
void IISiggen.EnableModulation(InstrOutput onoff)
{
_myVisaSg.WriteString("OUTP:MOD " + onoff, true);
}
void IISiggen.SetAmplitude(float dBm)
{
_myVisaSg.WriteString("POW:LEV:IMM:AMPL " + dBm.ToString(), true);
}
void IISiggen.SetFreq(double mHz)
{
_myVisaSg.WriteString("FREQ:FIX " + mHz.ToString() + "MHz", true);
}
void IISiggen.SetPowerMode(N5182PowerMode mode)
{
_myVisaSg.WriteString(":POW:MODE " + mode.ToString(), true);
}
void IISiggen.SetFreqMode(N5182FrequencyMode mode)
{
_myVisaSg.WriteString(":FREQ:MODE " + mode.ToString(), true);
}
void IISiggen.MOD_FORMAT_WITH_LOADING_CHECK(string strWaveform, string strWaveformName, bool waveformInitalLoad)
{
//Not applicable
}
void IISiggen.SELECT_WAVEFORM(N5182AWaveformMode mode)
{
//Not applicable
}
void IISiggen.SET_LIST_TYPE(N5182ListType mode)
{
//myVisaSg.WriteString(":LIST:TYPE " + _mode.ToString(), true);
}
void IISiggen.SET_LIST_MODE(InstrMode mode)
{
//myVisaSg.WriteString(":LIST:MODE " + _mode.ToString(), true);
}
void IISiggen.SET_LIST_TRIG_SOURCE(N5182TrigType mode)
{
//myVisaSg.WriteString(":LIST:TRIG:SOUR " + _mode.ToString(), true);
}
void IISiggen.SET_CONT_SWEEP(InstrOutput onoff) // Set up for single sweep
{
_myVisaSg.WriteString(":INIT:CONT " + onoff.ToString(), true);
}
void IISiggen.SET_START_FREQUENCY(double mHz)
{
_myVisaSg.WriteString("FREQ:START " + mHz.ToString() + "MHz", true);
}
void IISiggen.SET_STOP_FREQUENCY(float mHz)
{
_myVisaSg.WriteString("FREQ:STOP " + mHz.ToString() + "MHz", true);
}
void IISiggen.SET_TRIG_TIMERPERIOD(double ms)
{
double second = ms / 1e3;
_myVisaSg.WriteString("SWE:TIME " + second, true);
}
void IISiggen.SET_SWEEP_POINT(int points)
{
_myVisaSg.WriteString("SWE:POIN " + points.ToString(), true);
}
void IISiggen.SINGLE_SWEEP()
{
_myVisaSg.WriteString("INIT:IMM", true);
}
void IISiggen.SET_SWEEP_PARAM(int points, double ms, double startFreqMHz, double stopFreqMHz)
{
double totalSweepT = ms * points; //calculate dwelltime(mS) per point to total sweepTime(mS)
_myVisaSg.WriteString("FREQ:START " + startFreqMHz.ToString() + "MHz", true);
_myVisaSg.WriteString("FREQ:STOP " + stopFreqMHz.ToString() + "MHz", true);
_myVisaSg.WriteString("SWE:POIN " + points.ToString(), true);
_myVisaSg.WriteString("SWE:TIME " + totalSweepT.ToString() + "ms", true);
}
bool IISiggen.OPERATION_COMPLETE()
{
try
{
bool complete = false;
double dummy = -99;
do
{
dummy = WRITE_READ_DOUBLE("*OPC?");
} while (dummy == 0);
complete = true;
return complete;
}
catch (Exception ex)
{
throw new Exception("E8257D: OPERATION_COMPLETE -> " + ex.Message);
}
}
#endregion
public string QUERY_ERROR()
{
string errMsg, tempErrMsg = "";
int errNum;
try
{
errMsg = WRITE_READ_STRING("SYST:ERR?");
tempErrMsg = errMsg;
// Remove the error number
errNum = Convert.ToInt16(errMsg.Remove((errMsg.IndexOf(",")),
(errMsg.Length) - (errMsg.IndexOf(","))));
if (errNum != 0)
{
while (errNum != 0)
{
tempErrMsg = errMsg;
// Check for next error(s)
errMsg = WRITE_READ_STRING("SYST:ERR?");
// Remove the error number
errNum = Convert.ToInt16(errMsg.Remove((errMsg.IndexOf(",")),
(errMsg.Length) - (errMsg.IndexOf(","))));
}
}
return tempErrMsg;
}
catch (Exception ex)
{
throw new Exception("EquipE8257D: QUERY_ERROR --> " + ex.Message);
}
}
#region generic READ and WRITE function
public float WRITE_READ_SINGLE(string cmd)
{
_myVisaSg.WriteString(cmd, true);
return Convert.ToSingle(_myVisaSg.ReadString());
}
public float[] READ_IEEEBlock(IEEEBinaryType type)
{
return (float[])_myVisaSg.ReadIEEEBlock(type, true, true);
}
public float[] WRITE_READ_IEEEBlock(string cmd, IEEEBinaryType type)
{
_myVisaSg.WriteString(cmd, true);
return (float[])_myVisaSg.ReadIEEEBlock(type, true, true);
}
public void Write(string cmd)
{
_myVisaSg.WriteString(cmd, true);
}
public double WRITE_READ_DOUBLE(string cmd)
{
_myVisaSg.WriteString(cmd, true);
return Convert.ToDouble(_myVisaSg.ReadString());
}
public string WRITE_READ_STRING(string cmd)
{
_myVisaSg.WriteString(cmd, true);
return _myVisaSg.ReadString();
}
public void WriteInt16Array(string command, Int16[] data)
{
_myVisaSg.WriteIEEEBlock(command, data, true);
}
public void WriteByteArray(string command, byte[] data)
{
_myVisaSg.WriteIEEEBlock(command, data, true);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace Jieshai
{
public class LogStopwatch: IDisposable
{
public LogStopwatch(string title, string message)
{
this.Watch = new Stopwatch();
this.LogSeconds = 2;
this.Title = title;
this.Message = message;
}
public Stopwatch Watch { set; get; }
public double TotalSeconds
{
get
{
return this.Watch.Elapsed.TotalSeconds;
}
}
public double TotalMilliseconds
{
get
{
return this.Watch.Elapsed.TotalMilliseconds;
}
}
public int LogSeconds { set; get; }
public string Message { set; get; }
public string Title { set; get; }
public bool Overtime { set; get; }
public void Start()
{
this.Watch.Start();
this.OnStarted();
}
protected virtual void OnStarted()
{
}
public void Start(int logSeconds)
{
this.LogSeconds = logSeconds;
this.Start();
}
public void Stop()
{
try
{
this.Watch.Stop();
if (this.Watch.Elapsed.TotalSeconds >= this.LogSeconds)
{
EIMLog.Logger.Warn(string.Format("{0} 加载时间: {1} {2}", this.Title, this.Watch.Elapsed.TotalSeconds, this.Message));
this.Overtime = true;
}
else
{
this.Overtime = false;
}
this.OnStoped();
}
catch(Exception ex)
{
EIMLog.Logger.Error(ex.Message, ex);
}
}
protected virtual void OnStoped()
{
}
public static LogStopwatch StartNew(string title, string message, int logSeconds)
{
LogStopwatch watch = new LogStopwatch(title, message);
watch.Start(logSeconds);
return watch;
}
public static LogStopwatch StartNew(string title, string message)
{
LogStopwatch watch = new LogStopwatch(title, message);
watch.Start();
return watch;
}
public void Dispose()
{
this.Stop();
}
}
}
|
namespace ToDoApp.Db.Interfaces
{
public interface ISearchable
{
public string Title { get; }
}
}
|
using System;
using System.Threading.Tasks;
using API.Controllers.Resources;
using Application;
using Application.User;
using Domain;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
public class UsersController : BaseController
{
[AllowAnonymous]
[HttpGet("conn-test")]
public ActionResult Test()
{
return Ok(Guid.NewGuid());
}
[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult<UserResource>> Login(Login.Query query)
{
return await Mediator.Send(query);
}
[AllowAnonymous]
[HttpPost("register")]
public async Task<ActionResult<UserResource>> Register(Register.Command command)
{
return await Mediator.Send(command);
}
[HttpGet("current")]
public async Task<ActionResult<UserResource>> CurrentUser()
{
return await Mediator.Send(new CurrentUser.Query());
}
[HttpGet]
public async Task<ActionResult<QueryObject<UserResource>>> List([FromQuery] PagingParameterModel pagingModel)
{
return await Mediator.Send(new List.Query { Page = pagingModel.PageNumber, Size = pagingModel.PageSize });
}
[HttpPost]
public async Task<ActionResult<Unit>> Create(Create.Command command)
{
return await Mediator.Send(command);
}
[HttpPut("{userName}")]
public async Task<ActionResult<Unit>> Edit(string userName, Edit.Command command)
{
command.UserName = userName;
return await Mediator.Send(command);
}
[HttpDelete("{userName}")]
public async Task<ActionResult<Unit>> Delete(string userName)
{
return await Mediator.Send(new Delete.Command { UserName = userName });
}
}
} |
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using CustomerFinderCognitiveServices.Models;
using Microsoft.Rest;
using Newtonsoft.Json.Linq;
namespace CustomerFinderCognitiveServices.Models
{
public partial class MultiLanguageBatchInputV2
{
private IList<MultiLanguageInputV2> _documents;
/// <summary>
/// Optional.
/// </summary>
public IList<MultiLanguageInputV2> Documents
{
get { return this._documents; }
set { this._documents = value; }
}
/// <summary>
/// Initializes a new instance of the MultiLanguageBatchInputV2 class.
/// </summary>
public MultiLanguageBatchInputV2()
{
this.Documents = new LazyList<MultiLanguageInputV2>();
}
/// <summary>
/// Serialize the object
/// </summary>
/// <returns>
/// Returns the json model for the type MultiLanguageBatchInputV2
/// </returns>
public virtual JToken SerializeJson(JToken outputObject)
{
if (outputObject == null)
{
outputObject = new JObject();
}
JArray documentsSequence = null;
if (this.Documents != null)
{
if (this.Documents is ILazyCollection<MultiLanguageInputV2> == false || ((ILazyCollection<MultiLanguageInputV2>)this.Documents).IsInitialized)
{
documentsSequence = new JArray();
outputObject["documents"] = documentsSequence;
foreach (MultiLanguageInputV2 documentsItem in this.Documents)
{
if (documentsItem != null)
{
documentsSequence.Add(documentsItem.SerializeJson(null));
}
}
}
}
return outputObject;
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
// ReSharper disable InconsistentNaming
namespace Dnn.ExportImport.Dto.Workflow
{
public class ExportWorkflow : BasicExportImportDto
{
public int WorkflowID { get; set; }
public string WorkflowName { get; set; }
public string Description { get; set; }
public bool IsDeleted { get; set; }
public bool StartAfterCreating { get; set; }
public bool StartAfterEditing { get; set; }
public bool DispositionEnabled { get; set; }
public bool IsSystem { get; set; }
public string WorkflowKey { get; set; }
public bool IsDefault { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Evpro.Data.Infrastructure;
using Evpro.Domain;
using Evpro.Domain.Entities;
using Evpro.Service.Pattern;
namespace Evpro.Service
{
public class TaskService : MyServiceGeneric<task>, ITaskService
{
static private DataBaseFactory dbFactory = new DataBaseFactory();
static private IUnitOfWork ut = new UnitOfWork(dbFactory);
public TaskService() : base(ut)
{
ut = new UnitOfWork(dbFactory);
}
public TaskService(IUnitOfWork itw) : base(itw)
{
}
public float Counttacheeevent(int id)
{
float res = GetMany(l => l.idEvent == id).Count();
return res;
}
public float EventProgressDone(int id, float total)
{
float tachedone = GetMany(l => l.idEvent == id && l.status == "Done").Count();
float resu = (tachedone / total) * 100;
return resu;
}
public float EventProgressDoing(int id, float total)
{
float tachedoing = GetMany(l => l.idEvent == id && l.status == "Doing").Count();
float res = (tachedoing / total) * 100;
return res;
}
public float EventProgressToDo(int id, float total)
{
float tacheToDo = GetMany(l => l.idEvent == id && l.status == "ToDo").Count();
float resultat = (tacheToDo / total) * 100;
return resultat;
}
public float AllDone()
{
float total = GetMany().Count();
float tacheDone = GetMany(l=>l.status=="Done").Count();
float resultat= (tacheDone / total) * 100;
return resultat;
}
public float AllDoing()
{
float total = GetMany().Count();
float tacheDone = GetMany(l => l.status == "Doing").Count();
float resultat = (tacheDone / total) * 100;
return resultat;
}
public float AllToDo()
{
float total = GetMany().Count();
float tacheDone = GetMany(l => l.status == "ToDo").Count();
float resultat = (tacheDone / total) * 100;
return resultat;
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TechnologyAppLineCriteriaTest.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Entities;
using CGI.Reflex.Core.Queries;
using CGI.Reflex.Core.Queries.Series;
using FluentAssertions;
using NUnit.Framework;
namespace CGI.Reflex.Core.Tests.Queries.Series.Criteria
{
public class TechnologyAppLineCriteriaTest : BaseCriteriaTest
{
[Test]
public void It_should_work_with_line_only_and_all_applications()
{
var rootTechno = Factories.Technology.Save();
var parentTechno1 = Factories.Technology.Save(t => t.Parent = rootTechno);
var parentTechno2 = Factories.Technology.Save(t => t.Parent = rootTechno);
var appTechno1 = Factories.Technology.Save(t => t.Parent = parentTechno1);
var appTechno2 = Factories.Technology.Save(t => t.Parent = parentTechno1);
var appTechno3 = Factories.Technology.Save(t => t.Parent = parentTechno2);
for (var i = 0; i < 3; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = NonActiveDomainValue; });
app.AddTechnologyLink(appTechno1);
app.AddTechnologyLink(appTechno3);
}
for (var i = 0; i < 5; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = ActiveDomainValue; });
app.AddTechnologyLink(appTechno2);
}
for (var i = 0; i < 1; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = ActiveDomainValue; });
app.AddTechnologyLink(appTechno3);
}
NHSession.Flush();
NHSession.Clear();
var result = new ApplicationSeries { LineCriteria = "Technology" }.Execute();
result.Columns.Should().HaveCount(0);
result.Lines.Should().HaveCount(3);
result.Lines[0].GetCriteria<Technology>().Name.Should().Be(appTechno1.Name);
result.Lines[0].GetCount(0).Should().Be(3);
result.Lines[0].Total.Should().Be(3);
result.Lines[1].GetCriteria<Technology>().Name.Should().Be(appTechno2.Name);
result.Lines[1].GetCount(0).Should().Be(5);
result.Lines[1].Total.Should().Be(5);
result.Lines[2].GetCriteria<Technology>().Name.Should().Be(appTechno3.Name);
result.Lines[2].GetCount(0).Should().Be(4);
result.Lines[2].Total.Should().Be(4);
result.GetTotalCount(0).Should().Be(12);
result.GetGrandTotal().Should().Be(12);
// Verifying hierarchy
result.AreLinesHierarchical.Should().BeTrue();
var rootNodes = result.GetRootNodes();
rootNodes.Should().HaveCount(1);
var rootNode = rootNodes.First();
rootNode.GetCriteria<Technology>().Id.Should().Be(rootTechno.Id);
rootNode.Total.Should().Be(12);
rootNode.Children.Should().HaveCount(2);
var parentNode1 = rootNode.Children.Where(node => node.GetCriteria<Technology>().Id == parentTechno1.Id).First();
parentNode1.Total.Should().Be(8);
parentNode1.Children.Should().HaveCount(2);
var node1 = parentNode1.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno1.Id).First();
node1.Total.Should().Be(3);
node1.Children.Should().HaveCount(0);
var node2 = parentNode1.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno2.Id).First();
node2.Total.Should().Be(5);
node2.Children.Should().HaveCount(0);
var parentNode2 = rootNode.Children.Where(node => node.GetCriteria<Technology>().Id == parentTechno2.Id).First();
parentNode2.Total.Should().Be(4);
parentNode2.Children.Should().HaveCount(1);
var node3 = parentNode2.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno3.Id).First();
node3.Total.Should().Be(4);
node3.Children.Should().HaveCount(0);
}
[Test]
public void It_should_work_with_line_only_and_only_active_applications()
{
var rootTechno = Factories.Technology.Save();
var parentTechno1 = Factories.Technology.Save(t => t.Parent = rootTechno);
var parentTechno2 = Factories.Technology.Save(t => t.Parent = rootTechno);
var appTechno1 = Factories.Technology.Save(t => t.Parent = parentTechno1);
var appTechno2 = Factories.Technology.Save(t => t.Parent = parentTechno1);
var appTechno3 = Factories.Technology.Save(t => t.Parent = parentTechno2);
for (var i = 0; i < 3; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = NonActiveDomainValue; });
app.AddTechnologyLink(appTechno1);
app.AddTechnologyLink(appTechno3);
}
for (var i = 0; i < 5; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = ActiveDomainValue; });
app.AddTechnologyLink(appTechno2);
}
for (var i = 0; i < 1; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = ActiveDomainValue; });
app.AddTechnologyLink(appTechno3);
}
NHSession.Flush();
NHSession.Clear();
var result = new ApplicationSeries { LineCriteria = "Technology", OnlyActiveApplications = true }.Execute();
result.Columns.Should().HaveCount(0);
result.Lines.Should().HaveCount(3);
result.Lines[0].GetCriteria<Technology>().Name.Should().Be(appTechno1.Name);
result.Lines[0].GetCount(0).Should().Be(0);
result.Lines[0].Total.Should().Be(0);
result.Lines[1].GetCriteria<Technology>().Name.Should().Be(appTechno2.Name);
result.Lines[1].GetCount(0).Should().Be(5);
result.Lines[1].Total.Should().Be(5);
result.Lines[2].GetCriteria<Technology>().Name.Should().Be(appTechno3.Name);
result.Lines[2].GetCount(0).Should().Be(1);
result.Lines[2].Total.Should().Be(1);
result.GetTotalCount(0).Should().Be(6);
result.GetGrandTotal().Should().Be(6);
// Verifying hierarchy
result.AreLinesHierarchical.Should().BeTrue();
var rootNodes = result.GetRootNodes();
rootNodes.Should().HaveCount(1);
var rootNode = rootNodes.First();
rootNode.GetCriteria<Technology>().Id.Should().Be(rootTechno.Id);
rootNode.Total.Should().Be(6);
rootNode.Children.Should().HaveCount(2);
var parentNode1 = rootNode.Children.Where(node => node.GetCriteria<Technology>().Id == parentTechno1.Id).First();
parentNode1.Total.Should().Be(5);
parentNode1.Children.Should().HaveCount(2);
var node1 = parentNode1.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno1.Id).First();
node1.Total.Should().Be(0);
node1.Children.Should().HaveCount(0);
var node2 = parentNode1.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno2.Id).First();
node2.Total.Should().Be(5);
node2.Children.Should().HaveCount(0);
var parentNode2 = rootNode.Children.Where(node => node.GetCriteria<Technology>().Id == parentTechno2.Id).First();
parentNode2.Total.Should().Be(1);
parentNode2.Children.Should().HaveCount(1);
var node3 = parentNode2.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno3.Id).First();
node3.Total.Should().Be(1);
node3.Children.Should().HaveCount(0);
}
[Test]
public void It_should_work_with_columns_and_all_applications()
{
var rootTechno = Factories.Technology.Save();
var parentTechno1 = Factories.Technology.Save(t => t.Parent = rootTechno);
var appTechno1 = Factories.Technology.Save(t => t.Parent = parentTechno1);
var appTechno2 = Factories.Technology.Save(t => t.Parent = parentTechno1);
for (var i = 0; i < 7; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = ActiveDomainValue; });
app.AddTechnologyLink(appTechno1);
}
for (var i = 0; i < 6; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = NonActiveDomainValue; });
app.AddTechnologyLink(appTechno1);
}
for (var i = 0; i < 5; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = null; });
app.AddTechnologyLink(appTechno1);
}
for (var i = 0; i < 4; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = ActiveDomainValue; });
app.AddTechnologyLink(appTechno2);
}
for (var i = 0; i < 3; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = NonActiveDomainValue; });
app.AddTechnologyLink(appTechno2);
}
for (var i = 0; i < 2; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = null; });
app.AddTechnologyLink(appTechno2);
}
CleanOtherStatuses();
var result = new ApplicationSeries { LineCriteria = "Technology", ColumnCriteria = "ApplicationStatus" }.Execute();
result.Columns.Should().HaveCount(3);
result.Lines.Should().HaveCount(2);
result.Lines[0].GetCriteria<Technology>().Name.Should().Be(appTechno1.Name);
result.Lines[0].GetCount(0).Should().Be(7);
result.Lines[0].GetCount(1).Should().Be(6);
result.Lines[0].GetCount(2).Should().Be(5);
result.Lines[0].Total.Should().Be(18);
result.Lines[1].GetCriteria<Technology>().Name.Should().Be(appTechno2.Name);
result.Lines[1].GetCount(0).Should().Be(4);
result.Lines[1].GetCount(1).Should().Be(3);
result.Lines[1].GetCount(2).Should().Be(2);
result.Lines[1].Total.Should().Be(9);
result.GetTotalCount(0).Should().Be(11);
result.GetTotalCount(1).Should().Be(9);
result.GetTotalCount(2).Should().Be(7);
result.GetGrandTotal().Should().Be(27);
// Verifying hierarchy
result.AreLinesHierarchical.Should().BeTrue();
var rootNodes = result.GetRootNodes();
rootNodes.Should().HaveCount(1);
var rootNode = rootNodes.First();
rootNode.GetCriteria<Technology>().Id.Should().Be(rootTechno.Id);
rootNode.Total.Should().Be(27);
rootNode.Children.Should().HaveCount(1);
var parentNode1 = rootNode.Children.Where(node => node.GetCriteria<Technology>().Id == parentTechno1.Id).First();
parentNode1.Total.Should().Be(27);
parentNode1.Children.Should().HaveCount(2);
var node1 = parentNode1.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno1.Id).First();
node1.Total.Should().Be(18);
node1.Children.Should().HaveCount(0);
var node2 = parentNode1.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno2.Id).First();
node2.Total.Should().Be(9);
node2.Children.Should().HaveCount(0);
}
[Test]
public void It_should_work_with_columns_and_only_active_applications()
{
var rootTechno = Factories.Technology.Save();
var parentTechno1 = Factories.Technology.Save(t => t.Parent = rootTechno);
var appTechno1 = Factories.Technology.Save(t => t.Parent = parentTechno1);
var appTechno2 = Factories.Technology.Save(t => t.Parent = parentTechno1);
for (var i = 0; i < 7; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = ActiveDomainValue; });
app.AddTechnologyLink(appTechno1);
}
for (var i = 0; i < 6; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = NonActiveDomainValue; });
app.AddTechnologyLink(appTechno1);
}
for (var i = 0; i < 5; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = null; });
app.AddTechnologyLink(appTechno1);
}
for (var i = 0; i < 4; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = ActiveDomainValue; });
app.AddTechnologyLink(appTechno2);
}
for (var i = 0; i < 3; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = NonActiveDomainValue; });
app.AddTechnologyLink(appTechno2);
}
for (var i = 0; i < 2; i++)
{
var app = Factories.Application.Save(a => { a.AppInfo.Status = null; });
app.AddTechnologyLink(appTechno2);
}
CleanOtherStatuses();
var result = new ApplicationSeries { LineCriteria = "Technology", ColumnCriteria = "ApplicationStatus", OnlyActiveApplications = true }.Execute();
result.Columns.Should().HaveCount(3);
result.Lines.Should().HaveCount(2);
result.Lines[0].GetCriteria<Technology>().Name.Should().Be(appTechno1.Name);
result.Lines[0].GetCount(0).Should().Be(7);
result.Lines[0].GetCount(1).Should().Be(0);
result.Lines[0].GetCount(2).Should().Be(0);
result.Lines[0].Total.Should().Be(7);
result.Lines[1].GetCriteria<Technology>().Name.Should().Be(appTechno2.Name);
result.Lines[1].GetCount(0).Should().Be(4);
result.Lines[1].GetCount(1).Should().Be(0);
result.Lines[1].GetCount(2).Should().Be(0);
result.Lines[1].Total.Should().Be(4);
result.GetTotalCount(0).Should().Be(11);
result.GetTotalCount(1).Should().Be(0);
result.GetTotalCount(2).Should().Be(0);
result.GetGrandTotal().Should().Be(11);
// Verifying hierarchy
result.AreLinesHierarchical.Should().BeTrue();
var rootNodes = result.GetRootNodes();
rootNodes.Should().HaveCount(1);
var rootNode = rootNodes.First();
rootNode.GetCriteria<Technology>().Id.Should().Be(rootTechno.Id);
rootNode.Total.Should().Be(11);
rootNode.Children.Should().HaveCount(1);
var parentNode1 = rootNode.Children.Where(node => node.GetCriteria<Technology>().Id == parentTechno1.Id).First();
parentNode1.Total.Should().Be(11);
parentNode1.Children.Should().HaveCount(2);
var node1 = parentNode1.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno1.Id).First();
node1.Total.Should().Be(7);
node1.Children.Should().HaveCount(0);
var node2 = parentNode1.Children.Where(node => node.GetCriteria<Technology>().Id == appTechno2.Id).First();
node2.Total.Should().Be(4);
node2.Children.Should().HaveCount(0);
}
}
}
|
using System;
using FluentAssertions;
using System.Threading.Tasks;
using Xunit;
using InfluxData.Net.InfluxDb.Models;
namespace InfluxData.Net.Integration.Tests
{
[Collection("Integration")]
[Trait("Integration", "Continuous Queries")]
public class IntegrationContinuousQueries : IDisposable
{
private readonly IntegrationFixture _fixture;
public IntegrationContinuousQueries(IntegrationFixture fixture)
{
_fixture = fixture;
_fixture.TestSetup();
}
public void Dispose()
{
_fixture.TestTearDown();
}
[Fact]
public async Task CreateContinuousQuery_OnExistingMeasurement_ShouldReturnSuccess()
{
ContinuousQuery cq = _fixture.MockContinuousQuery();
var result = await _fixture.Sut.ContinuousQuery.CreateContinuousQueryAsync(cq);
result.Should().NotBeNull();
result.Success.Should().BeTrue();
// TODO: expand test to check if the item is really in the database
}
[Fact]
public void CreateContinuousQuery_OnNonExistingMeasurement_ShouldThrow()
{
}
[Fact]
public async Task DeleteContinuousQuery_OnExistingCq_ShouldReturnSuccess()
{
var cq = _fixture.MockContinuousQuery();
await _fixture.Sut.ContinuousQuery.CreateContinuousQueryAsync(cq);
var result = await _fixture.Sut.ContinuousQuery.DeleteContinuousQueryAsync(_fixture.DbName, "FakeCQ");
result.Should().NotBeNull();
result.Success.Should().BeTrue();
}
[Fact]
public async Task GetContinuousQueries_OnExistingCq_ShouldReturnCqs()
{
var cq = _fixture.MockContinuousQuery();
await _fixture.Sut.ContinuousQuery.CreateContinuousQueryAsync(cq);
var result = await _fixture.Sut.ContinuousQuery.GetContinuousQueriesAsync(_fixture.DbName);
result.Should().NotBeNull();
}
[Fact]
public async Task Backfill_OnValidBackfillObject_ShouldReturnSuccess()
{
var backfill = _fixture.MockBackfill();
var result = await _fixture.Sut.ContinuousQuery.BackfillAsync("Novaerus01", backfill);
result.Should().NotBeNull();
result.Success.Should().BeTrue();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Script
{
public class BulletPlayer : MonoBehaviour
{
[SerializeField] private int damage = 10;
public string direction = "left";
[SerializeField] private float speed;
[SerializeField] public string owner = "none";
[SerializeField] private bool onStone = false;
[SerializeField] private LayerMask stone1;
[SerializeField] private LayerMask stone2;
[SerializeField] private LayerMask stone3;
[SerializeField] private Transform stoneCheck;
[SerializeField] private float stoneCheckRadius;
//[SerializeField] private LayerMask player;
//[SerializeField] private LayerMask playerFriends;
[SerializeField] private LayerMask enemy;
private float div=10f;
public int Damage { get => damage; set => damage = value; }
// Start is called before the first frame update
void Start()
{
Destroy(this.gameObject, 5f);
}
private void FixedUpdate()
{
CheckingStone();
if (onStone)
{
Destroy(this.gameObject);
}
RaycastHit2D hit2DE = Physics2D.Raycast(transform.position, transform.up, div, enemy);
if (hit2DE.collider != null)
{
if (hit2DE.collider.CompareTag("Enemy"))
{
hit2DE.collider.GetComponent<Enemy>().TakeDamage(Damage);
Destroy(this.gameObject);
}
}
RaycastHit2D hit2DG = Physics2D.Raycast(transform.position, transform.up, div, stone1);
if (hit2DG.collider != null)
{
if (hit2DG.collider.CompareTag("Stone"))
{
hit2DG.collider.GetComponent<Stone>().Die();
Destroy(this.gameObject);
}
}
RaycastHit2D hit2DB = Physics2D.Raycast(transform.position, transform.up, div, stone1);
if (hit2DG.collider != null)
{
if (hit2DG.collider.CompareTag("BaseEnemy"))
{
hit2DG.collider.GetComponent<Stone>().Die();
Destroy(this.gameObject);
}
}
RaycastHit2D hit2Db = Physics2D.Raycast(transform.position, transform.up, div,stone3);
if (hit2Db.collider != null)
{
if (hit2Db.collider.CompareTag("BaseEnemy"))
{
hit2Db.collider.GetComponent<BaseEnemy>().TakeDamage(Damage);
Destroy(this.gameObject);
}
}
//}
}
void Update()
{
if (direction == "left")
{
transform.position += new Vector3(speed, 0, 0);
}
else if (direction == "right")
{
transform.position += new Vector3(-speed, 0, 0);
}
else if (direction == "up")
{
transform.position += new Vector3(0, speed, 0);
}
else if (direction == "down")
{
transform.position += new Vector3(0, -speed, 0);
}
}
void CheckingStone()
{
onStone = Physics2D.OverlapCircle(stoneCheck.position, stoneCheckRadius, stone2);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public Question[] questions;
private static List<Question> unansweredQuestions;
private Question currentQuestion;
[SerializeField]
private TMP_Text factText;
[SerializeField]
private float timeBtwQuestions = 1f;
//[SerializeField]
//private TMP_Text trueAnswerText;
//[SerializeField]
//private TMP_Text falseAnswerText;
//[SerializeField]
//private Animator anim;
public int scoreGameOne;
public int mistakesGameOne;
public int ctr;
// Start is called before the first frame update
void Start()
{
if(unansweredQuestions == null || unansweredQuestions.Count == 0)
{
unansweredQuestions = questions.ToList<Question>();
}
SetCurrentQuestion();
}
// Update is called once per frame
void Update()
{
}
void SetCurrentQuestion()
{
++ctr;
if(ctr <= 15)
{
int randomQuestionIndex = Random.Range(0, unansweredQuestions.Count);
currentQuestion = unansweredQuestions[randomQuestionIndex];
factText.text = currentQuestion.fact;
if (currentQuestion.isTrue)
{
//trueAnswerText.text = "CORRECT";
//falseAnswerText.text = "WRONG";
}
else
{
//trueAnswerText.text = "WRONG";
//falseAnswerText.text = "CORRECT";
}
}
else
{
PlayerPrefs.SetInt("pScoreOne", scoreGameOne);
PlayerPrefs.SetInt("mScoreOne", mistakesGameOne);
unansweredQuestions = null;
ctr = 0;
SceneManager.LoadScene("ScoreScene");
}
}
IEnumerator GoToNextQuestion()
{
unansweredQuestions.Remove(currentQuestion);
yield return new WaitForSeconds(timeBtwQuestions);
SetCurrentQuestion();
}
public void SelectTrue()
{
if(currentQuestion.isTrue)
{
//anim.SetTrigger("True");
Debug.Log("CORRECT!");
++scoreGameOne;
}
else
{
Debug.Log("WRONG!");
++mistakesGameOne;
}
StartCoroutine(GoToNextQuestion());
}
public void SelectFalse()
{
//anim.SetTrigger("False");
if (!currentQuestion.isTrue)
{
Debug.Log("CORRECT!");
++scoreGameOne;
}
else
{
Debug.Log("WRONG!");
++mistakesGameOne;
}
StartCoroutine(GoToNextQuestion());
}
}
|
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using MyCashFlow.Domains.DataObject;
using MyCashFlow.Web.ViewModels.Account;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyCashFlow.Web.Services.Account
{
public interface IAccountService
{
RegisterViewModel BuildRegisterViewModel();
IEnumerable<Country> GetCountries();
VerifyCodeViewModel BuildVerifyCodeViewModel(
string provider,
string returnUrl,
bool rememberMe);
Task<IdentityResult> RegisterUserAsync(
UserManager<User, int> userManager,
SignInManager<User, int> signInManager,
RegisterViewModel model);
Task<IdentityResult> ResetPasswordAsync(
UserManager<User, int> userManager,
ResetPasswordViewModel model);
Task<SendCodeViewModel> BuildSendCodeViewModelAsync(
UserManager<User, int> userManager,
SignInManager<User, int> signInManager,
string returnUrl,
bool rememberMe);
Task<IdentityResult> ConfirmExternalLoginAsync(
IAuthenticationManager authenticationManager,
UserManager<User, int> userManager,
SignInManager<User, int> signInManager,
ExternalLoginConfirmationViewModel model);
}
}
|
using SandBoxRestApiUdemy.Data.VO;
using System.Collections.Generic;
namespace SandBoxRestApiUdemy.Business
{
public interface IBookBusiness
{
BookVO Create(BookVO person);
BookVO FindById(int id);
List<BookVO> FindAll();
BookVO Update(BookVO person);
void Delete(int id);
}
}
|
using System;
using System.Linq;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Support.V4.Widget;
using Android.Support.V7.App;
using Android.Support.V7.AppCompat;
using Android.Views;
using Android.Views.Animations;
using Android.Widget;
using Toolbar = Android.Support.V7.Widget.Toolbar;
using FloatingActionButton = Clans.Fab.FloatingActionButton;
using Fragment = Android.Support.V4.App.Fragment;
using FragmentTransaction = Android.Support.V4.App.FragmentTransaction;
namespace FAB.Demo
{
[Activity(Label = "@string/app_name", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private NavigationView navigationView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.main_activity);
Toolbar toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
this.toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close);
drawerLayout.AddDrawerListener(this.toggle);
this.navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
if (savedInstanceState == null)
{
SupportFragmentManager.BeginTransaction().Add(Resource.Id.fragment, new HomeFragment()).Commit();
}
navigationView.SetCheckedItem(Resource.Id.home);
}
protected override void OnPostCreate(Bundle savedInstanceState)
{
base.OnPostCreate(savedInstanceState);
this.toggle.SyncState();
}
protected override void OnResume()
{
base.OnResume();
this.navigationView.NavigationItemSelected += NavigationView_NavigationItemSelected;
}
protected override void OnPause()
{
base.OnPause();
this.navigationView.NavigationItemSelected -= NavigationView_NavigationItemSelected;
}
public override void OnBackPressed()
{
if (drawerLayout != null && drawerLayout.IsDrawerOpen((int)GravityFlags.Start))
{
drawerLayout.CloseDrawer((int)GravityFlags.Start);
}
else {
base.OnBackPressed();
}
}
private void NavigationView_NavigationItemSelected(object sender, NavigationView.NavigationItemSelectedEventArgs e)
{
this.drawerLayout.CloseDrawer((int)GravityFlags.Start);
Fragment fragment = null;
FragmentTransaction ft = SupportFragmentManager.BeginTransaction();
switch (e.MenuItem.ItemId)
{
case Resource.Id.home:
fragment = new HomeFragment();
break;
case Resource.Id.menus:
fragment = new MenusFragment();
break;
case Resource.Id.progress:
fragment = new ProgressFragment();
break;
case Resource.Id.menu_snack:
fragment = new SnackbarFragment();
break;
case Resource.Id.menu_tab:
fragment = new TabFragment();
break;
}
ft.Replace(Resource.Id.fragment, fragment).Commit();
e.Handled = true;
}
}
} |
using System.Collections.Generic;
using Psub.DataService.DTO;
namespace Psub.DataService.Abstract
{
public interface IControlObjectService
{
ControlObjectDTO GetControlObjectById(int id);
List<ControlObjectDTO> GetControlObjectList(UserDTO user);
void SaveOrUpdate(ControlObjectDTO controlObjectDTO);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace _4SC1PraktikumService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IPegawai" in both code and config file together.
[ServiceContract]
public interface IPegawai
{
[OperationContract]
List<PegawaiInfo> getPegawaiInfo();
[OperationContract]
List<PegawaiInfo> getPegawaiID();
[OperationContract]
string getPegawaiLastID();
[OperationContract]
string insertPegawai(PegawaiInfo data);
[OperationContract]
string updatePegawai(PegawaiInfo data);
[OperationContract]
string deletePegawai(string id);
}
}
|
// Copyright 2020 Google Inc. 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 NtApiDotNet;
using System.Management.Automation;
namespace NtObjectManager.Cmdlets.Object
{
/// <summary>
/// <para type="synopsis">Remove the object ID for a file.</para>
/// <para type="description">This cmdlet removes the object ID for a file.</para>
/// </summary>
/// <example>
/// <code>Remove-NtFileObjectId -File $f</code>
/// <para>Remove the object ID for the file.</para>
/// </example>
/// <example>
/// <code>Remove-NtFileObjectId -Path "\??\c:\windows\notepad.exe"</code>
/// <para>Remove the object ID for the file by path</para>
/// </example>
/// <example>
/// <code>Remove-NtFileObjectId -Path "c:\windows\notepad.exe" -Win32Path</code>
/// <para>Remove the object ID for the file by win32 path</para>
/// </example>
[Cmdlet(VerbsCommon.Remove, "NtFileObjectId", DefaultParameterSetName = "Default")]
public class RemoveNtFileObjectIdCmdlet : BaseNtFilePropertyCmdlet
{
/// <summary>
/// Constructor.
/// </summary>
public RemoveNtFileObjectIdCmdlet()
: base(FileAccessRights.WriteData, FileShareMode.None, FileOpenOptions.None)
{
}
private protected override void HandleFile(NtFile file)
{
file.DeleteObjectId();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class ScoreManager : MonoBehaviour {
public Text scoreText;
public Text highScoreText;
public float scoreTracker;
public float highScoreTracker;
public float pointsPerSecond;
public bool isAlive;
void Start () {
if (PlayerPrefs.HasKey("HighScore"))
{
highScoreTracker = PlayerPrefs.GetFloat("HighScore");
}
}
void Update () {
if (isAlive)
{
scoreTracker += pointsPerSecond * Time.deltaTime;
}
if (scoreTracker > highScoreTracker)
{
highScoreTracker = scoreTracker;
PlayerPrefs.SetFloat("HighScore", highScoreTracker);
}
scoreText.text = "Score: " + Mathf.Round(scoreTracker);
highScoreText.text = "High Score: " + Mathf.Round(highScoreTracker);
}
public void AddToScore(int addScore)
{
scoreTracker += addScore;
}
}
|
/* *********************************************************************** *
* File : FlushHook.cs Part of Sitecore *
* Version: 2.2.0 www.sitecore.net *
* *
* *
* Purpose: Hook that calls the event handler Run method *
* *
* Bugs : None *
* *
* Status : Published. *
* *
* Copyright (C) 1999-2012 by Sitecore A/S. All rights reserved. *
* *
* This work is the property of: *
* *
* Sitecore A/S *
* Meldahlsgade 5, 4. *
* 1613 Copenhagen V. *
* Denmark *
* *
* This is a Sitecore published work under Sitecore's *
* shared source license. *
* *
* *********************************************************************** */
using System;
using Sitecore.Eventing;
using Sitecore.Events.Hooks;
using Sitecore.Sites.Events;
namespace Sitecore.Sites.Hooks
{
public class FlushHook : IHook
{
#region IHook Members
/// <summary>
/// This hook will call the event handler Run method
/// </summary>
public void Initialize()
{
EventManager.Subscribe(new Action<FlushRemoteEvent>(FlushRemoteEventHandler.Run));
}
#endregion
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBase : MonoBehaviour, IRayCollider
{
public TrailRenderer FastSpeedTrail;
public TrailRenderer SlowSpeedTrail;
public Rigidbody2D Rigidbody;
public CircleCollider2D Collider;
public Vector2 LastFrameCenterPoint { get; private set; }
public Vector2 LastFrameVelocity { get; private set; }
private Vector2 currentCenterPoint;
public LayerMask ColliderLayerMask;
private readonly float allowToHitTimeReset = 0.2f;
private float allowToHitTimer = 0;
private RaycastHit2D[] rayHits;
private float distToMoveOnOverlap = 0.02f;
private float rayDistOnOverlap = 0.05f;
private float defaultToTotalDistance { get { return (currentCenterPoint - LastFrameCenterPoint).magnitude; } }
private bool skipOneFrameFromCollisionSystem;
private bool isFastTrailOn;
private bool wasHittedRecently
{
get { return hittedRecently_; }
set
{
allowToHitTimer = 0;
hittedRecently_ = value;
}
}
private bool hittedRecently_;
private void Start()
{
RegisterObject();
}
private void OnDestroy()
{
Unregister();
}
public void Stop()
{
Rigidbody.velocity = Vector2.zero;
Rigidbody.angularVelocity = 0;
}
public void SetGravityState(bool state)
{
Rigidbody.gravityScale = state ? 1 : 0;
enabled = !state;
}
private void SetHittedState()
{
if (wasHittedRecently)
{
allowToHitTimer += Time.deltaTime;
if (allowToHitTimer >= allowToHitTimeReset)
{
wasHittedRecently = false;
}
}
else
{
allowToHitTimer = 0;
}
}
private void SetTrailBasedOnSpeed()
{
// Debug.Log(Rigidbody.velocity.magnitude);
isFastTrailOn = Rigidbody.velocity.magnitude >= PhysicsConstants.BallSpeedPowerShotThreshold;
FastSpeedTrail.emitting = isFastTrailOn;
SlowSpeedTrail.emitting = !isFastTrailOn;
}
public void ResetTrailEmitter()
{
FastSpeedTrail.emitting = false;
SlowSpeedTrail.emitting = false;
}
public void ResetLastFrameVelocityAndPosition()
{
LastFrameVelocity = Vector2.zero;
LastFrameCenterPoint = transform.position;
}
public void SetSpeedOnBallCollisionExit()
{
Rigidbody.velocity = Rigidbody.velocity.normalized * PhysicsConstants.BallSpeedAfterBallHit;
LastFrameVelocity = Rigidbody.velocity;
}
public void SetLastFrameVelocityOnCollisionStay()
{
//Debug.Log(gameObject.name + " on collision stay before: " + Rigidbody.velocity);
Rigidbody.velocity = LastFrameVelocity;
LastFrameVelocity = Rigidbody.velocity;
//Debug.Log(gameObject.name + " on collision stay after: " + Rigidbody.velocity);
}
public void SetLastFrameVelocityOnCollisionExit()
{
// Debug.Log(gameObject.name + " on collision EXIT before: " + Rigidbody.velocity);
Rigidbody.velocity = LastFrameVelocity;
LastFrameVelocity = Rigidbody.velocity;
// Debug.Log(gameObject.name + " on collision EXIT after: " + Rigidbody.velocity);
}
public void AddForceOnStrikerHit(Vector2 forceVector, float endSpeed)
{
if (!wasHittedRecently)
{
Vector2 finalVelocityVector = (LastFrameVelocity.normalized + forceVector).normalized * endSpeed;
Rigidbody.velocity = finalVelocityVector;
Debug.LogWarningFormat("[{0}]{1} + {2} = {3} || speed: {4}", gameObject.name, LastFrameVelocity.normalized, forceVector, finalVelocityVector, Rigidbody.velocity.magnitude);
LastFrameVelocity = Rigidbody.velocity;
wasHittedRecently = true;
}
else
{
Rigidbody.velocity = LastFrameVelocity;
wasHittedRecently = true;
Debug.LogErrorFormat("[{0}]BAD HIT!!! {1}", gameObject.name, Rigidbody.velocity);
}
}
public void RaycastAndSkipThisFrameCollision()
{
//Debug.LogError("STOP");
RaycastForColliders();
HandleCollision(new List<IRayCollider>());
OnFixedUpdateTick();
skipOneFrameFromCollisionSystem = true;
}
private void RaycastForColliders()
{
if (skipOneFrameFromCollisionSystem)
{
return;
}
currentCenterPoint = transform.position;
Vector2 direction = currentCenterPoint - LastFrameCenterPoint;
float distanceForRay = direction.magnitude;
float radius = Collider.radius / 2;
rayHits = Physics2D.CircleCastAll(LastFrameCenterPoint, radius, direction, distanceForRay, ColliderLayerMask);
if(rayHits.Length > 0)
{
rayHits.SortByLength();
RegisterCollision(rayHits[0]);
}
}
private void OnCollision(BallBase ball, RaycastHit2D rayHit, CollisionSide colSide, CollisionType colType, float totalDistance, float endSpeed, int safe, ICollider collidingObject, out float distanceAfterHit)
{
if(totalDistance <= 0)
{
rayHits = new RaycastHit2D[0];
Debug.LogWarning("TOTAL DISTNANCE <= 0!");
distanceAfterHit = 0;
return;
}
Vector2 lastFramePos = ball.LastFrameCenterPoint;
Vector2 velocity = LastFrameVelocity;
Vector2 actualPos = currentCenterPoint;
Vector2 centroidPoint = rayHit.centroid;
float colRadius = Collider.radius / 2;
float distanceToCollision = rayHit.distance;
distanceAfterHit = totalDistance - distanceToCollision;
// Debug.LogFormat("[{3}] distanceToCollision: {0}, total distance: {1} distanceAfterHit: {2}", distanceToCollision, totalDistance, distanceAfterHit, safe);
Debug.DrawLine(centroidPoint, rayHit.point, Color.blue, 2);
Debug.DrawLine(actualPos, lastFramePos, safe == 0 ? Color.black : Color.yellow, 2);
Debug.DrawLine(actualPos, centroidPoint, Color.green, 2);
Vector2 newPos;
bool overlapping = distanceToCollision == 0;
Debug.LogFormat("Collision. side: {0} type: {1} overlap: {2}, last framePos: {3} actualPos: {4}", colSide, colType, overlapping, lastFramePos, actualPos);
if (overlapping)
{
Debug.LogWarningFormat("OVERLAPPING! To collision: {0} total distance: {1}", distanceToCollision, totalDistance);
overlapping = true;
newPos = GetNewPositionWhenOverlaping(colType, colSide, collidingObject, rayHit, actualPos, colRadius);
distanceAfterHit = totalDistance - (newPos - lastFramePos).magnitude;
Debug.Log("new distance after hit: " + distanceAfterHit);
if(distanceAfterHit <= -100)
{
Debug.Log("FAIL");
}
// newPos = GetNewPositionBasedOnCollisionType(colType, colSide, newPos, velocity, distanceAfterHit);
// Debug.LogFormat("Pos changed: {0} to {1}", lastFramePos, newPos);
}
else
{
newPos = GetNewPositionBasedOnCollisionType(colType, colSide, centroidPoint, velocity, collidingObject, distanceAfterHit);
Vector2 endVel = SetVelocityBasedOnCollisionType(colType, colSide, collidingObject, endSpeed, LastFrameVelocity);
LastFrameVelocity = endVel;
Debug.Log("change velocity to " + (endVel.y < 0 ? "DOWN" : "UP"));
}
ball.transform.position = newPos;
Debug.DrawLine(centroidPoint, newPos, safe == 0 ? Color.red : Color.grey, 2);
currentCenterPoint = newPos;
if (overlapping)
{
rayHit.centroid = newPos;
rayHit.distance = distToMoveOnOverlap;
//rayHits = new RaycastHit2D[1] { rayHit };
//rayHits = Physics2D.CircleCastAll(newPos, colRadius, newPos - actualPos, distanceAfterHit, ColliderLayerMask);
OnCollision(ball, rayHit, colSide, colType, distanceAfterHit, endSpeed, safe, collidingObject, out distanceAfterHit);
LastFrameCenterPoint = newPos;
}
else
{
rayHits = Physics2D.CircleCastAll(centroidPoint, colRadius, newPos - centroidPoint, distanceAfterHit, ColliderLayerMask);
LastFrameCenterPoint = rayHit.centroid;
rayHits = rayHits.Remove(rayHit);
}
// Debug.LogFormat("col Y: {0}, end Y: {1}", centroidPoint.y, newPos.y);
// Debug.LogFormat("start vel: {0} end vel: {1}", velocity.normalized, endVel.normalized);
}
private Vector2 GetNewPositionBasedOnCollisionType(CollisionType colType, CollisionSide colSide, Vector2 centroidPoint, Vector2 velocity, ICollider collidingObject, float distanceAfterHit)
{
if(distanceAfterHit <= 0)
{
return centroidPoint;
}
switch (colType)
{
case CollisionType.Frame:
case CollisionType.Enemy:
case CollisionType.Ship:
return GetOppositePosition(colSide, centroidPoint, velocity, distanceAfterHit);
case CollisionType.StrikerLeft:
case CollisionType.StrikerRight:
return GetPositionOnStrikerHit(colSide, collidingObject, centroidPoint, velocity, distanceAfterHit);
default:
return Vector2.zero;
}
}
private Vector2 GetOppositePosition(CollisionSide colSide, Vector2 centroidPoint, Vector2 velocity, float distanceAfterHit)
{
return centroidPoint + colSide.GetCollisionDirectionVector(velocity) * distanceAfterHit;
}
private Vector2 GetPositionOnStrikerHit(CollisionSide colSide, ICollider collidingObject, Vector2 centroidPoint, Vector2 velocity, float distanceAfterHit)
{
Striker striker = collidingObject as Striker;
return centroidPoint + striker.GetForceOnBallHit(this, colSide).normalized * distanceAfterHit;
}
private Vector2 SetVelocityBasedOnCollisionType(CollisionType colType, CollisionSide colSide, ICollider collidingObject, float endSpeed, Vector2 actualVelocity)
{
switch (colType)
{
case CollisionType.Frame:
case CollisionType.Enemy:
return SetVelocity(colSide, endSpeed, LastFrameVelocity);
case CollisionType.Ship:
return SetVelocity(colSide, endSpeed, actualVelocity);
case CollisionType.StrikerLeft:
case CollisionType.StrikerRight:
Striker striker = collidingObject as Striker;
Vector2 vel = striker.GetForceOnBallHit(this, colSide);
Rigidbody.velocity = vel;
return vel;
default:
return Vector2.zero;
}
}
public Vector2 SetVelocity(CollisionSide colliderSide, float endSpeed, Vector2 actualVelocity)
{
float xVel = actualVelocity.x;
float yVel = actualVelocity.y;
float xVelAbs = Mathf.Abs(xVel);
float yVelAbs = Mathf.Abs(yVel);
Vector2 endVel = new Vector2();
switch (colliderSide)
{
case CollisionSide.Bottom:
endVel = new Vector2(xVel, yVelAbs).normalized * endSpeed;
break;
case CollisionSide.Top:
endVel = new Vector2(xVel, -yVelAbs).normalized * endSpeed;
break;
case CollisionSide.Left:
endVel = new Vector2(xVelAbs, yVel).normalized * endSpeed;
break;
case CollisionSide.Right:
endVel = new Vector2(-xVelAbs, yVel).normalized * endSpeed;
break;
}
Rigidbody.velocity = endVel;
return endVel;
}
/*
public Vector2 SetUpOrDownVelocity(CollisionSide colSide, float endSpeed, Vector2 actualVelocity)
{
float xVel = LastFrameVelocity.x;
float yVel = LastFrameVelocity.y;
Vector2 endVel = new Vector2(xVel, -yVel).normalized * endSpeed;
Rigidbody.velocity = endVel;
return endVel;
}*/
public void AddToPosition(Vector2 vec)
{
LastFrameCenterPoint += vec;
transform.position += (Vector3)vec;
currentCenterPoint += vec;
}
private Vector2 GetNewPositionWhenOverlaping(CollisionType colType, CollisionSide colSide, ICollider collidingObject, RaycastHit2D rayHit, Vector2 actualPos, float radius)
{
switch (colType)
{
case CollisionType.Frame:
return GetOverlapPositionForFrame(colSide, rayHit, actualPos, radius);
case CollisionType.Ship:
case CollisionType.Enemy:
return GetOverlapPositionForEnemyOrShip(colSide, rayHit, actualPos, radius);
case CollisionType.StrikerLeft:
case CollisionType.StrikerRight:
Striker striker = collidingObject as Striker;
return GetOverlapPositionForStriker(striker, colSide, rayHit, actualPos, radius);
default:
return actualPos;
}
}
private Vector2 GetOverlapPositionForStriker(Striker striker, CollisionSide colSide, RaycastHit2D rayHit, Vector2 actualPos, float radius)
{
Vector2 startPos = actualPos;
Vector2 newDirectionVector = new Vector2();
switch (colSide)
{
case CollisionSide.Bottom:
newDirectionVector = striker.transform.up;
break;
case CollisionSide.Top:
newDirectionVector = striker.transform.up * -1;
break;
case CollisionSide.Left:
newDirectionVector = striker.transform.right;
break;
case CollisionSide.Right:
newDirectionVector = striker.transform.right * -1;
break;
}
BoxCollider2D boxCollider = rayHit.collider as BoxCollider2D;
float fromCenterToBorderHorizontally = boxCollider.size.x * boxCollider.transform.localScale.x / 2;
float fromCenterToBorderVertically = boxCollider.size.y * boxCollider.transform.localScale.y / 2;
Vector2 a = (Vector2)boxCollider.bounds.center + fromCenterToBorderHorizontally * (Vector2)striker.transform.right * -1;
Vector2 b = (Vector2)boxCollider.bounds.center + fromCenterToBorderHorizontally * (Vector2)striker.transform.right;
Vector2 c = (Vector2)boxCollider.bounds.center + fromCenterToBorderVertically * (Vector2)striker.transform.up;
Vector2 d = (Vector2)boxCollider.bounds.center + fromCenterToBorderVertically * (Vector2)striker.transform.up * -1;
Vector2 e = new Vector2();
Vector2 f = new Vector2();
float distToMove = 0;
switch (colSide)
{
case CollisionSide.Bottom:
case CollisionSide.Top:
e = actualPos + newDirectionVector * 10;
f = actualPos - newDirectionVector * 10;
actualPos = Math2D.GetIntersectionPointCoordinates(a, b, e, f);
distToMove = radius + fromCenterToBorderVertically + distToMoveOnOverlap;
break;
case CollisionSide.Left:
case CollisionSide.Right:
e = actualPos + newDirectionVector * 10;
f = actualPos - newDirectionVector * 10;
actualPos = Math2D.GetIntersectionPointCoordinates(c, d, e, f);
distToMove = radius + fromCenterToBorderHorizontally + distToMoveOnOverlap;
break;
}
Vector2 newPos = actualPos + newDirectionVector * distToMove;
Debug.DrawLine(startPos, newPos, Color.white, 4);
return newPos;
}
private Vector2 GetOverlapPositionForFrame(CollisionSide colSide, RaycastHit2D rayHit, Vector2 actualPos, float radius)
{
if (colSide == CollisionSide.Bottom || colSide == CollisionSide.Top)
{
actualPos.y = rayHit.collider.bounds.center.y;
}
else if (colSide == CollisionSide.Left || colSide == CollisionSide.Right)
{
actualPos.x = rayHit.collider.bounds.center.x;
}
BoxCollider2D boxCollider = rayHit.collider as BoxCollider2D;
float fromCenterToBorder = boxCollider.size.x * boxCollider.transform.parent.localScale.x / 2;
float distToMove = radius + fromCenterToBorder + distToMoveOnOverlap;
Vector2 newPos = actualPos + colSide.GetOppositeDirectionVector() * distToMove;
Debug.LogWarningFormat("dist to move on overlap: {0} newPos: {1}, from center to border: {2} ", distToMove, newPos, fromCenterToBorder);
return newPos;
}
private Vector2 GetOverlapPositionForEnemyOrShip(CollisionSide colSide, RaycastHit2D rayHit, Vector2 actualPos, float radius)
{
BoxCollider2D boxCollider = rayHit.collider as BoxCollider2D;
float fromCenterToBorder = 0;
switch (colSide)
{
case CollisionSide.Bottom:
case CollisionSide.Top:
fromCenterToBorder = boxCollider.size.y * boxCollider.transform.localScale.y / 2;
actualPos.y = rayHit.collider.bounds.center.y;
break;
case CollisionSide.Left:
case CollisionSide.Right:
actualPos.x = rayHit.collider.bounds.center.x;
fromCenterToBorder = boxCollider.size.x * boxCollider.transform.localScale.x / 2;
break;
}
float distToMove = radius + fromCenterToBorder + distToMoveOnOverlap;
Vector2 newPos = actualPos + colSide.GetOppositeDirectionVector() * distToMove;
return newPos;
}
#region IRayCollider
public void Raycast()
{
RaycastForColliders();
}
public void RegisterObject()
{
RayCollidersController.Instance.RegisterRayCollider(this);
}
public void Unregister()
{
if(RayCollidersController.Instance != null)
{
RayCollidersController.Instance.UnregisterRayCollider(this);
}
}
public void OnFixedUpdateTick()
{
if (skipOneFrameFromCollisionSystem)
{
skipOneFrameFromCollisionSystem = false;
return;
}
LastFrameVelocity = Rigidbody.velocity;
LastFrameCenterPoint = transform.position;
// Debug.LogFormat("set last frame pos: {0} -- {1}", LastFrameCenterPoint.x, LastFrameCenterPoint.y);
SetHittedState();
SetTrailBasedOnSpeed();
}
public List<IRayCollider> HandleCollision(List<IRayCollider> collidersToSkip)
{
if (skipOneFrameFromCollisionSystem)
{
return new List<IRayCollider>();
}
List<IRayCollider> collidedWith = new List<IRayCollider>();
Vector2 direction = currentCenterPoint - LastFrameCenterPoint;
float distanceForRay = direction.magnitude;
float radius = Collider.radius / 2;
int safe = 0;
while (rayHits.Length > 0 && distanceForRay > 0)
{
rayHits.SortByLength();
if (rayHits.Length > 1)
{
for (int i = 0; i < rayHits.Length; i++)
{
//Debug.LogWarningFormat("[{0}] point: {1} centroid: {2} length: {3}", i, rayHits[i].point, rayHits[i].centroid, rayHits[i].distance);
}
}
RaycastHit2D rayHit = rayHits[0];
CollisionSide colSide = CollisionSide.Bottom;
if (rayHit.collider.CompareTag(GameTags.Frame))
{
FrameCollider frameCollider = rayHit.collider.GetComponent<FrameCollider>();
IRayCollider col = frameCollider as IRayCollider;
if (!collidersToSkip.Contains(col))
{
if (frameCollider.DestroyBallAndProjectiles)
{
GameController.Instance.RemoveBallFromPlay(this);
}
else
{
colSide = frameCollider.CollisionSide;
OnCollision(this, rayHit, colSide, CollisionType.Frame, defaultToTotalDistance, LastFrameVelocity.magnitude, safe, frameCollider, out distanceForRay);
}
if (!collidedWith.Contains(col))
{
collidedWith.Add(col);
}
}
}
else if (rayHit.collider.CompareTag(GameTags.Enemy))
{
// Debug.DrawLine(currentCenterPoint, LastFrameCenterPoint, Color.green, 2);
EnemyBase enemy = rayHit.collider.GetComponent<EnemyBase>();
IRayCollider col = enemy as IRayCollider;
if (!collidersToSkip.Contains(col))
{
colSide = CollisionSideDetect.GetCollisionSide(rayHit.centroid, rayHit.point);
OnCollision(this, rayHit, colSide, CollisionType.Enemy, defaultToTotalDistance, PhysicsConstants.BallSpeedAfterEnemyHit, safe, enemy, out distanceForRay);
enemy.OnCollisionWithBall(this);
if (!collidedWith.Contains(col))
{
collidedWith.Add(col);
}
}
}
else if (rayHit.collider.CompareTag(GameTags.Ship))
{
ShipCollider ship = rayHit.collider.GetComponent<ShipCollider>();
IRayCollider col = ship as IRayCollider;
if (!collidersToSkip.Contains(col))
{
colSide = ship.GetCollisionSideWithBall(this, LastFrameCenterPoint);
OnCollision(this, rayHit, colSide, CollisionType.Ship, defaultToTotalDistance, PhysicsConstants.BallSpeedAfterShipHit, safe, ship, out distanceForRay);
}
if (!collidedWith.Contains(col))
{
collidedWith.Add(col);
}
}
else if (rayHit.collider.CompareTag(GameTags.Striker))
{
Striker striker = rayHit.collider.GetComponent<Striker>();
IRayCollider col = striker as IRayCollider;
if (!collidersToSkip.Contains(col))
{
colSide = striker.GetCollisionSideWithBall(LastFrameCenterPoint);
OnCollision(this, rayHit, colSide, striker.CollisionType, defaultToTotalDistance, striker.GetForceOnBallHit(this, colSide).magnitude, safe, striker, out distanceForRay);
}
if (!collidedWith.Contains(col))
{
collidedWith.Add(col);
}
}
//Debug.LogFormat("{0} collision with {1} on side {2}", safe, rayHit.collider.gameObject.name, colSide);
safe++;
}
return collidedWith;
}
public void RegisterCollision(RaycastHit2D rayHit)
{
RayCollidersController.Instance.RegisterCollision(this, rayHit);
}
#endregion
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biblioteca.Models
{
abstract class Socio
{
public string Nombre { get; set; }
public string Apellido { get; set; }
public long NroIdentificacion { get; set; }
public List<Ejemplar> Ejemplares { get; set; }
public int CantidadMax { get; set; }
public abstract bool ConsultarCupo();
public abstract void DevolverEjemplar(Ejemplar e);
public abstract string PedirEjemplar(Ejemplar e);
}
}
|
using System.Collections.Generic;
using eForm.Auditing.Dto;
using eForm.Dto;
namespace eForm.Auditing.Exporting
{
public interface IAuditLogListExcelExporter
{
FileDto ExportToFile(List<AuditLogListDto> auditLogListDtos);
FileDto ExportToFile(List<EntityChangeListDto> entityChangeListDtos);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace QueueLinkedListImplementation
{
//a queue is a collection of data with the restriction that elements can only be removed from the front of the queue and inserted
//into the rear of the queue, this is called first in first out, methods include Engueue(int newData) Dequeue() Front() and IsEmpty
//you can implement with different data structures such as arrays, linked lists, etc
public class QueueLinkedListImplementation
{
public static void Main(string[] args)
{
}
public Node head { get; set; }
public Node rear { get; set; }
public class Node
{
public Node next { get; set; }
public int data { get; set; }
}
public Node EnqueueIntoRear(int newData)
{
Node newNode = new Node() { data = newData };
//check to see if list is currently empty
if(head== null && rear == null)
{
head = newNode;
rear = newNode;
return newNode;
}
rear.next = newNode;
rear = newNode;
return newNode;
}
public Node Dequeue()
{
if(head == null)
{
throw new Exception("List is empty, nothing to dequeue");
}
if(head.next == null)
{
//alternatively you can have an empty list and remove the head
throw new Exception("List has one item in it");
}
Node temp = new Node();
temp = head;
head = head.next;
temp.next = null;
return head;
}
}
}
|
// Operator.cs
// Author:
// Stephen Shaw <sshaw@decriptor.com>
// Copyright (c) 2011 sshaw
namespace Compiler.Semantics
{
public class Operator
{
public string Name { get; private set; }
public int Weight { get; private set; }
public Operator (string oper, int weight)
{
Name = oper;
Weight = weight;
}
public override string ToString ()
{
return string.Format ("[Operator: Name= '{0}', Weight= {1}]", Name, Weight);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Class that manages the creation and manipulation of corn.
public class CornManager : MonoBehaviour {
// Set the values used to determine if a corn is swiped left or right.
const float swipedLeft = -2.0f;
const float swipedRight = 2.0f;
public GameObject Corn;
public GameObject Cob;
public CornUtil cornUtil;
public Sprite goodCorn;
public Sprite badCorn;
public ScoreManager scoreManager;
private bool isTouching = false;
private bool isNaked = false;
private bool gameStarted = true;
private bool isGoodCorn;
private void Update () {
if (gameStarted) {
// Initialize corn with 4 - 6 husks to start.
this.InitializeCorn(Random.Range(4, 7));
gameStarted = false;
}
// If a corn has been husked enter the if.
if (isNaked) {
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved) {
if (!isTouching) {
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero);
if (hit.collider == Corn.GetComponentInChildren<BoxCollider2D>()) {
isTouching = true;
}
} else if (isTouching && Input.GetTouch(0).phase == TouchPhase.Moved) {
Vector3 fingerPos = Input.GetTouch(0).position;
fingerPos.z = 8f;
Vector3 realWorldPos = Camera.main.ScreenToWorldPoint(fingerPos);
Corn.transform.position = realWorldPos;
}
} else if (isTouching && Input.GetTouch(0).phase == TouchPhase.Ended) {
cornUtil.InitializeStartingPosition(Corn.transform.position, cornUtil.centerPosition, newLaunchTime: 0.2f);
isTouching = false;
} else if (Input.touchCount == 0) {
cornUtil.ExtrapolateCurrentPosition(cornUtil.endingPosition);
}
if (Corn.transform.position.x > swipedRight) {
cornUtil.InitializeStartingPosition(Corn.transform.position, new Vector3(5f, 0), 0.1f);
if (this.DoneTravelling()) {
// If corn is good add points. Otherwise deduct.
scoreManager.ScoreCalculator(isGoodCorn);
// TODO: Determine when to increase husk count.
this.InitializeCorn(Random.Range(4, 7));
}
} else if (Corn.transform.position.x < swipedLeft) {
cornUtil.InitializeStartingPosition(Corn.transform.position, new Vector3(-5f, 0), 0.1f);
if (this.DoneTravelling()) {
// If corn is good add points. Otherwise deduct.
scoreManager.ScoreCalculator(!isGoodCorn);
this.InitializeCorn(Random.Range(4, 7));
}
}
}
// If no touches are registered enter.
if (Input.touchCount == 0 && !gameStarted) {
cornUtil.ExtrapolateCurrentPosition(cornUtil.endingPosition);
}
// If the cob is the only thing that is left set isNaked to true;
if (Corn.transform.childCount <= 1) {
isNaked = true;
}
}
// Method used to reset a husked and swiped corn to it's prior glory.
public void InitializeCorn (int huskCount) {
// Set position to the specified initial position.
Corn.transform.position = cornUtil.initialPosition;
// Create new husks and attach.
// FUTURE ISSUE: the position values are hard coded. When you pass in Vector3 coordinates this way they are world coordinates, not coordinates related to the parent.
for (int i = 1; i <= huskCount; i++) {
int rand = Random.Range(1, 4);
if (i != huskCount) {
// Spawn each husk at least once
if (i == 1 || (i != 2 && i != 3 && rand == 1)) {
GameObject MidHusk = (GameObject) Instantiate(Resources.Load("Husks/MiddleHusk"), new Vector3 (4.323f, -5.832f), Quaternion.Euler(0, 0, 0), Corn.transform);
MidHusk.GetComponent<HuskController>().layer = i;
MidHusk.GetComponent<SpriteRenderer>().sortingOrder = i;
}
if (i == 2 || (i != 1 && i != 3 && rand == 2)) {
GameObject LeftHusk = (GameObject) Instantiate(Resources.Load("Husks/LeftHusk"), new Vector3 (3.227f, -5.832f), Quaternion.Euler(0, 0, 0), Corn.transform);
LeftHusk.GetComponent<HuskController>().layer = i;
LeftHusk.GetComponent<SpriteRenderer>().sortingOrder = i;
}
if (i == 3 || (i != 1 && i != 2 && rand == 3)) {
GameObject RightHusk = (GameObject) Instantiate(Resources.Load("Husks/RightHusk"), new Vector3 (5.373f, -5.832f), Quaternion.Euler(0, 0, 0), Corn.transform);
RightHusk.GetComponent<HuskController>().layer = i;
RightHusk.GetComponent<SpriteRenderer>().sortingOrder = i;
}
} else {
// Guarantee the middle husk is the last one to spawn
GameObject MidHusk = (GameObject) Instantiate(Resources.Load("Husks/MiddleHusk"), new Vector3 (4.323f, -5.832f), Quaternion.Euler(0, 0, 0), Corn.transform);
MidHusk.GetComponent<HuskController>().layer = i;
MidHusk.GetComponent<SpriteRenderer>().sortingOrder = i;
}
}
// Set bool denoting that the corn is in need of husking.
isNaked = false;
// Randomly choose the cob sprite, set bool value for scoring.
if (Random.Range(1, 3) == 1) {
isGoodCorn = true;
Cob.GetComponent<SpriteRenderer>().sprite = goodCorn;
} else {
isGoodCorn = false;
Cob.GetComponent<SpriteRenderer>().sprite = badCorn;
}
// Set initial position for launch.
cornUtil.InitializeStartingPosition(cornUtil.initialPosition, cornUtil.centerPosition);
}
public bool DoneTravelling () {
return Corn.transform.position == cornUtil.endingPosition;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Session01_Homework : MonoBehaviour {
/* Session 1 homework:
Declare a int variable and set a value
Declare a float variable and set a value
Declare a string variable and set a value
Create a function that prints the declared variables
Declare and initialize an array
Declare and initialize a list
Create and initialize a Dictionary */
public int HomeworkInteger = 7;
public float HomeworkFloat = 11.5f;
public string HomeworkString = "Multiplication of numbers";
public int [] homeworkIntegerArray = new int [3];
public float[] homeworkFloatArray = { 8, 11.1f, 51.1f, 199.1f };
public List<int> homeworkIntegerList = new List<int>();
public List<string> FruitsOnTheImaginarySuperexpensiveMarket = new List<string>();
Dictionary<string, float> priceOfFruit = new Dictionary<string, float>();
float HomeworkFunction(float firstVariable, float secondVariable)
{
float Multiplication = firstVariable * secondVariable;
return Multiplication;
}
// Use this for initialization
void Start () {
Debug.Log( HomeworkString + HomeworkInteger + " and " + HomeworkFloat + " is " + HomeworkFunction(HomeworkInteger, HomeworkFloat));
homeworkFloatArray[2] = 13.3f;
homeworkIntegerArray[1] = homeworkIntegerArray[0]+1;
homeworkIntegerArray[2] = homeworkIntegerArray[1] * 3;
homeworkIntegerList.Add(2);
homeworkIntegerList.Add(55);
FruitsOnTheImaginarySuperexpensiveMarket.Add("apple");
FruitsOnTheImaginarySuperexpensiveMarket.Add("banana");
FruitsOnTheImaginarySuperexpensiveMarket.Add("pineapple");
priceOfFruit.Add ( FruitsOnTheImaginarySuperexpensiveMarket [0], HomeworkInteger );
priceOfFruit.Add ( "mango", homeworkFloatArray[1] );
priceOfFruit.Add ( FruitsOnTheImaginarySuperexpensiveMarket [2], HomeworkFloat );
Debug.Log("Price of " + FruitsOnTheImaginarySuperexpensiveMarket[2] + " is " + priceOfFruit[FruitsOnTheImaginarySuperexpensiveMarket[2]]);
Debug.Log("In the store " + priceOfFruit.Count + " fruts are too expensive.");
}
// Update is called once per frame
void Update () {
homeworkIntegerList.Remove(2);
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace DllRegistrar
{
class Regasm
{
enum RegasmOperation
{
Register, Unregister
}
public static List<string> GetPaths(bool getFor64bit)
{
string dotNetPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET", getFor64bit ? "Framework64" : "Framework");
List<string> regasmPaths = new List<string>();
if (!Directory.Exists(dotNetPath))
return regasmPaths;
var files = Directory.GetFiles(dotNetPath);
var regasm_tmp = files.Where(f => Path.GetFileName(f).ToLower() == "regasm.exe");
foreach (var f in regasm_tmp)
regasmPaths.Add(f);
var dirs = Directory.GetDirectories(dotNetPath);
foreach (var dir in dirs)
{
files = Directory.GetFiles(dir);
regasm_tmp = files.Where(f => Path.GetFileName(f).ToLower() == "regasm.exe");
foreach (var f in regasm_tmp)
regasmPaths.Add(f);
}
return regasmPaths;
}
public static string FindBestRegasm(List<string> regasmPaths)
{
foreach (var item in regasmPaths)
{
if (item.ToString().Contains("v4.0"))
{
return item;
}
}
return "";
}
public static void Register(string regasmPath, string dllPath)
{
menageRegasm(RegasmOperation.Register, regasmPath, dllPath);
}
public static void Unregister(string regasmPath, string dllPath)
{
menageRegasm(RegasmOperation.Unregister, regasmPath, dllPath);
}
private static void menageRegasm(RegasmOperation regasmOperation, string regasmPath, string dllPath)
{
string arg = "";
if (regasmOperation == RegasmOperation.Register)
arg += dllPath.WrapIn("\"");
else if (regasmOperation == RegasmOperation.Unregister)
arg += string.Concat("/unregister", " ", dllPath.WrapIn("\""));
Process proc = new Process();
proc.StartInfo.FileName = regasmPath;
proc.StartInfo.Arguments = arg;
proc.StartInfo.Verb = "runas";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.OutputDataReceived += Proc_OutputDataReceived;
proc.ErrorDataReceived += Proc_OutputDataReceived;
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
}
public delegate void OutputDataReceived(string output);
public static event OutputDataReceived OutputDataReceiverEvent;
private static void Proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (OutputDataReceiverEvent != null)
OutputDataReceiverEvent(e.Data + Environment.NewLine);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Ex1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
algoCB.Items.Add("AES");
algoCB.Items.Add("DES");
algoCB.Items.Add("3DES");
algoCB.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
//openFileDialog1.ShowDialog();
if(openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
string path = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
label1.Text = path;
CryptoG.Criptare(path, algoCB.Text, int.Parse(sizeCB.Text));
}
}
private void decriptBtN_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
string path = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
label1.Text = path;
CryptoG.Decriptare(path, algoCB.Text, int.Parse(sizeCB.Text));
}
}
private void algoCB_SelectedIndexChanged(object sender, EventArgs e)
{
if(algoCB.SelectedItem == algoCB.Items[0])
{
sizeCB.Items.Clear();
sizeCB.Items.Add(128);
sizeCB.Items.Add(256);
sizeCB.Refresh();
}
if (algoCB.SelectedItem == algoCB.Items[1])
{
sizeCB.Items.Clear();
sizeCB.Items.Add(64);
sizeCB.Refresh();
}
if (algoCB.SelectedItem == algoCB.Items[2])
{
sizeCB.Items.Clear();
sizeCB.Items.Add(128);
sizeCB.Items.Add(198);
sizeCB.Refresh();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using StudyEspanol.Data;
using StudyEspanol.Data.Models;
namespace StudyEspanol.Data.Managers
{
public class WordsManager : Manager<Word>
{
#region Events
public event EventHandler<EventArgs> SearchFinished;
#endregion
#region Constructor
private static WordsManager instance;
public static WordsManager Instance
{
get
{
Debug.WriteLine("[Study Espanol] Retriving Tags Manager Instance");
if (instance == null)
{
instance = new WordsManager();
}
return instance;
}
}
private WordsManager()
{
Debug.WriteLine("[Study Espanol] Creating Tags Manager");
}
#endregion
#region Methods
public void SaveWord(Word word)
{
Debug.WriteLine("[Study Espanol] Saving Word " + word.English);
Database.Instance.SaveWord(word);
}
public void DeleteWord(Word word)
{
Debug.WriteLine("[Study Espanol] Deleting Word" + word.English);
foreach (Word aWord in Objects)
{
if (aWord.Id == word.Id)
{
Objects.Remove(aWord);
break;
}
}
Database.Instance.DeleteWord(word);
}
public void Search(Query query, int maxWords)
{
Debug.WriteLine("[Study Espanol] Searching for Words");
Debug.WriteLine("[Study Espanol] Query " + query.GetQuery());
Objects = null;
Database.Instance.SearchWords(query, (sender, e) => {
if (e.Error != null)
{
Debug.WriteLine(e.Error.Message);
}
Objects = (List<Word>)e.Result;
if (maxWords < Objects.Count && maxWords != 0)
{
Objects.RemoveRange(maxWords, Objects.Count - maxWords);
}
SearchFinished(this, new EventArgs());
SearchFinished = null;
});
}
public List<QuizWord> WordsToQuizWords(TranslateDirection translateDirection)
{
List<QuizWord> quizWords = new List<QuizWord>();
foreach (Word word in Objects)
{
quizWords.Add(word.ToQuizWord(translateDirection));
}
return quizWords;
}
#endregion
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.PowerShell.EditorServices.Services;
using Microsoft.PowerShell.EditorServices.Services.PowerShellContext;
using Microsoft.PowerShell.EditorServices.Services.TextDocument;
using OmniSharp.Extensions.DebugAdapter.Protocol.Events;
using OmniSharp.Extensions.DebugAdapter.Protocol.Requests;
using OmniSharp.Extensions.JsonRpc;
namespace Microsoft.PowerShell.EditorServices.Handlers
{
internal class ConfigurationDoneHandler : IConfigurationDoneHandler
{
private readonly ILogger _logger;
private readonly IJsonRpcServer _jsonRpcServer;
private readonly DebugService _debugService;
private readonly DebugStateService _debugStateService;
private readonly DebugEventHandlerService _debugEventHandlerService;
private readonly PowerShellContextService _powerShellContextService;
private readonly WorkspaceService _workspaceService;
public ConfigurationDoneHandler(
ILoggerFactory loggerFactory,
IJsonRpcServer jsonRpcServer,
DebugService debugService,
DebugStateService debugStateService,
DebugEventHandlerService debugEventHandlerService,
PowerShellContextService powerShellContextService,
WorkspaceService workspaceService)
{
_logger = loggerFactory.CreateLogger<SetFunctionBreakpointsHandler>();
_jsonRpcServer = jsonRpcServer;
_debugService = debugService;
_debugStateService = debugStateService;
_debugEventHandlerService = debugEventHandlerService;
_powerShellContextService = powerShellContextService;
_workspaceService = workspaceService;
}
public async Task<ConfigurationDoneResponse> Handle(ConfigurationDoneArguments request, CancellationToken cancellationToken)
{
_debugService.IsClientAttached = true;
if (_debugStateService.OwnsEditorSession)
{
// If this is a debug-only session, we need to start
// the command loop manually
_powerShellContextService.ConsoleReader.StartCommandLoop();
}
if (!string.IsNullOrEmpty(_debugStateService.ScriptToLaunch))
{
if (_powerShellContextService.SessionState == PowerShellContextState.Ready)
{
// Configuration is done, launch the script
var nonAwaitedTask = LaunchScriptAsync(_debugStateService.ScriptToLaunch)
.ConfigureAwait(continueOnCapturedContext: false);
}
else
{
_logger.LogTrace("configurationDone request called after script was already launched, skipping it.");
}
}
if (_debugStateService.IsInteractiveDebugSession)
{
if (_debugService.IsDebuggerStopped)
{
if (_debugService.CurrentDebuggerStoppedEventArgs != null)
{
// If this is an interactive session and there's a pending breakpoint,
// send that information along to the debugger client
_debugEventHandlerService.TriggerDebuggerStopped(_debugService.CurrentDebuggerStoppedEventArgs);
}
else
{
// If this is an interactive session and there's a pending breakpoint that has not been propagated through
// the debug service, fire the debug service's OnDebuggerStop event.
_debugService.OnDebuggerStopAsync(null, _powerShellContextService.CurrentDebuggerStopEventArgs);
}
}
}
return new ConfigurationDoneResponse();
}
private async Task LaunchScriptAsync(string scriptToLaunch)
{
// Is this an untitled script?
if (ScriptFile.IsUntitledPath(scriptToLaunch))
{
ScriptFile untitledScript = _workspaceService.GetFile(scriptToLaunch);
await _powerShellContextService
.ExecuteScriptStringAsync(untitledScript.Contents, true, true);
}
else
{
await _powerShellContextService
.ExecuteScriptWithArgsAsync(scriptToLaunch, _debugStateService.Arguments, writeInputToHost: true);
}
_jsonRpcServer.SendNotification(EventNames.Terminated);
}
}
}
|
using DS1.Resources;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DS1.Mantenimientos.CedulaMantenimiento
{
public partial class GestionCedula : Form
{
CedulaEntities Entities = new CedulaEntities();
List<string> msg = new List<string>();
public int? cedulaToEditId;
public GestionCedula()
{
InitializeComponent();
LoadComboBox();
}
void LoadComboBox()
{
var cbNacionalidadData = Entities.Nacionalidads.Where(n => n.Estado == (int)EstadosEnum.Activo).Select(n => new { id = n.Id, text = n.Descripcion }).ToList();
var cbLugarNacimientoData = Entities.LugarNacimientoes.Where(n => n.Estado == (int)EstadosEnum.Activo).Select(n => new { id = n.Id, text = n.Descripcion }).ToList();
var cbSexoData = Entities.Sexoes.Where(n => n.Estado == (int)EstadosEnum.Activo).Select(n => new { id = n.Id, text = n.Descripcion }).ToList();
var cbTipoSangreData = Entities.TipoSangres.Where(n => n.Estado == (int)EstadosEnum.Activo).Select(n => new { id = n.Id, text = n.Descripcion }).ToList();
var cbOcupacionData = Entities.Ocupacions.Where(n => n.Estado == (int)EstadosEnum.Activo).Select(n => new { id = n.Id, text = n.Descripcion }).ToList();
var cbEstadoCivilData = Entities.EstadoCivils.Where(n => n.Estado == (int)EstadosEnum.Activo).Select(n => new { id = n.Id, text = n.Descripcion }).ToList();
var cbMunicipioData = Entities.Municipios.Where(n => n.Estado == (int)EstadosEnum.Activo).Select(n => new { id = n.Id, text = n.Descripcion }).ToList();
cbNacionalidadData.ForEach(data =>
cbNacionalidad.Items.Insert(data.id-1, data.text)
);
cbLugarNacimientoData.ForEach(data =>
cbLugarNacimiento.Items.Insert(data.id-1, data.text)
);
cbSexoData.ForEach(data =>
cbSexo.Items.Insert(data.id-1, data.text)
);
cbTipoSangreData.ForEach(data =>
cbTipoSangre.Items.Insert(data.id-1, data.text)
);
cbOcupacionData.ForEach(data =>
cbOcupacion.Items.Insert(data.id-1, data.text)
);
cbEstadoCivilData.ForEach(data =>
cbEstadoCivil.Items.Insert(data.id-1, data.text)
);
cbMunicipioData.ForEach(data =>
cbMunicipio.Items.Insert(data.id-1, data.text)
);
}
public void LoadData()
{
var Cedula = Entities.Cedulas.Find(cedulaToEditId);
tbNombre.Text = Cedula.Nombre;
tbApellido.Text = Cedula.Apellido;
dtFechaNacimiento.Value = Cedula.FechaNacimiento;
tbDireccionResidencia.Text = Cedula.DireccionResidencia;
cbNacionalidad.SelectedIndex = Cedula.IdNacional - 1;
cbEstadoCivil.SelectedIndex = Cedula.IdEstadoCivil - 1;
cbLugarNacimiento.SelectedIndex = Cedula.IdLugarNacimiento - 1;
cbSexo.SelectedIndex = Cedula.IdSexo - 1;
cbTipoSangre.SelectedIndex = Cedula.IdTipoSangre - 1;
cbOcupacion.SelectedIndex = Cedula.IdOcupacion - 1;
cbOcupacion.SelectedIndex = Cedula.IdOcupacion - 1;
cbMunicipio.SelectedIndex = Cedula.IdMunicipio - 1;
LoadCbSector();
cbSector.SelectedIndex = Cedula.IdSector -1;
LoadCbColegio();
cbColegio.SelectedIndex = Cedula.IdColegioElectoral - 1;
}
Cedula GetObject()
{
var rnd = new Random();
var diaMesNacimiento = dtFechaNacimiento.Value.ToString("dd-MM");
var anoVencimiento = DateTime.UtcNow.AddYears(8).ToString("-yyyy");
DateTime FechaExpiracion = Convert.ToDateTime(diaMesNacimiento + anoVencimiento);
return new Cedula
{
Codigo = Entities.LugarNacimientoes.FirstOrDefault(l => l.Descripcion == cbLugarNacimiento.Text).Codigo + "-" + rnd.Next(1000000, 9999999),
Nombre = tbNombre.Text,
Apellido = tbApellido.Text,
FechaNacimiento = dtFechaNacimiento.Value,
FechaExpiracion = FechaExpiracion,
DireccionResidencia = tbDireccionResidencia.Text,
IdNacional = cbNacionalidad.SelectedIndex+1,
IdLugarNacimiento = cbLugarNacimiento.SelectedIndex+1,
IdSexo = cbSexo.SelectedIndex+1,
IdTipoSangre = cbTipoSangre.SelectedIndex+1,
IdOcupacion = cbOcupacion.SelectedIndex+1,
IdEstadoCivil = cbOcupacion.SelectedIndex+1,
IdMunicipio = cbMunicipio.SelectedIndex+1,
IdSector = Entities.Sectors.FirstOrDefault(c => c.Descripcion == cbSector.Text).Id,
IdColegioElectoral = Entities.Colegios.FirstOrDefault(c=>c.Nombre==cbColegio.Text).Id,
Estado = (int)EstadosEnum.Activo,
FechaCreacion = DateTime.UtcNow.AddMinutes(-240)
};
}
void update()
{
var cedulaToUpdate = Entities.Cedulas.Find(cedulaToEditId);
var cedulaChange = GetObject();
cedulaToUpdate.IdColegioElectoral = cedulaChange.IdColegioElectoral;
cedulaToUpdate.Nombre = cedulaChange.Nombre;
cedulaToUpdate.Apellido = cedulaChange.Apellido;
cedulaToUpdate.DireccionResidencia = cedulaChange.DireccionResidencia;
cedulaToUpdate.IdEstadoCivil = cedulaChange.IdEstadoCivil;
cedulaToUpdate.FechaNacimiento = cedulaChange.FechaNacimiento;
cedulaToUpdate.FechaExpiracion = cedulaChange.FechaExpiracion;
cedulaToUpdate.IdLugarNacimiento = cedulaChange.IdLugarNacimiento;
cedulaToUpdate.IdMunicipio = cedulaChange.IdMunicipio;
cedulaToUpdate.IdOcupacion = cedulaChange.IdOcupacion;
cedulaToUpdate.IdSector = cedulaChange.IdSector;
cedulaToUpdate.FechaModificacion = DateTime.UtcNow.AddMinutes(-240);
bool result = Entities.SaveChanges() > 0;
if (result)
{
this.Close();
}
}
void Save()
{
var NewCedula = GetObject();
var Existe = Entities.Cedulas.Any(c => c.Nombre == NewCedula.Nombre && c.Apellido == NewCedula.Apellido);
if (!Existe) Entities.Cedulas.Add(NewCedula);
else
{
}
bool result = Entities.SaveChanges() > 0;
if (result)
{
this.Close();
}
}
bool ValidandoDatos()
{
msg = new List<string>();
bool result = true;
if (string.IsNullOrEmpty(tbNombre.Text))
{
msg.Add("El campo Nombre es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(tbApellido.Text))
{
msg.Add("El campo Apellido es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(tbApellido.Text))
{
msg.Add("El campo Apellido es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(tbDireccionResidencia.Text))
{
msg.Add("El campo Direccion Residencia es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(cbNacionalidad.Text))
{
msg.Add("El campo Nacionalidad es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(cbLugarNacimiento.Text))
{
msg.Add("El campo Lugar Nacimiento es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(cbSexo.Text))
{
msg.Add("El campo Sexo es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(cbTipoSangre.Text))
{
msg.Add("El campo Tipo de Sangre es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(cbOcupacion.Text))
{
msg.Add("El campo Ocupacion es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(cbEstadoCivil.Text))
{
msg.Add("El campo Estado Civil es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(cbMunicipio.Text))
{
msg.Add("El campo Municipio es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(cbSector.Text))
{
msg.Add("El campo Sector es Requerido.");
result = false;
}
if (string.IsNullOrEmpty(cbColegio.Text))
{
msg.Add("El campo Colegio es Requerido.");
result = false;
}
return result;
}
void LoadCbSector()
{
var cbSectorData = Entities.Sectors.Where(n => n.Estado == (int)EstadosEnum.Activo && n.IdMunicipio == cbMunicipio.SelectedIndex + 1).Select(n => new { id = n.Id, text = n.Descripcion }).ToList();
//necesita sacarlo de municipio
cbSectorData.ForEach(data =>
cbSector.Items.Insert(data.id - 1, data.text)
);
}
void LoadCbColegio()
{
var cbColegioData = Entities.Colegios.Where(n => n.Estado == (int)EstadosEnum.Activo && n.IdMunicipio == cbMunicipio.SelectedIndex + 1 && n.IdSector == cbSector.SelectedIndex + 1).Select(n => new { id = n.Id, text = n.Nombre }).ToList();
//necesita sacarlo de municipio y sector
cbColegioData.ForEach(data =>
cbColegio.Items.Insert(data.id - 1, data.text));
}
private void addButton_Click(object sender, EventArgs e)
{
var rnd = new Random();
try
{
if (ValidandoDatos())
{
if (cedulaToEditId != null)
{
update();
}
else
{
Save();
}
}
else
{
var list = string.Empty;
foreach (var item in msg)
{
list += item + "\n";
}
MessageBox.Show(list, "INTEC");
}
}
catch (Exception err)
{
Console.WriteLine(err);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void cbMunicipio_SelectionChangeCommitted(object sender, EventArgs e)
{
LoadCbSector();
}
private void cbSector_SelectionChangeCommitted(object sender, EventArgs e)
{
LoadCbColegio();
}
}
}
|
using System;
using System.Linq.Expressions;
using Bindable.Linq.Interfaces;
namespace Bindable.Linq
{
public static partial class BindableEnumerable
{
/// <summary>Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.</summary>
/// <returns>The single element of the input sequence.</returns>
/// <param name="source">An <see cref="IBindableCollection{TElement}" /> to return the single element of.</param>
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="source" /> is null.</exception>
/// <exception cref="T:System.InvalidOperationException">The input sequence contains more than one element.-or-The input sequence is empty.</exception>
public static IBindable<TSource> Single<TSource>(this IBindableCollection<TSource> source)
{
return source.FirstOrDefault();
}
/// <summary>Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.</summary>
/// <returns>The single element of the input sequence that satisfies a condition.</returns>
/// <param name="source">An <see cref="IBindableCollection{TElement}" /> to return a single element from.</param>
/// <param name="predicate">A function to test an element for a condition.</param>
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="source" /> or <paramref name="predicate" /> is null.</exception>
/// <exception cref="T:System.InvalidOperationException">No element satisfies the condition in <paramref name="predicate" />.-or-More than one element satisfies the condition in <paramref name="predicate" />.-or-The source sequence is empty.</exception>
public static IBindable<TSource> Single<TSource>(this IBindableCollection<TSource> source, Expression<Func<TSource, bool>> predicate) where TSource : class
{
return source.FirstOrDefault(predicate);
}
}
}
|
using Newtonsoft.Json;
using ShelterApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ShelterAPI.Models
{
public class AnimalFilter : ICloneable
{
public int Age { get; set; }
public int Weight { get; set; }
public int Size { get; set; }
public string Strain { get; set; }
public string OrderBy { get; set; }
private static IEnumerable<string> allowedOrderBy = new string[] { "Added", "Size" };
public AnimalFilter()
{
Age = 0;
Weight = 0;
Size = 0;
Strain = "";
OrderBy = "";
}
public bool ParametersExist()
{
return Age != 0 || Weight != 0 || Size != 0 || Strain.Length != 0;
}
public bool OrderParameterExist()
{
return OrderBy.Length != 0;
}
public object Clone()
{
var jsonString = JsonConvert.SerializeObject(this);
return JsonConvert.DeserializeObject(jsonString, this.GetType());
}
public IEnumerable<Animal> FilterAnimals(IEnumerable<Animal> animals) // filter animals by age, weight, size or strain
{
var result = animals.Where(a => (this.Age == 0 || a.Age == this.Age) &&
(this.Weight == 0 || a.Weight == this.Weight) &&
(this.Size == 0 || a.Size == this.Size) &&
(this.Strain.Length == 0 || a.Strain.Equals(this.Strain)));
return result;
}
public IEnumerable<Animal> SortAnimals(IEnumerable<Animal> animals) // filter animals by one of allowed parameter from allowedOrderBy collection
{
var propertyName = OrderBy.Split(" ")[0];
if (allowedOrderBy.Contains(propertyName))
{
if (OrderBy.EndsWith(" desc")) animals = animals.OrderByDescending(a => a.GetType().GetProperty(propertyName).GetValue(a, null));
else animals = animals.OrderBy(a => a.GetType().GetProperty(propertyName).GetValue(a, null));
}
return animals;
}
}
}
|
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== //
//
// Notes:
//
// ============================================================================ //
using System;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace EnhancedEditor.Editor
{
/// <summary>
/// Custom <see cref="InstanceTracker"/> editor.
/// </summary>
[CustomEditor(typeof(InstanceTracker)), CanEditMultipleObjects]
public class InstanceTrackerEditor : UnityObjectEditor
{
#region Styles
private static class Styles
{
public static readonly GUIStyle HeaderStyle = new GUIStyle(EditorStyles.label)
{
fontSize = 16,
fixedHeight = 22f
};
}
#endregion
#region Editor Content
private static readonly string multiObjectEditingMessage = $"{typeof(InstanceTracker).Name} does not support multi-object editing. " +
$"Please select only one object at a time to preview.";
private static readonly GUIContent headerGUI = new GUIContent();
private InstanceTracker tracker = null;
// -----------------------
public override bool UseDefaultMargins() => false;
protected override void OnEnable()
{
base.OnEnable();
// Multi-editing.
if (targets.Length > 1)
{
headerGUI.text = headerGUI.tooltip
= $"Multiple {typeof(InstanceTracker).Name} Preview";
return;
}
// Initialization.
tracker = target as InstanceTracker;
if (!tracker.Initialize())
return;
tracker.editor = this;
headerGUI.text = headerGUI.tooltip
= tracker.targetType.Name;
trackTabsGUI = new GUIContent[] { };
selectedTrackTab = -1;
selectedTrack = null;
selectedInstance = null;
// Callbacks.
EditorSceneManager.sceneOpened -= OnSceneOpened;
EditorSceneManager.sceneClosed -= OnSceneClosed;
EditorSceneManager.sceneOpened += OnSceneOpened;
EditorSceneManager.sceneClosed += OnSceneClosed;
// Get open scenes instances.
foreach (var _track in tracker.tracks)
{
_track.IsLoaded = false;
}
for (int _i = 0; _i < SceneManager.sceneCount; _i++)
{
Scene _scene = SceneManager.GetSceneAt(_i);
OnSceneOpened(_scene);
}
for (int _i = tracker.tracks.Length; _i-- > 0;)
{
var _track = tracker.tracks[_i];
if (!_track.OnEnabled())
{
tracker.RemoveTrack(_track);
}
}
// Sort the tracks on enabled as they can be renamed by users.
Array.Sort(tracker.tracks, (a, b) => a.SceneName.CompareTo(b.SceneName));
}
public override void OnInspectorGUI()
{
using (var _indentScope = new EditorGUI.IndentLevelScope())
{
GUILayout.Space(5f);
// Button.
EditorGUILayout.LabelField(headerGUI, Styles.HeaderStyle);
GUILayout.Space(7f);
// Multi editing is not allowed.
if (targets.Length > 1)
{
EditorGUILayout.HelpBox(multiObjectEditingMessage, UnityEditor.MessageType.Warning);
return;
}
// Tracker.
DrawUnloadedTracks();
DrawLoadedTracker();
}
}
protected override void OnDisable()
{
base.OnDisable();
if ((tracker != null) && (tracker.editor == this))
tracker.editor = null;
EditorSceneManager.sceneOpened -= OnSceneOpened;
EditorSceneManager.sceneClosed -= OnSceneClosed;
}
#endregion
#region GUI Draw
private const float UnloadedAreaHeight = 150f;
private const float ToolbarHeight = 22f;
private const float OpenSceneButtonWidth = 80f;
private const string NoOpenedTrackMessage = "There is no \"{0}\" instance in the open scene(s).";
private const string SelectTrackMessage = "Select a scene to look for \"{0}\" instances:";
private static readonly GUIContent instancePreviewGUI = new GUIContent("Preview", "Shows / Hides a preview of all instances in the selected scene.");
private static readonly GUIContent openSceneGUI = new GUIContent("Open Scene", "Opens the selected scene.");
private static readonly GUIContent openSceneSingleGUI = new GUIContent("Open Single");
private static readonly GUIContent openSceneAdditiveGUI = new GUIContent("Open Additive");
private static readonly GUIContent selectObjectGUI = new GUIContent("Select", "Select this object.");
private static readonly EditorColor sectionColor = new EditorColor(new Color(.65f, .65f, .65f), SuperColor.DarkGrey.Get());
private static readonly EditorColor peerColor = new EditorColor(new Color(.8f, .8f, .8f), new Color(.25f, .25f, .25f));
private static readonly EditorColor selectedColor = EnhancedEditorGUIUtility.GUISelectedColor;
private static readonly Color openButtonColor = SuperColor.Green.Get();
private GUIContent[] trackTabsGUI = new GUIContent[] { };
private int selectedTrackTab = -1;
private int trackSelectionControlID = -1;
private int instanceSelectionControlID = -1;
private string searchFilter = string.Empty;
private bool isInstancePreview = false;
[NonSerialized] private InstanceTracker.SceneTrack selectedUnloadedTrack = null;
[NonSerialized] private InstanceTracker.SceneTrack selectedTrack = null;
[NonSerialized] private Component selectedInstance = null;
private bool doFocusUnloadedTrack = false;
private Vector2 unloadedTracksScroll = new Vector2();
private Vector2 trackTabsScroll = new Vector2();
// -----------------------
private void DrawUnloadedTracks()
{
Rect _position;
trackSelectionControlID = EnhancedEditorGUIUtility.GetControlID(173, FocusType.Keyboard);
// As the horizontal toolbar scope doesn't accept any indent, use a zero indent scope.
using (var _zeroIndentScope = EnhancedEditorGUI.ZeroIndentScope())
using (var _scope = new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(EditorGUIUtility.singleLineHeight);
using (var _sectionScope = new EditorGUILayout.VerticalScope(GUILayout.Height(UnloadedAreaHeight)))
{
// Background.
_position = _sectionScope.rect;
EditorGUI.DrawRect(_position, sectionColor);
_position.y -= 1f;
_position.height += 2f;
GUI.Label(_position, GUIContent.none, EditorStyles.helpBox);
// Toolbar.
using (var _toolbarScope = new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
// Draw an empty button all over the toolbar to draw its bounds.
{
Rect _toolbarPosition = _toolbarScope.rect;
_toolbarPosition.xMin += 1f;
GUI.Label(_toolbarPosition, GUIContent.none, EditorStyles.toolbarButton);
}
// Search filter.
string _searchFilter = EnhancedEditorGUILayout.ToolbarSearchField(searchFilter);
if (_searchFilter != searchFilter)
{
searchFilter = _searchFilter;
_searchFilter = _searchFilter.ToLower();
foreach (var _track in tracker.tracks)
{
_track.UpdateVisibility(_searchFilter);
}
}
}
// Non-loaded scene tracks.
using (var _scroll = new GUILayout.ScrollViewScope(unloadedTracksScroll))
{
unloadedTracksScroll = _scroll.scrollPosition;
int _index = 0;
for (int _i = 0; _i < tracker.tracks.Length; _i++)
{
var _track = tracker.tracks[_i];
if (!_track.IsVisible)
continue;
// Visible track.
_position = EditorGUILayout.GetControlRect();
_position.xMin -= 2f;
_position.xMax += 2f;
_position.height += 2f;
bool _isSelected = selectedUnloadedTrack == _track;
EnhancedEditorGUI.BackgroundLine(_position, _isSelected, _index, selectedColor, peerColor);
Rect _temp = new Rect(_position)
{
xMin = _position.x + 10f
};
EditorGUI.LabelField(_temp, _track.SceneName);
GUIContent _label = EnhancedEditorGUIUtility.GetLabelGUI(_track.Instances.Length.ToString());
_temp.xMin = _temp.xMax - EditorStyles.label.CalcSize(_label).x - 5f;
EditorGUI.LabelField(_temp, _label);
// Scroll focus.
if (_isSelected && doFocusUnloadedTrack && (Event.current.type == EventType.Repaint))
{
Vector2 _areaSize = new Vector2(_position.x, UnloadedAreaHeight - 20f);
unloadedTracksScroll = EnhancedEditorGUIUtility.FocusScrollOnPosition(unloadedTracksScroll, _position, _areaSize);
doFocusUnloadedTrack = false;
Repaint();
}
// Track selection.
if (_position.Event(out Event _event) == EventType.MouseDown)
{
SelectUnloadedTrack(_track);
if (_event.clickCount == 2)
OpenSelectedScene();
_event.Use();
}
// Key selection.
if (_isSelected && (GUIUtility.keyboardControl == trackSelectionControlID))
{
int _switch = EnhancedEditorGUIUtility.VerticalKeys();
switch (_switch)
{
case -1:
for (int _j = _i; _j-- > 0;)
{
var _selectedTrack = tracker.tracks[_j];
if (_selectedTrack.IsVisible)
{
SelectUnloadedTrack(_selectedTrack);
break;
}
}
break;
case 1:
for (int _j = _i + 1; _j < tracker.tracks.Length; _j++)
{
var _selectedTrack = tracker.tracks[_j];
if (_selectedTrack.IsVisible)
{
SelectUnloadedTrack(_selectedTrack);
break;
}
}
break;
default:
break;
}
}
// Context click.
if (EnhancedEditorGUIUtility.ContextClick(_position))
{
GenericMenu _menu = new GenericMenu();
_menu.AddItem(openSceneSingleGUI, false, () =>
{
if (!SceneHandlerWindow.OpenSceneFromGUID(selectedUnloadedTrack.SceneGUID, OpenSceneMode.Single))
RemoveSelectedUnloadedTrack();
});
_menu.AddItem(openSceneAdditiveGUI, false, () =>
{
if (!SceneHandlerWindow.OpenSceneFromGUID(selectedUnloadedTrack.SceneGUID, OpenSceneMode.Additive))
RemoveSelectedUnloadedTrack();
});
_menu.ShowAsContext();
}
_index++;
}
GUILayout.Space(5f);
}
// Unselect on empty space click.
if (EnhancedEditorGUIUtility.MouseDown(_sectionScope.rect))
selectedUnloadedTrack = null;
}
GUILayout.Space(10f);
}
GUILayout.Space(5f);
// Selected track operations.
bool _enabled = selectedUnloadedTrack != null;
_position = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(true, 20f));
_position.xMax -= OpenSceneButtonWidth + 10f;
if (_enabled)
{
isInstancePreview = EditorGUI.Foldout(_position, isInstancePreview, instancePreviewGUI, true);
}
_position.xMin = _position.xMax;
_position.width = OpenSceneButtonWidth;
using (var _enabledScope = EnhancedGUI.GUIEnabled.Scope(_enabled))
using (var _colorScope = EnhancedGUI.GUIColor.Scope(openButtonColor))
{
if (GUI.Button(_position, openSceneGUI))
{
OpenSelectedScene();
}
}
// Selected track preview.
if (isInstancePreview && _enabled)
{
using (var _indentScope = new EditorGUI.IndentLevelScope())
{
for (int _i = 0; _i < selectedUnloadedTrack.Instances.Length; _i++)
{
string _instance = selectedUnloadedTrack.Instances[_i];
_position = EditorGUILayout.GetControlRect();
Rect _temp = new Rect(_position)
{
x = 0f,
width = EditorGUIUtility.currentViewWidth
};
EnhancedEditorGUI.BackgroundLine(_temp, false, _i);
EditorGUI.LabelField(_position, _instance);
}
}
}
}
private void DrawLoadedTracker()
{
GUILayout.Space(10f);
// No track to select instances.
if (selectedTrack == null)
{
EditorGUILayout.HelpBox(string.Format(NoOpenedTrackMessage, tracker.targetType.Name), UnityEditor.MessageType.Warning);
return;
}
// Scene selection.
EditorGUILayout.HelpBox(string.Format(SelectTrackMessage, tracker.targetType.Name), UnityEditor.MessageType.Info);
GUILayout.Space(5f);
using (var _scope = new GUILayout.ScrollViewScope(trackTabsScroll))
{
trackTabsScroll = _scope.scrollPosition;
int _selectedTrackTab = EnhancedEditorGUILayout.CenteredToolbar(selectedTrackTab, trackTabsGUI, GUILayout.Height(ToolbarHeight));
if (_selectedTrackTab != selectedTrackTab)
{
SelectTrack(_selectedTrackTab);
}
}
GUILayout.Space(2f);
instanceSelectionControlID = EnhancedEditorGUIUtility.GetControlID(173, FocusType.Keyboard);
// Draw all scene instances.
Event _event;
int _index = 0;
for (int _i = 0; _i < selectedTrack.SceneInstances.Count; _i++)
{
Component _instance = selectedTrack.SceneInstances[_i];
if (_instance == null)
continue;
Rect _position = EditorGUILayout.GetControlRect(true, 20f);
Rect _temp = new Rect(_position);
bool _isSelected = selectedInstance == _instance;
_position.x = 0f;
_position.width = EditorGUIUtility.currentViewWidth;
EnhancedEditorGUI.BackgroundLine(_position, _isSelected, _index);
EditorGUI.LabelField(_temp, _instance.name);
_index++;
// Select button.
_temp.xMin = _temp.xMax - 50f;
_temp.y += 1f;
_temp.height -= 2f;
if (GUI.Button(_temp, selectObjectGUI))
{
EditorGUIUtility.PingObject(_instance);
Selection.activeObject = _instance;
}
// Selection.
if (_position.Event(out _event) == EventType.MouseDown)
{
SelectInstance(_instance);
switch (_event.clickCount)
{
case 1:
EditorGUIUtility.PingObject(_instance);
break;
case 2:
Selection.activeObject = _instance;
break;
}
_event.Use();
}
// Keyboard focus.
if (_isSelected && (GUIUtility.keyboardControl == instanceSelectionControlID))
{
int _switch = EnhancedEditorGUIUtility.VerticalKeys();
if (_switch != 0)
{
int _selectedIndex = Mathf.Clamp(_i + _switch, 0, selectedTrack.SceneInstances.Count - 1);
SelectInstance(selectedTrack.SceneInstances[_selectedIndex]);
}
else if ((_event.type == EventType.KeyDown) && (_event.keyCode == KeyCode.Return))
{
EditorGUIUtility.PingObject(_instance);
_event.Use();
}
}
}
// Unselect instance on empty space click.
_event = Event.current;
if (_event.type == EventType.MouseDown)
{
selectedInstance = null;
_event.Use();
}
}
#endregion
#region Scene Callback
private void OnSceneOpened(Scene _scene, OpenSceneMode _mode = OpenSceneMode.Single)
{
if (!_scene.isLoaded || !_scene.IsValid() || string.IsNullOrEmpty(_scene.path))
return;
// Load instances.
string _guid = AssetDatabase.AssetPathToGUID(_scene.path);
foreach (var _track in tracker.tracks)
{
if (_track.Load(_scene, _guid, tracker.targetType))
{
OnNewTrack(_track);
break;
}
}
}
private void OnSceneClosed(Scene _scene)
{
if (!_scene.IsValid() || string.IsNullOrEmpty(_scene.path))
return;
// Close scene.
string _guid = AssetDatabase.AssetPathToGUID(_scene.path);
foreach (var _track in tracker.tracks)
{
if (_track.Close(_guid))
{
OnRemoveTrack(_track);
_track.UpdateVisibility(searchFilter.ToLower());
break;
}
}
}
#endregion
#region Tracker Callback
internal void OnNewTrack(InstanceTracker.SceneTrack _track)
{
GUIContent _tabGUI = new GUIContent(_track.SceneName, _track.SceneName);
ArrayUtility.Add(ref trackTabsGUI, _tabGUI);
SelectTrack(Mathf.Max(0, selectedTrackTab));
}
internal void OnRemoveTrack(InstanceTracker.SceneTrack _track)
{
int _index = Array.FindIndex(trackTabsGUI, t => t.text == _track.SceneName);
if (_index > -1)
{
ArrayUtility.RemoveAt(ref trackTabsGUI, _index);
SelectTrack(Mathf.Min(trackTabsGUI.Length - 1, selectedTrackTab));
}
}
#endregion
#region Utility
private void OpenSelectedScene()
{
if (!SceneHandlerWindow.OpenSceneFromGUID(selectedUnloadedTrack.SceneGUID))
{
RemoveSelectedUnloadedTrack();
}
}
private void RemoveSelectedUnloadedTrack()
{
tracker.RemoveTrack(selectedUnloadedTrack);
selectedUnloadedTrack = null;
}
private void SelectUnloadedTrack(InstanceTracker.SceneTrack _track)
{
selectedUnloadedTrack = _track;
doFocusUnloadedTrack = true;
GUIUtility.keyboardControl = trackSelectionControlID;
}
private void SelectTrack(int _selectedTrackTab)
{
int _index = _selectedTrackTab;
selectedTrackTab = _selectedTrackTab;
foreach (var _track in tracker.tracks)
{
if (_track.IsLoaded)
{
if (_index == 0)
{
selectedTrack = _track;
return;
}
_index--;
}
}
selectedTrack = null;
}
private void SelectInstance(Component _component)
{
selectedInstance = _component;
GUIUtility.keyboardControl = instanceSelectionControlID;
}
#endregion
}
}
|
namespace Contoso.XPlatform.Constants
{
/// <summary>
/// The keys match the workflow variable's member name property.
/// Typically for reference types the member name is typeof(T).FullName.
/// For literals we more unique names to interact with the workflow from the code.
/// </summary>
public struct FlowDataCacheItemKeys
{
public const string Get_Selector_Success = nameof(Get_Selector_Success);
public const string SearchText = nameof(SearchText);
public const string SkipCount = nameof(SkipCount);
}
}
|
// Copyright 2021 Google Inc. 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 NtApiDotNet.Win32.Security.Native;
using System;
namespace NtApiDotNet.Win32.Security.Buffers
{
/// <summary>
/// A security buffer which can only be an output.
/// </summary>
public sealed class SecurityBufferOut : SecurityBuffer
{
private byte[] _array;
private int _size;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">The type of buffer.</param>
/// <param name="size">The size of the output buffer.</param>
public SecurityBufferOut(SecurityBufferType type, int size) : base(type)
{
_size = size;
}
/// <summary>
/// Convert to buffer back to an array.
/// </summary>
/// <returns>The buffer as an array.</returns>
public override byte[] ToArray()
{
if (_array == null)
throw new InvalidOperationException("Can't access buffer until it's been populated.");
return _array;
}
internal override SecBuffer ToBuffer(DisposableList list)
{
return SecBuffer.Create(_type, _size, list);
}
internal override void FromBuffer(SecBuffer buffer)
{
_array = buffer.ToArray();
_size = _array.Length;
_type = buffer.BufferType;
}
}
}
|
using Swiddler.ChunkViews;
using Swiddler.DataChunks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
namespace Swiddler.Rendering
{
public class SelectionLayer : FragmentLayer
{
public FilledFragment HighlightFragment { get; } = new FilledFragment(); // highlight drawing
public FilledFragment SelectionFragment { get; } = new FilledFragment();
public Fragment CurrentlySelectedFragment { get; set; } // actual selected fragment
public Fragment CurrentlyHighlightedFragment { get; set; } // actual highlighted fragment
public SelectionAnchorCaret SelectionStart { get; private set; }
public SelectionAnchorCaret SelectionEnd { get; private set; }
readonly List<Fragment> fragments = new List<Fragment>();
public SelectionLayer(FragmentView owner) : base(owner)
{
fragments.Add(HighlightFragment);
fragments.Add(SelectionFragment);
foreach (var f in fragments) f.Layer = this;
if (App.Current != null) // design mode
{
SelectionFragment.Brush = App.Current.Res.SelectionBrush;
SelectionFragment.Pen = App.Current.Res.SelectionPen;
}
SelectionFragment.MouseEnter = () => SelectionMouseOver(true);
SelectionFragment.MouseLeave = () => SelectionMouseOver(false);
}
private void SelectionMouseOver(bool hovered)
{
Owner.Mouse.IsOverSelection = hovered;
Owner.UpdateCursor();
}
public override void ArrangeViewport()
{
fragments.ForEach(x => x.Visualise());
}
public override void Clear()
{
base.Clear();
CurrentlySelectedFragment?.MouseLeave();
CurrentlyHighlightedFragment?.MouseLeave();
foreach (var f in fragments) f.Recycle();
ResetSelection();
}
public void ResetSelection()
{
SelectionStart = null;
SelectionEnd = null;
UpdateSelectionPolygon();
}
public void SetSelection(SelectionAnchorCaret start, SelectionAnchorCaret end)
{
if (start != null)
{
SelectionStart = start;
Owner.Content.SelectionStart = start.Anchor;
}
SelectionEnd = end;
Owner.Content.SelectionEnd = end.Anchor;
UpdateSelectionPolygon();
}
public override void MouseChanged(MouseState mouse)
{
if (!mouse.IsCaptured && SelectionFragment.Contains(mouse.Position))
{
TrySetMouseHover(SelectionFragment);
}
LeaveUnhoveredFragments(mouse);
}
void UpdateSelectionPolygon()
{
SelectionFragment.Polgyons = CreateSelectionPolygons(SelectionStart, SelectionEnd, out var bounds);
if (SelectionFragment.Polgyons != null)
SelectionFragment.Bounds = bounds;
}
PolygonFigure[] CreateSelectionPolygons(SelectionAnchorCaret start, SelectionAnchorCaret end, out Rect bounds)
{
bounds = default;
if (start == null || end == null) return null;
if (start.Anchor.Equals(end.Anchor)) return null;
if (start.Anchor.CompareTo(end.Anchor) > 0) // swap when start > end
{
var _ = start;
start = end;
end = _;
}
var content = Owner.Content;
return FilledFragment.CreatePolygons(
start.Bounds.TopLeft, end.Bounds.TopLeft, content.LineHeight,
content.SnapToPixelsX(content.Metrics.Viewport.Width - content.DpiScale.X), out bounds);
}
public void SetSelection(SelectionAnchorCaret caret)
{
var content = Owner.Content;
if (content.SelectionStart == null)
SetSelection(caret, caret);
else
SetSelection(null, caret);
}
public bool TrySetSelection(Fragment fragment)
{
if (fragment.IsSelectable)
{
var caret = new SelectionAnchorCaret() { Fragment = fragment };
fragment.Source.PrepareSelectionAnchor(caret);
SetSelection(caret);
if (Owner.Mouse.SelectWholeChunks)
{
SelectionStart = null;
SelectionEnd = null;
var content = Owner.Content;
if (content.SelectionStart.CompareTo(content.SelectionEnd) > 0)
{
if (Owner.Content.SelectionStart.Chunk is Packet startPacket)
{
content.SelectionStart = new SelectionAnchor() { Chunk = content.SelectionStart.Chunk, Offset = startPacket.Payload.Length }; ;
content.SelectionEnd.Offset = 0;
}
}
else
{
if (Owner.Content.SelectionEnd.Chunk is Packet endPacket)
{
content.SelectionStart.Offset = 0;
content.SelectionEnd = new SelectionAnchor() { Chunk = content.SelectionEnd.Chunk, Offset = endPacket.Payload.Length };
}
}
AdjustSelectionAnchors();
}
return true;
}
return false;
}
public void SetNearestSelection(Fragment fragment, Point mousePosition)
{
if (fragment.IsSelectable)
{
TrySetSelection(fragment);
return;
}
var prev = fragment.PreviousSelectable;
var next = fragment.NextSelectable?.Fragment;
if (prev == null && next == null) return;
double prevDist = double.MaxValue, nextDist = double.MaxValue;
if (prev != null) prevDist = GetPointDistance(prev.Bounds, mousePosition);
if (next != null) nextDist = GetPointDistance(next.Bounds, mousePosition);
TrySetSelection(prevDist < nextDist ? prev : next);
}
private double GetPointDistance(Rect bounds, Point point)
{
if (point.Y > bounds.Bottom)
return point.Y - bounds.Bottom;
else if (point.Y < bounds.Top)
return bounds.Top - point.Y;
else
{
if (point.X > bounds.Right)
return point.X - bounds.Right;
else if (point.X < bounds.Left)
return bounds.Left - point.X;
else
return 0; // point is inside box
}
}
public void AdjustSelectionAnchors()
{
bool updated = false;
SelectionStart = UpdateCaret(Owner.Content.SelectionStart, SelectionStart, ref updated);
SelectionEnd = UpdateCaret(Owner.Content.SelectionEnd, SelectionEnd, ref updated);
if (updated) UpdateSelectionPolygon();
}
SelectionAnchorCaret UpdateCaret(SelectionAnchor anchor, SelectionAnchorCaret caret, ref bool updated)
{
if (anchor != null && caret == null)
{
updated = true;
caret = new SelectionAnchorCaret() { Anchor = anchor };
var content = Owner.Content;
if (anchor.Chunk.SequenceNumber < content.TextLayer.Items.FirstOrDefault()?.Source.BaseChunk.SequenceNumber)
{
caret.Bounds = new Rect(0, -content.LineHeight, 0, 0);
}
else if (anchor.Chunk.SequenceNumber > content.TextLayer.Items.LastOrDefault()?.Source.BaseChunk.SequenceNumber)
{
caret.Bounds = new Rect(0, Math.Max(content.Metrics.Viewport.Height, content.TextLayer.Height) + content.LineHeight, 0, 0);
}
else
{
var chunkView = content.TryGetChunkView(anchor.Chunk.SequenceNumber);
if (chunkView != null)
{
if (chunkView.FirstFragmentIndex != -1 && chunkView.LastFragmentIndex != -1)
chunkView.PrepareSelectionAnchor(caret);
else
Debug.Assert(false);
}
}
}
return caret;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Evpro.Service.Pattern
{
public interface IMyServiceGeneric<T> : IDisposable where T : class
{
void Add(T t);
void Delete(T t);
void Update(T t);
T GetById(int id);
T GetById(string id);
IEnumerable<T> GetMany(Expression<Func<T, bool>> condition = null, Expression<Func<T, bool>> orderBy = null);//Type Expresion lamda , Null pour
void DeletebyCondition(Expression<Func<T, bool>> condition);
void commit();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmsChapter1
{
public class _1_1_30_ArrayExcercise
{
/*
* Array exercise. Write a code fragment that creates an N-by-N boolean array a[][]
* such that a[i][j] is true if i and j are relatively prime (have no common factors), and false otherwise.
*/
public bool[,] ArrayExcercise(int m, int n)
{
bool[,] res = new bool[m, n];
for(int i =1;i< m;i++)
{
for(int j = 1;j<n;j++)
{
if(Elucid(i,j) > 1)
{
res[i,j] = true;
}
}
}
return res;
}
private int Elucid(int i, int j)
{
if (j == 0)
return j;
int r = i % j;
return Elucid(j, r);
}
}
}
|
using OtelProjesi.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;
namespace OtelProjesi.Formlar.Misafir
{
public partial class FrmMisafirListesi : Form
{
public FrmMisafirListesi()
{
InitializeComponent();
}
DbOtelEntities db = new DbOtelEntities();
private void FrmMisafirListesi_Load(object sender, EventArgs e)
{
gridControl1.DataSource = (from x in db.TBLMISAFIR
select new
{
x.MISAFIRID,
x.ADSOYAD,
x.TC,
x.TELEFON,
x.MAIL,
x.iller.sehir,
x.ilceler.ilce
}).ToList();
}
private void gridControl1_DoubleClick(object sender, EventArgs e)
{
FrmMisafirKart frm = new FrmMisafirKart();
frm.id = int.Parse(gridView1.GetFocusedRowCellValue("MISAFIRID").ToString());
frm.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TTT
{
class Player
{
public static string ChooseChip()
{
String choice = "";
do
{
Console.Write("Player 1, choose a chip! X or O: ");
choice = Console.ReadLine().ToUpper();
if (choice == "X" || choice == "O")
{
break;
}
} while (choice != "X" || choice != "O");
return choice;
}
public static int ChoosePosition(int player)
{
int choice = 0;
bool isNumber = false;
while (!isNumber)
{
Console.Write("Player {0}, pick a position: ", player);
String input = Console.ReadLine();
var isNumeric = int.TryParse(input, out choice);
if (isNumeric)
{
if (choice < 10 && choice > 0)
{
isNumber = true;
}
else
{
continue;
}
}
else
{
continue;
}
}
return choice;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#region using Lucene.Net
using Analysis = Lucene.Net.Analysis;
using Documents = Lucene.Net.Documents;
using Index = Lucene.Net.Index;
using Standard = Lucene.Net.Analysis.Standard;
using Messages = Lucene.Net.Messages;
using QueryParsers = Lucene.Net.QueryParsers;
using Search = Lucene.Net.Search;
using Store = Lucene.Net.Store;
using Util = Lucene.Net.Util;
using Newtonsoft.Json;
#endregion
namespace Channel.Mine.IMDB.Actions
{
public class IndexBuilder : Framework.Abstraction.BaseAction<Collections.MediaCollection>
{
public String IndexPath { get; private set; }
public IndexBuilder(String indexPath)
{
this.IndexPath = indexPath;
}
public override void DoAction(Collections.MediaCollection mediaCollection)
{
Store.Directory directory = Store.FSDirectory.GetDirectory(this.IndexPath, true);
Standard.StandardAnalyzer analyzer = new Standard.StandardAnalyzer(Util.Version.LUCENE_29);
Index.IndexWriter writer = new Index.IndexWriter(directory, analyzer, true, Index.IndexWriter.MaxFieldLength.UNLIMITED);
Documents.Document document = null;
Documents.Field newField = null;
foreach (Entities.Media mediaItem in mediaCollection)
{
document = new Documents.Document();
document.Add(new Documents.Field("MediaType", Enum.GetName(typeof(Entities.MediaTypeEnum), mediaItem.MediaType), Documents.Field.Store.YES, Documents.Field.Index.NOT_ANALYZED, Documents.Field.TermVector.YES));
document.Add(new Documents.Field("Title", mediaItem.Title, Documents.Field.Store.YES, Documents.Field.Index.ANALYZED, Documents.Field.TermVector.YES));
document.Add(new Documents.Field("EpisodeName", mediaItem.EpisodeName, Documents.Field.Store.YES, Documents.Field.Index.ANALYZED, Documents.Field.TermVector.YES));
document.Add(new Documents.Field("EpisodeNo", mediaItem.EpisodeNo.ToString(), Documents.Field.Store.YES, Documents.Field.Index.NOT_ANALYZED, Documents.Field.TermVector.YES));
document.Add(new Documents.Field("SeasonNo", mediaItem.SeasonNo.ToString(), Documents.Field.Store.YES, Documents.Field.Index.NOT_ANALYZED, Documents.Field.TermVector.YES));
document.Add(new Documents.Field("Genre", String.Join(", ", mediaItem.Genres), Documents.Field.Store.YES, Documents.Field.Index.ANALYZED, Documents.Field.TermVector.YES));
document.Add(new Documents.Field("Names", String.Join(", ", mediaItem.Names), Documents.Field.Store.YES, Documents.Field.Index.ANALYZED, Documents.Field.TermVector.YES));
document.Add(new Documents.Field("ReleaseYear", mediaItem.ReleaseYear, Documents.Field.Store.YES, Documents.Field.Index.NOT_ANALYZED, Documents.Field.TermVector.YES));
document.Add(new Documents.Field("Object", JsonConvert.SerializeObject(mediaItem), Documents.Field.Store.YES, Documents.Field.Index.NOT_ANALYZED, Documents.Field.TermVector.NO));
writer.AddDocument(document);
}
writer.Commit();
writer.Optimize();
writer.Close();
analyzer.Close();
directory.Close();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace IntegracaoMFE.Utils
{
public static class Criptografia
{
public static string MD5(string conteudo)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(conteudo));
return BitConverter.ToString(bytes).Replace("-", "");
}
}
}
|
// Accord Machine Learning Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// 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 St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.MachineLearning
{
using System;
using System.Linq;
using Accord.Math;
using Accord.Math.Distances;
/// <summary>
/// K-Nearest Neighbor (k-NN) algorithm.
/// </summary>
///
/// <typeparam name="T">The type of the input data.</typeparam>
///
/// <remarks>
/// <para> The k-nearest neighbor algorithm (k-NN) is a method for classifying objects
/// based on closest training examples in the feature space. It is amongst the simplest
/// of all machine learning algorithms: an object is classified by a majority vote of
/// its neighbors, with the object being assigned to the class most common amongst its
/// k nearest neighbors (k is a positive integer, typically small).</para>
///
/// <para>If k = 1, then the object is simply assigned to the class of its nearest neighbor.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description>
/// Wikipedia contributors. "K-nearest neighbor algorithm." Wikipedia, The
/// Free Encyclopedia. Wikipedia, The Free Encyclopedia, 10 Oct. 2012. Web.
/// 9 Nov. 2012. http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm </description></item>
/// </list>
/// </para>
/// </remarks>
///
/// <example>
/// <para>The following example shows how to create
/// and use a k-Nearest Neighbor algorithm to classify
/// a set of numeric vectors.</para>
///
/// <code>
/// // Create some sample learning data. In this data,
/// // the first two instances belong to a class, the
/// // four next belong to another class and the last
/// // three to yet another.
///
/// double[][] inputs =
/// {
/// // The first two are from class 0
/// new double[] { -5, -2, -1 },
/// new double[] { -5, -5, -6 },
///
/// // The next four are from class 1
/// new double[] { 2, 1, 1 },
/// new double[] { 1, 1, 2 },
/// new double[] { 1, 2, 2 },
/// new double[] { 3, 1, 2 },
///
/// // The last three are from class 2
/// new double[] { 11, 5, 4 },
/// new double[] { 15, 5, 6 },
/// new double[] { 10, 5, 6 },
/// };
///
/// int[] outputs =
/// {
/// 0, 0, // First two from class 0
/// 1, 1, 1, 1, // Next four from class 1
/// 2, 2, 2 // Last three from class 2
/// };
///
///
/// // Now we will create the K-Nearest Neighbors algorithm. For this
/// // example, we will be choosing k = 4. This means that, for a given
/// // instance, its nearest 4 neighbors will be used to cast a decision.
/// KNearestNeighbors knn = new KNearestNeighbors(k: 4, classes: 3,
/// inputs: inputs, outputs: outputs);
///
///
/// // After the algorithm has been created, we can classify a new instance:
/// int answer = knn.Compute(new double[] { 11, 5, 4 }); // answer will be 2.
/// </code>
///
///
/// <para>The k-Nearest neighbor algorithm implementation in the
/// framework can also be used with any instance data type. For
/// such cases, the framework offers a generic version of the
/// classifier, as shown in the example below.</para>
///
/// <code>
/// // The k-Nearest Neighbors algorithm can be used with
/// // any kind of data. In this example, we will see how
/// // it can be used to compare, for example, Strings.
///
/// string[] inputs =
/// {
/// "Car", // class 0
/// "Bar", // class 0
/// "Jar", // class 0
///
/// "Charm", // class 1
/// "Chair" // class 1
/// };
///
/// int[] outputs =
/// {
/// 0, 0, 0, // First three are from class 0
/// 1, 1, // And next two are from class 1
/// };
///
///
/// // Now we will create the K-Nearest Neighbors algorithm. For this
/// // example, we will be choosing k = 1. This means that, for a given
/// // instance, only its nearest neighbor will be used to cast a new
/// // decision.
///
/// // In order to compare strings, we will be using Levenshtein's string distance
/// KNearestNeighbors<string> knn = new KNearestNeighbors<string>(k: 1, classes: 2,
/// inputs: inputs, outputs: outputs, distance: Distance.Levenshtein);
///
///
/// // After the algorithm has been created, we can use it:
/// int answer = knn.Compute("Chars"); // answer should be 1.
/// </code>
/// </example>
///
/// <seealso cref="KNearestNeighbors"/>
///
[Serializable]
public class KNearestNeighbors<T>
{
private int k;
private T[] inputs;
private int[] outputs;
private int classCount;
private IDistance<T> distance;
private double[] distances;
/// <summary>
/// Creates a new <see cref="KNearestNeighbors"/>.
/// </summary>
///
/// <param name="k">The number of nearest neighbors to be used in the decision.</param>
///
/// <param name="inputs">The input data points.</param>
/// <param name="outputs">The associated labels for the input points.</param>
/// <param name="distance">The distance measure to use in the decision.</param>
///
public KNearestNeighbors(int k, T[] inputs, int[] outputs, IDistance<T> distance)
{
checkArgs(k, null, inputs, outputs, distance);
int classCount = outputs.Distinct().Count();
initialize(k, classCount, inputs, outputs, distance);
}
/// <summary>
/// Creates a new <see cref="KNearestNeighbors"/>.
/// </summary>
///
/// <param name="k">The number of nearest neighbors to be used in the decision.</param>
/// <param name="classes">The number of classes in the classification problem.</param>
///
/// <param name="inputs">The input data points.</param>
/// <param name="outputs">The associated labels for the input points.</param>
/// <param name="distance">The distance measure to use in the decision.</param>
///
public KNearestNeighbors(int k, int classes, T[] inputs, int[] outputs, IDistance<T> distance)
{
checkArgs(k, classes, inputs, outputs, distance);
initialize(k, classes, inputs, outputs, distance);
}
private void initialize(int k, int classes, T[] inputs, int[] outputs, IDistance<T> distance)
{
this.inputs = inputs;
this.outputs = outputs;
this.k = k;
this.classCount = classes;
this.distance = distance;
this.distances = new double[inputs.Length];
}
/// <summary>
/// Gets the set of points given
/// as input of the algorithm.
/// </summary>
///
/// <value>The input points.</value>
///
public T[] Inputs
{
get { return inputs; }
}
/// <summary>
/// Gets the set of labels associated
/// with each <see cref="Inputs"/> point.
/// </summary>
///
public int[] Outputs
{
get { return outputs; }
}
/// <summary>
/// Gets the number of class labels
/// handled by this classifier.
/// </summary>
///
public int ClassCount
{
get { return classCount; }
}
/// <summary>
/// Gets or sets the distance function used
/// as a distance metric between data points.
/// </summary>
///
public IDistance<T> Distance
{
get { return distance; }
set { distance = value; }
}
/// <summary>
/// Gets or sets the number of nearest
/// neighbors to be used in the decision.
/// </summary>
///
/// <value>The number of neighbors.</value>
///
public int K
{
get { return k; }
set
{
if (value <= 0 || value > inputs.Length)
throw new ArgumentOutOfRangeException("value",
"The value for k should be greater than zero and less than total number of input points.");
k = value;
}
}
/// <summary>
/// Computes the most likely label of a new given point.
/// </summary>
///
/// <param name="input">A point to be classified.</param>
///
/// <returns>The most likely label for the given point.</returns>
///
public int Compute(T input)
{
double[] scores;
return Compute(input, out scores);
}
/// <summary>
/// Computes the most likely label of a new given point.
/// </summary>
///
/// <param name="input">A point to be classified.</param>
/// <param name="response">A value between 0 and 1 giving
/// the strength of the classification in relation to the
/// other classes.</param>
///
/// <returns>The most likely label for the given point.</returns>
///
public int Compute(T input, out double response)
{
double[] scores;
int result = Compute(input, out scores);
response = scores[result] / scores.Sum();
return result;
}
/// <summary>
/// Computes the most likely label of a new given point.
/// </summary>
///
/// <param name="input">A point to be classified.</param>
/// <param name="scores">The distance score for each possible class.</param>
///
/// <returns>The most likely label for the given point.</returns>
///
public virtual int Compute(T input, out double[] scores)
{
// Compute all distances
for (int i = 0; i < inputs.Length; i++)
distances[i] = distance.Distance(input, inputs[i]);
int[] idx = distances.Bottom(k, inPlace: true);
scores = new double[classCount];
for (int i = 0; i < idx.Length; i++)
{
int j = idx[i];
int label = outputs[j];
double d = distances[i];
// Convert to similarity measure
scores[label] += 1.0 / (1.0 + d);
}
// Get the maximum weighted score
int result; scores.Max(out result);
return result;
}
/// <summary>
/// Gets the top <see cref="KNearestNeighbors{T}.K"/> points that are the closest
/// to a given <paramref name="input"> reference point</paramref>.
/// </summary>
///
/// <param name="input">The query point whose neighbors will be found.</param>
/// <param name="labels">The label for each neighboring point.</param>
///
/// <returns>
/// An array containing the top <see cref="KNearestNeighbors{T}.K"/> points that are
/// at the closest possible distance to <paramref name="input"/>.
/// </returns>
///
public virtual T[] GetNearestNeighbors(T input, out int[] labels)
{
// Compute all distances
for (int i = 0; i < inputs.Length; i++)
distances[i] = distance.Distance(input, inputs[i]);
int[] idx = distances.Bottom(k, inPlace: true);
labels = outputs.Submatrix(idx);
return inputs.Submatrix(idx);
}
private static void checkArgs(int k, int? classes, T[] inputs, int[] outputs, IDistance<T> distance)
{
if (k <= 0)
throw new ArgumentOutOfRangeException("k", "Number of neighbors should be greater than zero.");
if (classes != null && classes <= 0)
throw new ArgumentOutOfRangeException("k", "Number of classes should be greater than zero.");
if (inputs == null)
throw new ArgumentNullException("inputs");
if (outputs == null)
throw new ArgumentNullException("inputs");
if (inputs.Length != outputs.Length)
throw new DimensionMismatchException("outputs",
"The number of input vectors should match the number of corresponding output labels");
if (distance == null)
throw new ArgumentNullException("distance");
}
}
}
|
namespace TipsAndTricksLibrary.Redis.StackExhange
{
using System;
using System.Collections.Generic;
using Converters;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
public class CacheConnectionsFactory : ICacheConnectionsFactory
{
private readonly ConnectionMultiplexer _connectionMultiplexer;
protected bool Disposed;
public CacheConnectionsFactory(IOptions<CacheConnectionsFactoryOptions> options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
if (string.IsNullOrWhiteSpace(options.Value.Redis))
throw new ArgumentNullException(nameof(CacheConnectionsFactoryOptions.Redis));
var configuration = ConfigurationOptions.Parse(options.Value.Redis);
configuration.CommandMap = CommandMap.Create(new HashSet<string> {"SUBSCRIBE"}, false);
configuration.SocketManager = new SocketManager("Custom", true);
_connectionMultiplexer = ConnectionMultiplexer.Connect(configuration);
_connectionMultiplexer.IncludeDetailInExceptions = true;
}
private void ValidateStatus()
{
if (Disposed)
throw new ObjectDisposedException(nameof(ConnectionMultiplexer));
}
public ICacheConnection Create()
{
ValidateStatus();
return new CacheConnection(_connectionMultiplexer.GetDatabase(), new KeysConverter(), new ValuesConverter());
}
protected virtual void Dispose(bool disposing)
{
if (Disposed)
return;
if (disposing)
_connectionMultiplexer?.Dispose();
Disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~CacheConnectionsFactory()
{
Dispose(false);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TutEngine;
namespace TutGame
{
class Program
{
public static void Main(String[] args)
{
Game game;
game = new Game(500,500, "silla");
}
}
}
|
using System;
using CallCenter.Client.ViewModel.Helpers;
namespace CallCenter.Client.ViewModel.ViewModels
{
public class SettingWindowViewModel : OkCancelViewModel
{
private readonly ISettings settings;
private string serverName;
private int serverPort;
public SettingWindowViewModel(IWindowService windowService, ISettings settings) : base(windowService)
{
if (windowService == null)
throw new ArgumentNullException("windowService");
if(settings == null)
throw new ArgumentNullException("settings");
this.settings = settings;
this.ServerName = this.settings.ServerName;
this.ServerPort = this.settings.ServerPort;
}
public string ServerName
{
get
{
return this.serverName;
}
set
{
this.serverName = value;
this.RaisePropertyChanged();
}
}
public int ServerPort
{
get
{
return this.serverPort;
}
set
{
this.serverPort = value;
this.RaisePropertyChanged();
}
}
public override ViewModelType Type
{
get
{
return ViewModelType.SettingsWindow;
}
}
protected override void OnOkExecuted(object parameter)
{
this.settings.ServerName = this.serverName;
this.settings.ServerPort = this.serverPort;
this.Close();
}
protected override void OnCancelExecuted(object parameter)
{
this.Close();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace TailorIT.API.Commands.Common
{
public abstract class AbstractCommand
{
public void Validate()
{
var context = new ValidationContext(this);
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(this, context, results, true);
if (!isValid)
{
List<ErrorDetailException> errors = results.Select(item => new ErrorDetailException(item.MemberNames.FirstOrDefault(), item.ErrorMessage)).ToList();
throw new BadRequestException("erros de validação encontrados.", errors);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmsChapter1
{
public class _1_2_7_MysteryMethod
{
/*
* What does the following recursive fucntion return?
* I guess it is reverse of the string.
*/
public string mystery(string s)
{
int N = s.Length;
if (N <= 1) return s;
string a = s.Substring(0,N/2);
string b = s.Substring(N / 2 , N - N / 2);
return mystery(b) + mystery(a);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Section01 {
class Program {
static void Main(string[] args) {
/*var names = new List<string> {
"Tokyo", "New Delhi", "Bangkok", "London", "Paris", "Berlin", "Canberra", "Hong Kong",};
IEnumerable<string> query = names.Where(s => s.Length <= 5).
Select(s => s.ToLower()) ;//抽出されたものが全て小文字に
foreach (string s in query) {
Console.WriteLine(s);
}*/
string[] names = {
"Tokyo", "New Delhi", "Bangkok", "London", "Paris", "Berlin", "Canberra" };
var query = names.Where(s => s.Length <= 5).ToList();
foreach (var item in query)
Console.WriteLine(item);
Console.WriteLine("------");
names[0] = "Osaka";
foreach (var item in query)
Console.WriteLine(item);
}
}
} |
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.CortanaAnalytics.Models;
using Microsoft.CortanaAnalytics.SolutionAccelerators.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Microsoft.CortanaAnalytics.ResourceService.Controllers
{
public class DeployController : ApiController
{
// TODO: [chrisriz] This needs to be a default configuration driven value on v1
string resourceGroup = "solutionaccelerators";
// TODO: [chrisriz] This is test until we get the ARM templates from Anand Monday
string template = @"{
'$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#/',
'contentVersion': '1.0.0.0',
'resources': [{
'type': 'Microsoft.Compute/availabilitySets',
'name': 'availabilitySet3',
'apiVersion': '2015-05-01-preview',
'location': 'West US',
'properties': { }
}]
}";
Guid correlationId;
public class DeployParameters
{
public string subscriptionId { get; set; }
public string solutionName { get; set; }
public string token { get; set; }
}
/*
* ----- AUTH FLOW -----------------------------------------------------------------------
*
* Deploy URL comes to site (atlas) via a get
*
* Authentication happens
*
* After landing on the page with incoming parameters the page then gets the auth token
*
* After getting the auth token, that value and the rest of needed parameters are posted to this
* endpoint
*/
[HttpPost]
public Solution Post(DeployParameters parameters)
{
var prov = new Provision();
var json = new Json()
{
Content = template
};
var result = prov.DeployTemplate(parameters.subscriptionId, resourceGroup, json, parameters.token);
correlationId = result.CorrelationId;
DeploymentOperationsCreateResult opResult = result.OperationResult;
if (opResult != null && opResult.StatusCode.Equals(HttpStatusCode.Created))
{
return new Solution()
{
ID = result.CorrelationId.ToString()
};
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace WebApp1.Pages
{
public class InformacionModel : PageModel
{
private readonly ILogger<InformacionModel> _logger;
public InformacionModel(ILogger<InformacionModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
|
namespace Bank_accounts.Accounts
{
using System;
public class Account
{
private Customer customer;
private decimal balance;
private decimal interestRate;
public Account(Customer customer, decimal balance, decimal interestRate)
{
this.Customer = customer;
this.Balance = balance;
this.InterestRate = interestRate;
}
public Customer Customer { get; private set; }
public decimal Balance { get; protected set; }
public decimal InterestRate { get; private set; }
public virtual decimal CalculateInterestRate(int numberOfMonths)
{
return numberOfMonths * this.InterestRate;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace QuestomAssets.AssetsChanger
{
public class MeshObject : AssetsObject, IHaveName
{
public MeshObject(AssetsFile assetsFile) : base(assetsFile, AssetsConstants.ClassID.MeshAssetClassID)
{
}
public MeshObject(IObjectInfo<AssetsObject> objectInfo, AssetsReader reader) : base(objectInfo)
{
Parse(reader);
}
public override void Parse(AssetsReader reader)
{
base.ParseBase(reader);
int startPosition = reader.Position;
Name = reader.ReadString();
//int readLen = ObjectInfo.DataSize - (reader.Position - startPosition);
//MeshData = reader.ReadBytes(readLen);
SubMeshes = reader.ReadArrayOf(r => new Submesh(r));
BlendShapeData = new BlendShapeData(reader);
BindPose = reader.ReadArrayOf(r => reader.ReadSingle());
BoneNameHashes = reader.ReadArrayOf(r => r.ReadUInt32());
RootBoneNameHash = reader.ReadUInt32();
MeshCompression = reader.ReadByte();
IsReadable = reader.ReadBoolean();
KeepVerticies = reader.ReadBoolean();
KeepIndicies = reader.ReadBoolean();
reader.AlignTo(4);
IndexFormat = reader.ReadInt32();
IndexBuffer = reader.ReadArray();
reader.AlignTo(4);
VertexData = new VertexData(reader);
CompressedMesh = new CompressedMesh(reader);
LocalAABB = new AABB(reader);
MeshUsageFlags = reader.ReadInt32();
BakedConvexCollisionMesh = reader.ReadArray();
reader.AlignTo(4);
BakedTriangleCollisionMesh = reader.ReadArray();
reader.AlignTo(4);
MeshMetrics1 = reader.ReadSingle();
MeshMetrics2 = reader.ReadSingle();
StreamData = new StreamingInfo(reader);
}
protected override void WriteObject(AssetsWriter writer)
{
base.WriteBase(writer);
writer.Write(Name);
//writer.Write(MeshData);
writer.WriteArrayOf(SubMeshes, (o, w) => o.Write(w));
BlendShapeData.Write(writer);
writer.WriteArrayOf(BindPose, (o, w) => w.Write(o));
writer.WriteArrayOf(BoneNameHashes, (o, w) => w.Write(o));
writer.Write(RootBoneNameHash);
writer.Write(MeshCompression);
writer.Write(IsReadable);
writer.Write(KeepVerticies);
writer.Write(KeepIndicies);
writer.AlignTo(4);
writer.Write(IndexFormat);
writer.WriteArray(IndexBuffer);
writer.AlignTo(4);
VertexData.Write(writer);
CompressedMesh.Write(writer);
LocalAABB.Write(writer);
writer.Write(MeshUsageFlags);
writer.WriteArray(BakedConvexCollisionMesh);
writer.AlignTo(4);
writer.WriteArray(BakedTriangleCollisionMesh);
writer.AlignTo(4);
writer.Write(MeshMetrics1);
writer.Write(MeshMetrics2);
StreamData.Write(writer);
}
public string Name { get; set; }
public List<Submesh> SubMeshes { get; set; }
public BlendShapeData BlendShapeData { get; set; }
public List<Single> BindPose { get; set; }
public List<UInt32> BoneNameHashes { get; set; }
public UInt32 RootBoneNameHash { get; set; }
public byte MeshCompression { get; set; }
public bool IsReadable { get; set; }
public bool KeepVerticies { get; set; }
public bool KeepIndicies { get; set; }
public int IndexFormat { get; set; }
public byte[] IndexBuffer { get; set; }
public VertexData VertexData { get; set; }
public CompressedMesh CompressedMesh { get; set; }
public AABB LocalAABB { get; set; }
public int MeshUsageFlags { get; set; }
public byte[] BakedConvexCollisionMesh { get; set; }
public byte[] BakedTriangleCollisionMesh { get; set; }
public Single MeshMetrics1 { get; set; }
public Single MeshMetrics2 { get; set; }
public StreamingInfo StreamData { get; set; }
// public byte[] MeshData { get; set; }
[System.ComponentModel.Browsable(false)]
[Newtonsoft.Json.JsonIgnore]
public override byte[] Data { get => throw new InvalidOperationException("Data cannot be accessed from this class!"); set => throw new InvalidOperationException("Data cannot be accessed from this class!"); }
}
}
|
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Dapper;
using DataStore.Dal.Pager;
using DataStore.Entity;
using DataStore.Pager;
namespace DataStore.Dal
{
public partial interface IOperLogService
{
void Delete(List<long> idList);
void Delete(long id);
void Insert(List<OperLog> operLogList);
void Insert(OperLog operLog);
void Update(List<OperLog> operLogList);
void Update(OperLog operLog);
IEnumerable<OperLog> GetOperLogs();
IEnumerable<OperLog> GetOperLogs(string where, DynamicParameters parameters);
OperLog GetSingleOperLog(string where, DynamicParameters parameters);
OperLog GetOperLogByPk(long id);
PageDataView<OperLog> GetList(int page, int pageSize = 10);
}
} |
// Copyright 2021 Google Inc. 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 NtApiDotNet.Win32.SafeHandles;
using System;
namespace NtApiDotNet.Win32.Security.Policy
{
/// <summary>
/// Class to represent an LSA secret value.
/// </summary>
public sealed class LsaSecretValue
{
/// <summary>
/// The current value of the secret.
/// </summary>
public byte[] CurrentValue { get; }
/// <summary>
/// The set time for the current value.
/// </summary>
public DateTime CurrentValueSetTime { get; }
/// <summary>
/// The old value of the secret.
/// </summary>
public byte[] OldValue { get; }
/// <summary>
/// The set time for the old value.
/// </summary>
public DateTime OldValueSetTime { get; }
internal LsaSecretValue(SafeLsaMemoryBuffer current_value, LargeInteger current_value_set_time,
SafeLsaMemoryBuffer old_value, LargeInteger old_value_set_time)
{
if (!current_value.IsInvalid)
{
CurrentValue = current_value.GetUnicodeString().ToArray();
CurrentValueSetTime = current_value_set_time.ToDateTime();
}
else
{
CurrentValue = new byte[0];
CurrentValueSetTime = DateTime.MinValue;
}
if (!old_value.IsInvalid)
{
OldValue = old_value.GetUnicodeString().ToArray();
OldValueSetTime = old_value_set_time.ToDateTime();
}
else
{
OldValue = new byte[0];
OldValueSetTime = DateTime.MinValue;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StageManager : SingletonBehavior<StageManager>
{
public static StageAchivementData data;
public CameraManager CameraManager { get; private set; }
public ItemManager ItemManager { get; private set; }
public TilemapGeneration MapManager { get; private set; }
public PlayerStats Stat { get; private set; }
public GameObject Player { get; private set; }
public Shop Shop { get; private set; }
public GameObject BonusRoom { get; private set; }
public int monsterCount;
public static event System.Action<int> changeCurrentRoom;
private int playerRoom = 1; //현재 스테이지안의 방
public int PlayerRoom
{
get
{
return playerRoom;
}
private set
{
playerRoom = value;
changeCurrentRoom?.Invoke(playerRoom);
}
}
public static event System.Action clearEvent;
protected override void OnAwake()
{
GameManager.Instance.input.Touch.ButtonExtent = 0.5f;
GameManager.Instance.input.Joystick.SetFirst();
data = new StageAchivementData(new Timer());
clearEvent += () => GameManager.Data.SumDatas(data);
clearEvent += () => GameManager.Data.ClearCount++;
ItemManager = new ItemManager();
Player = GameObject.FindGameObjectWithTag("Player");
Stat = Player.GetComponent<Player>().stats;
foreach(GameObject obj in GameObject.FindGameObjectsWithTag("Wall"))
{
if (obj.name == nameof(MapManager))
MapManager = obj.GetComponent<TilemapGeneration>();
}
Shop = GameObject.FindGameObjectWithTag("Shop").GetComponent<Shop>();
Shop.gameObject.SetActive(false);
BonusRoom = GameObject.FindGameObjectWithTag("BonusRoom");
BonusRoom.SetActive(false);
CameraManager = Camera.main.gameObject.GetComponent<CameraManager>();
PlayerInStage = true;
}
private void Update()
{
data.timer.TimerUpdate();
if (PlayerInStage)
{
if (CameraManager.Screen2World(GameManager.ScreenSize).y
> MapManager.EndYPosition)
{
CameraManager.CameraLock = true;
}
if (CameraManager.Screen2World(GameManager.ScreenSize).y < 0)
{
CameraManager.CameraLock = true;
CameraManager.CamPositionChangeY(0);
}
if (CameraManager.TargetIsInRange() &&
CameraManager.gameObject.transform.position.y == 0)
{
CameraManager.CameraLock = false;
}
if (Player.transform.position.y
>= MapManager.EndYPosition)
{
if (PlayerRoom >= MapManager.levelInStage * MapManager.stageCount)
clearEvent?.Invoke();
else
PlayerTeleportToShop();
}
}
}
public static bool PlayerInStage { get; private set; } = true;
private Vector3 nextMovePosition;
private void PlayerTeleportToShop()
{
nextMovePosition = new Vector3(MapManager.XPositions[PlayerRoom++], -MapManager.MapYSize / 2, 0);
Shop.gameObject.SetActive(true);
PlayerInStage = false;
Player.transform.position = Shop.DoorPosition;
CameraManager.CameraLock = true;
CameraManager.CamPositionChange(Shop.ShopPosition);
}
public void PlayerTeleportToBonusRoom(Vector3 originalPos)
{
nextMovePosition = originalPos;
nextMovePosition.x = 0;
Player.transform.position = BonusRoom.transform.GetChild(2).position;
BonusRoom.gameObject.SetActive(true);
PlayerInStage = false;
CameraManager.CameraLock = true;
CameraManager.CamPositionChange(BonusRoom.transform.position);
}
public void PlayerTeleportToStage()
{
Shop.gameObject.SetActive(false);
BonusRoom.gameObject.SetActive(false);
Player.transform.position = nextMovePosition;
PlayerInStage = true;
nextMovePosition.z = CameraManager.transform.position.z;
CameraManager.CamPositionChange(nextMovePosition);
CameraManager.CameraLock = false;
}
private void OnDestroy()
{
clearEvent -= () => GameManager.Data.SumDatas(data);
clearEvent -= () => GameManager.Data.ClearCount++;
}
}
|
using System;
namespace Common.Dialog
{
public interface IDialogService
{
string GetOpenFileDialog(string title, string filter);
string GetSaveFileDialog(string title, string filter);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CommunityAssist2018MVC.Models;
namespace CommunityAssist2018MVC.Controllers
{
public class RegistrationController : Controller
{
CommunityAssist2017Entities db = new CommunityAssist2017Entities();
// GET: Registration
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "PersonLastName, PersonFirstName, PersonEmail, PersonPrimaryPhone, PersonAddressApt, PersonAddressStreet, PersonAddressCity, PersonAddressState, PersonAddressPostal, PersonPlainPassword")]NewPerson np)
{
int result = db.usp_Register(np.PersonLastName, np.PersonFirstName, np.PersonEmail, np.PersonPlainPassword, np.PersonAddressApt, np.PersonAddressStreet, np.PersonAddressCity, np.PersonAddressState, np.PersonAddressPostal, np.PersonPrimaryPhone);
var resultMessage = new Message();
if (result != -1)
{
resultMessage.MessageText = "Thanks for registering.";
} else {
resultMessage.MessageText = "Sorry, but something seems to have gone wrong with the registration.";
}
return View("Result",resultMessage);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using App1.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace App1
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page3 : ContentPage
{
public Page3()
{
InitializeComponent();
var boxViewRed = new ExBoxView
{
Color = Color.Red
};
var boxViewBlue = new ExBoxView
{
Color = Color.Blue
};
var sliderRed = new Slider
{
Maximum = 100,
WidthRequest = 200,
};
sliderRed.PropertyChanged += (s, a) => {
boxViewRed.Radius = (int)sliderRed.Value;
};
var sliderBlue = new Slider
{
Maximum = 100,
WidthRequest = 200,
};
sliderBlue.PropertyChanged += (s, a) => {
boxViewBlue.Radius = (int)sliderBlue.Value;
};
var layout = new AbsoluteLayout();
layout.Children.Add(boxViewRed, new Point(100, 100));
layout.Children.Add(boxViewBlue, new Point(50, 50));
layout.Children.Add(sliderRed, new Point(50, 300));
layout.Children.Add(sliderBlue, new Point(50, 350));
Content = new StackLayout
{
BackgroundColor = Color.White,
Children = { layout }
};
}
}
} |
namespace KRF.Core.Entities.AccessControl
{
public class Pages
{
public int PageID { get; set; }
/// <summary>
/// Holds the name of a page.
/// </summary>
public string PageName { get; set; }
public bool Active { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyPrivateFinance.data.entities
{
public class Payment
{
public int paymentId { get; set; }
public string name { get; set; }
public string description { get; set; }
public string date { get; set; }
public double amount { get; set; }
public bool isIncome { get; set; }
public int categoryId { get; set; }
public Payment(int paymentId, string name, string description, string date, double amount, bool isIncome, int categoryId)
{
this.paymentId = paymentId;
this.name = name;
this.description = description;
this.date = date;
this.amount = amount;
this.isIncome = isIncome;
this.categoryId = categoryId;
}
}
}
|
namespace Library_System.Areas.Administration.Controllers
{
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Models;
using Utilities;
using ViewModels;
[Authorize]
public class BooksController : Controller
{
//
// GET: /Admin/Books/
public ActionResult Index()
{
var db = new Library_SystemDbContext();
var found = db.Books.ToList();
return View(found);
}
public ActionResult BooksRead([DataSourceRequest]DataSourceRequest request)
{
var db = new Library_SystemDbContext();
IQueryable<Book> found = db.Books;
var viewModelBooks = found.ConvertToBookViewModel().ToList();
foreach (var item in viewModelBooks)
{
if (item.Description != null && item.Description.Length > 20)
{
item.Description = item.Description.Substring(0, 20);
}
}
DataSourceResult result = viewModelBooks.ToDataSourceResult(request);
return Json(result);
}
public ActionResult BooksCreate([DataSourceRequest]DataSourceRequest request, BookViewModel book)
{
if (ModelState.IsValid)
{
var db = new Library_SystemDbContext();
Book newBook = new Book()
{
Description = book.Description,
Author = book.Author,
ISBN = book.ISBN,
Title = book.Title,
Website = book.Website
};
var category = db.Categories.FirstOrDefault(x => x.Name == book.CategoryName);
category = CreateOrGetCategory(book, db, newBook, category);
newBook.Id = db.Books.Add(newBook).Id;
db.SaveChanges();
book.Id = newBook.Id;
}
return Json(new[] { book }.ToDataSourceResult(request, ModelState));
}
private static Category CreateOrGetCategory(BookViewModel book, Library_SystemDbContext db, Book newBook, Category category)
{
if (category == null)
{
category = db.Categories.Add(new Category()
{
Name = book.CategoryName
});
category.Books = new HashSet<Book>();
category.Books.Add(newBook);
}
else
{
newBook.Category = category;
}
return category;
}
public ActionResult BooksUpdate([DataSourceRequest]DataSourceRequest request, BookViewModel book)
{
if (ModelState.IsValid)
{
var db = new Library_SystemDbContext();
var category = db.Categories.FirstOrDefault(x => x.Name == book.CategoryName);
var oldBook = db.Books.Single(x => x.Id == book.Id);
if (oldBook.Category.Name != book.CategoryName)
{
oldBook.Category = category;
UpdateBookFields(book, oldBook);
category.Books.Add(oldBook);
db.SaveChanges();
}
else
{
UpdateBookFields(book, oldBook);
db.Entry(oldBook).State = EntityState.Modified;
db.SaveChanges();
}
}
return Json(new[] { book }.ToDataSourceResult(request, ModelState));
}
private static void UpdateBookFields(BookViewModel book, Book oldBook)
{
oldBook.Author = book.Author;
oldBook.Description = book.Description;
oldBook.ISBN = book.ISBN;
oldBook.Title = book.Title;
oldBook.Website = book.Website;
}
public ActionResult BooksDelete([DataSourceRequest]DataSourceRequest request, Book book)
{
if (ModelState.IsValid)
{
var db = new Library_SystemDbContext();
db.Books.Attach(book);
db.Books.Remove(book);
db.SaveChanges();
}
return Json(new[] { book }.ToDataSourceResult(request, ModelState));
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using ENTITY;
//<summary>
//Summary description for RouteInfo
//</summary>
namespace ENTITY
{
public class RouteInfo
{
private decimal _routeId;
private string _routeName;
private decimal _areaId;
private string _narration;
private DateTime _extraDate;
private string _extra1;
private string _extra2;
public decimal RouteId
{
get { return _routeId; }
set { _routeId = value; }
}
public string RouteName
{
get { return _routeName; }
set { _routeName = value; }
}
public decimal AreaId
{
get { return _areaId; }
set { _areaId = value; }
}
public string Narration
{
get { return _narration; }
set { _narration = value; }
}
public DateTime ExtraDate
{
get { return _extraDate; }
set { _extraDate = value; }
}
public string Extra1
{
get { return _extra1; }
set { _extra1 = value; }
}
public string Extra2
{
get { return _extra2; }
set { _extra2 = value; }
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
public class Skybox : MonoBehaviour {
public Texture2D[] textures;
public Renderer rend;
int index = 0;
Vector3 rotation;
Vector3 currentRotation;
void Start()
{
rend = GetComponent<Renderer>();
}
void Update()
{
if (textures.Length == 0)
return;
index++;
if (index >= textures.Length)
{
index = 0;
}
rend.material.mainTexture = textures[index];
currentRotation = transform.localEulerAngles;
rotation = currentRotation + new Vector3(0, 0.10f, 0);
transform.localEulerAngles = rotation;
}
}
|
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
namespace litecart_tests
{
public class MenuHelper : HelperBase
{
public MenuHelper(ApplicationManager app) : base(app)
{
}
public List<IWebElement> GetMenuItems()
{
return driver.FindElements(By.XPath("//ul[@id='box-apps-menu']/li")).ToList();
}
public List<IWebElement> GetSubmenuItems(int i)
{
List<IWebElement> menuItems = GetMenuItems();
return menuItems[i].FindElements(By.XPath("./ul/li")).ToList();
}
public bool IsMenuSelected(int i)
{
List<IWebElement> menuItems = GetMenuItems();
return menuItems[i].GetAttribute("class").Contains("selected");
}
public bool IsSubmenuSelected(int i, int n)
{
List<IWebElement> submenuItems = GetSubmenuItems(i);
return submenuItems[n].GetAttribute("class").Contains("selected");
}
public bool IsPageHeaderExist()
{
return IsElementPresent(By.XPath("//td[@id='content']/h1"));
}
public void ClickMenuCountry()
{
if (driver.Url == app.baseURL + "/litecart/admin/?app=countries&doc=countries")
return;
ClickMenuItem("doc=countries");
}
public void ClickMenuGeozone()
{
if (driver.Url == app.baseURL + "/litecart/admin/?app=geo_zones&doc=geo_zones")
return;
ClickMenuItem("doc=geo_zones");
}
public void ClickMenuCatalog()
{
if (driver.Url == app.baseURL + "/litecart/admin/?app=catalog&doc=catalog")
return;
ClickMenuItem("doc=catalog");
}
private void ClickMenuItem(string itemName)
{
ICollection<IWebElement> menuItems = driver.FindElements(By.XPath("//ul[@id='box-apps-menu']//a[contains(@href ,'" + itemName + "')]"));
if (menuItems.Count == 0)
throw new Exception("There is no '" + itemName + "' menu item");
IWebElement element = menuItems.First();
wait.Until(d=>
{
element.Click();
return IsElementPresent(By.XPath("//ul[@id='box-apps-menu']//a[contains(@href ,'" + itemName + "')]//parent::li[contains(@class ,'selected')]"));
});
}
public void ClickMenuByIndex(int i, string[] args)
{
List<IWebElement> menuItems = GetMenuItems();
IWebElement link = menuItems[i].FindElement(By.XPath("./a"));
args[0] = menuItems[i].Text;
wait.Until(d =>
{
link.Click();
return IsMenuSelected(i);
});
wait.Until(d => IsDocumentReadyStateComplete());
}
public void ClickSubmenuByIndex(int i, int n, string[] args)
{
List<IWebElement> submenuItems = GetSubmenuItems(i);
IWebElement link = submenuItems[n].FindElement(By.XPath("./a"));
args[0] = submenuItems[n].Text;
wait.Until(d =>
{
link.Click();
return IsSubmenuSelected(i, n);
});
wait.Until(d => IsDocumentReadyStateComplete());
}
}
}
|
namespace Prospects.Cross.Infrastructure.Enumerations
{
public enum PageTypes
{
Splash,
Login,
SignOut,
Home,
EditProspect,
ProspectDetail,
Log
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Creep : MonoBehaviour
{
public float creepSpeed = 0.05f;
public float creepIncrease = 0.05f;
public float creepCap = 20.0f;
public Transform particles;
public Transform player;
public SquishPlayer squishPlayer;
public Transform playerParticles;
bool playerDrives = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (creepSpeed < creepCap)
{
creepSpeed += creepIncrease;
}
//Vector3 special = particles.position;
//special.x = particles.position.x;
//special.x += creepSpeed;
//particles.position = special;
if (player.position.x < particles.position.x && player.gameObject.activeSelf)
{
//Object.Destroy(playerSoul.gameObject);
squishPlayer.playerDie = true;
//playerSoul.GetChild(0).DetachChildren;
playerParticles = player.GetChild(0).GetChild(0);
//Vector3 theScale = particles.localScale;
//theScale = new Vector3(1,1,1);
playerParticles.localScale = new Vector3(1, 1, 1);
playerParticles.gameObject.SetActive(true);
playerParticles.parent = null;
player.gameObject.SetActive(false);
}
if (playerParticles != null)
{
playerParticles.localScale = new Vector3(1, 1, 1);
}
if (Vector3.Distance(player.position, particles.position) > 21)
{
//Vector3 special = particles.position;
//special.x = particles.position.x;
//special.x += 40;
Vector3 special = new Vector3 (player.position.x, particles.position.y, particles.position.z);
special.x -= 20;
particles.position = special;
}
if (Vector3.Distance(player.position, particles.position) <= 30)
{
Vector3 special = particles.position;
special.x = particles.position.x;
special.x += creepSpeed;
particles.position = special;
}
//if (Vector3.Distance(player.position, particles.position) > 50)
//{
// Destroy(gameObject);
//}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using ExcelLibrary.CompoundDocumentFormat;
using ExcelLibrary.SpreadSheet;
using ExcelLibrary.BinaryDrawingFormat;
using ExcelLibrary.BinaryFileFormat;
using System.Diagnostics;
namespace POS_SYSTEM
{
public partial class ReportPurchaseOrder : Form
{
DataTable dataTableOrder;
public ReportPurchaseOrder(string databaseString)
{
InitializeComponent();
databaseConnectionStringTextBox.Text = databaseString;
orderListGridView();
searchSupplier();
searchDrug();
}
private void ReportPurchaseOrder_Load(object sender, EventArgs e)
{
}
//search drug from purchase history.
public void searchDrug()
{
productNameTextBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
productNameTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
try
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
con.Open();
MySqlCommand c = new MySqlCommand("select product_name AS 'name' FROM `order_price_list_history` ORDER BY product_name ASC", con);
MySqlDataReader r = c.ExecuteReader();
while (r.Read())
{
String name = r.GetString("name");
collection.Add(name);
}
con.Close();
}
catch (Exception)
{
}
productNameTextBox.AutoCompleteCustomSource = collection;
}
//search supplier from purchase history.
public void searchSupplier()
{
supplierTextBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
supplierTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
try
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
con.Open();
MySqlCommand c = new MySqlCommand("select supplier_name AS 'name' FROM `order_price_list_history` ORDER BY supplier_name ASC", con);
MySqlDataReader r = c.ExecuteReader();
while (r.Read())
{
String name = r.GetString("name");
collection.Add(name);
}
con.Close();
}
catch (Exception)
{
}
supplierTextBox.AutoCompleteCustomSource = collection;
}
// display order price list.
private void orderListGridView()
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
try
{
con.Open();
MySqlCommand com = new MySqlCommand("SELECT `order_price_list_history`.`supplier_name` AS 'SUPPLIER',`order_price_list_history`.`product_name` AS 'PRODUCT',`order_price_list_history`.`price` AS 'PRICE', `order_price_list_history`.`quantity` AS 'QUANTITY',ROUND((`order_price_list_history`.`price`*`order_price_list_history`.`quantity`),2) AS 'TOTAL',`order_price_list_history`.`date_added` AS 'DATE ORDERED',`order_price_list_history`.`added_by` AS 'ORDERED BY' FROM `order_price_list_history` ORDER BY `order_price_list_history`.`supplier_name` ASC", con);
MySqlDataAdapter a = new MySqlDataAdapter();
a.SelectCommand = com;
dataTableOrder = new DataTable();
// Add autoincrement column.
dataTableOrder.Columns.Add("#", typeof(int));
dataTableOrder.PrimaryKey = new DataColumn[] { dataTableOrder.Columns["#"] };
dataTableOrder.Columns["#"].AutoIncrement = true;
dataTableOrder.Columns["#"].AutoIncrementSeed = 1;
dataTableOrder.Columns["#"].ReadOnly = true;
// End adding AI column.
a.Fill(dataTableOrder);
BindingSource bs = new BindingSource();
bs.DataSource = dataTableOrder;
reportOrderDataGridView.DataSource = bs;
a.Update(dataTableOrder);
// Count number of rows to return records.
Int64 count = Convert.ToInt64(reportOrderDataGridView.Rows.Count) - 1;
rowCountLabel.Text = count.ToString() + " Records";
}
catch (Exception)
{
//MessageBox.Show(ex.Message);
// MessageBox.Show("Error has occured while displaying price list ............!", "DISPLAY DRUG PRICE LIST", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
getSupplierListAmount();
}
// display order price list filter by date.
private void orderListGridViewFilterByDate()
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
string date = dateBorrowedDateTimePicker.Value.ToString("yyyy-MM-dd");
try
{
con.Open();
MySqlCommand com = new MySqlCommand("SELECT `order_price_list_history`.`supplier_name` AS 'SUPPLIER',`order_price_list_history`.`product_name` AS 'PRODUCT',`order_price_list_history`.`price` AS 'PRICE', `order_price_list_history`.`quantity` AS 'QUANTITY',ROUND((`order_price_list_history`.`price`*`order_price_list_history`.`quantity`),2) AS 'TOTAL',`order_price_list_history`.`date_added` AS 'DATE ORDERED',`order_price_list_history`.`added_by` AS 'ORDERED BY' FROM `order_price_list_history` WHERE `order_price_list_history`.`date_added`='" + date + "' ORDER BY `order_price_list_history`.`supplier_name` ASC", con);
MySqlDataAdapter a = new MySqlDataAdapter();
a.SelectCommand = com;
dataTableOrder = new DataTable();
// Add autoincrement column.
dataTableOrder.Columns.Add("#", typeof(int));
dataTableOrder.PrimaryKey = new DataColumn[] { dataTableOrder.Columns["#"] };
dataTableOrder.Columns["#"].AutoIncrement = true;
dataTableOrder.Columns["#"].AutoIncrementSeed = 1;
dataTableOrder.Columns["#"].ReadOnly = true;
// End adding AI column.
a.Fill(dataTableOrder);
BindingSource bs = new BindingSource();
bs.DataSource = dataTableOrder;
reportOrderDataGridView.DataSource = bs;
a.Update(dataTableOrder);
// Count number of rows to return records.
Int64 count = Convert.ToInt64(reportOrderDataGridView.Rows.Count) - 1;
rowCountLabel.Text = count.ToString() + " Records";
}
catch (Exception)
{
//MessageBox.Show(ex.Message);
// MessageBox.Show("Error has occured while displaying price list ............!", "DISPLAY DRUG PRICE LIST", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
getSupplierListAmount();
}
// display order price list filter by date and supplier.
private void orderListGridViewFilterByDateAndSupplier()
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
string date = dateBorrowedDateTimePicker.Value.ToString("yyyy-MM-dd");
try
{
con.Open();
MySqlCommand com = new MySqlCommand("SELECT `order_price_list_history`.`supplier_name` AS 'SUPPLIER',`order_price_list_history`.`product_name` AS 'PRODUCT',`order_price_list_history`.`price` AS 'PRICE', `order_price_list_history`.`quantity` AS 'QUANTITY',ROUND((`order_price_list_history`.`price`*`order_price_list_history`.`quantity`),2) AS 'TOTAL',`order_price_list_history`.`date_added` AS 'DATE ORDERED',`order_price_list_history`.`added_by` AS 'ORDERED BY' FROM `order_price_list_history` WHERE (`order_price_list_history`.`date_added`='" + date + "' AND `order_price_list_history`.`supplier_name`='" + this.supplierTextBox.Text + "') ORDER BY `order_price_list_history`.`supplier_name` ASC", con);
MySqlDataAdapter a = new MySqlDataAdapter();
a.SelectCommand = com;
dataTableOrder = new DataTable();
// Add autoincrement column.
dataTableOrder.Columns.Add("#", typeof(int));
dataTableOrder.PrimaryKey = new DataColumn[] { dataTableOrder.Columns["#"] };
dataTableOrder.Columns["#"].AutoIncrement = true;
dataTableOrder.Columns["#"].AutoIncrementSeed = 1;
dataTableOrder.Columns["#"].ReadOnly = true;
// End adding AI column.
a.Fill(dataTableOrder);
BindingSource bs = new BindingSource();
bs.DataSource = dataTableOrder;
reportOrderDataGridView.DataSource = bs;
a.Update(dataTableOrder);
// Count number of rows to return records.
Int64 count = Convert.ToInt64(reportOrderDataGridView.Rows.Count) - 1;
rowCountLabel.Text = count.ToString() + " Records";
}
catch (Exception)
{
//MessageBox.Show(ex.Message);
// MessageBox.Show("Error has occured while displaying price list ............!", "DISPLAY DRUG PRICE LIST", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
getSupplierListAmount();
}
// display order price list filter by date between.
private void orderListGridViewFilterByDateBetween()
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
string startDate = startDateTimePicker.Value.ToString("yyyy-MM-dd");
string endDate = endDateTimePicker.Value.ToString("yyyy-MM-dd");
try
{
con.Open();
MySqlCommand com = new MySqlCommand("SELECT `order_price_list_history`.`supplier_name` AS 'SUPPLIER',`order_price_list_history`.`product_name` AS 'PRODUCT',`order_price_list_history`.`price` AS 'PRICE', `order_price_list_history`.`quantity` AS 'QUANTITY',ROUND((`order_price_list_history`.`price`*`order_price_list_history`.`quantity`),2) AS 'TOTAL',`order_price_list_history`.`date_added` AS 'DATE ORDERED',`order_price_list_history`.`added_by` AS 'ORDERED BY' FROM `order_price_list_history` WHERE `order_price_list_history`.`date_added` BETWEEN '" + startDate + "' AND '" + endDate + "' ORDER BY `order_price_list_history`.`supplier_name` ASC", con);
MySqlDataAdapter a = new MySqlDataAdapter();
a.SelectCommand = com;
dataTableOrder = new DataTable();
// Add autoincrement column.
dataTableOrder.Columns.Add("#", typeof(int));
dataTableOrder.PrimaryKey = new DataColumn[] { dataTableOrder.Columns["#"] };
dataTableOrder.Columns["#"].AutoIncrement = true;
dataTableOrder.Columns["#"].AutoIncrementSeed = 1;
dataTableOrder.Columns["#"].ReadOnly = true;
// End adding AI column.
a.Fill(dataTableOrder);
BindingSource bs = new BindingSource();
bs.DataSource = dataTableOrder;
reportOrderDataGridView.DataSource = bs;
a.Update(dataTableOrder);
// Count number of rows to return records.
Int64 count = Convert.ToInt64(reportOrderDataGridView.Rows.Count) - 1;
rowCountLabel.Text = count.ToString() + " Records";
}
catch (Exception)
{
//MessageBox.Show(ex.Message);
// MessageBox.Show("Error has occured while displaying price list ............!", "DISPLAY DRUG PRICE LIST", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
getSupplierListAmount();
}
// display order price list filter by date between and supplier.
private void orderListGridViewFilterByDateBetweenAndSupplier()
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
string startDate = startDateTimePicker.Value.ToString("yyyy-MM-dd");
string endDate = endDateTimePicker.Value.ToString("yyyy-MM-dd");
try
{
con.Open();
MySqlCommand com = new MySqlCommand("SELECT `order_price_list_history`.`supplier_name` AS 'SUPPLIER',`order_price_list_history`.`product_name` AS 'PRODUCT',`order_price_list_history`.`price` AS 'PRICE', `order_price_list_history`.`quantity` AS 'QUANTITY',ROUND((`order_price_list_history`.`price`*`order_price_list_history`.`quantity`),2) AS 'TOTAL',`order_price_list_history`.`date_added` AS 'DATE ORDERED',`order_price_list_history`.`added_by` AS 'ORDERED BY' FROM `order_price_list_history` WHERE ((`order_price_list_history`.`date_added` BETWEEN '" + startDate + "' AND '" + endDate + "') AND (`order_price_list_history`.`supplier_name`='" + this.supplierTextBox.Text + "')) ORDER BY `order_price_list_history`.`supplier_name` ASC", con);
MySqlDataAdapter a = new MySqlDataAdapter();
a.SelectCommand = com;
dataTableOrder = new DataTable();
// Add autoincrement column.
dataTableOrder.Columns.Add("#", typeof(int));
dataTableOrder.PrimaryKey = new DataColumn[] { dataTableOrder.Columns["#"] };
dataTableOrder.Columns["#"].AutoIncrement = true;
dataTableOrder.Columns["#"].AutoIncrementSeed = 1;
dataTableOrder.Columns["#"].ReadOnly = true;
// End adding AI column.
a.Fill(dataTableOrder);
BindingSource bs = new BindingSource();
bs.DataSource = dataTableOrder;
reportOrderDataGridView.DataSource = bs;
a.Update(dataTableOrder);
// Count number of rows to return records.
Int64 count = Convert.ToInt64(reportOrderDataGridView.Rows.Count) - 1;
rowCountLabel.Text = count.ToString() + " Records";
}
catch (Exception)
{
//MessageBox.Show(ex.Message);
// MessageBox.Show("Error has occured while displaying price list ............!", "DISPLAY DRUG PRICE LIST", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
getSupplierListAmount();
}
// display order price list filter by date.
private void orderListGridViewFilterByDateMinList()
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
string date = minDateTimePicker.Value.ToString("yyyy-MM-dd");
try
{
con.Open();
MySqlCommand com = new MySqlCommand("SELECT `min_order_price_list_history`.`supplier_name` AS 'SUPPLIER',`min_order_price_list_history`.`product_name` AS 'PRODUCT',`min_order_price_list_history`.`price` AS 'PRICE', `min_order_price_list_history`.`quantity` AS 'QUANTITY',ROUND((`min_order_price_list_history`.`price`*`min_order_price_list_history`.`quantity`),2) AS 'TOTAL',`min_order_price_list_history`.`date_added` AS 'DATE ORDERED',`min_order_price_list_history`.`added_by` AS 'ORDERED BY' FROM `min_order_price_list_history` WHERE `min_order_price_list_history`.`date_added`='" + date + "' ORDER BY `min_order_price_list_history`.`supplier_name` ASC", con);
MySqlDataAdapter a = new MySqlDataAdapter();
a.SelectCommand = com;
dataTableOrder = new DataTable();
// Add autoincrement column.
dataTableOrder.Columns.Add("#", typeof(int));
dataTableOrder.PrimaryKey = new DataColumn[] { dataTableOrder.Columns["#"] };
dataTableOrder.Columns["#"].AutoIncrement = true;
dataTableOrder.Columns["#"].AutoIncrementSeed = 1;
dataTableOrder.Columns["#"].ReadOnly = true;
// End adding AI column.
a.Fill(dataTableOrder);
BindingSource bs = new BindingSource();
bs.DataSource = dataTableOrder;
reportOrderDataGridView.DataSource = bs;
a.Update(dataTableOrder);
// Count number of rows to return records.
Int64 count = Convert.ToInt64(reportOrderDataGridView.Rows.Count) - 1;
rowCountLabel.Text = count.ToString() + " Records";
}
catch (Exception)
{
//MessageBox.Show(ex.Message);
// MessageBox.Show("Error has occured while displaying price list ............!", "DISPLAY DRUG PRICE LIST", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
getSupplierListAmount();
}
// display order price list filter by supplier.
private void orderListGridViewFilterBySupplier()
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
try
{
con.Open();
MySqlCommand com = new MySqlCommand("SELECT `order_price_list_history`.`supplier_name` AS 'SUPPLIER',`order_price_list_history`.`product_name` AS 'PRODUCT',`order_price_list_history`.`price` AS 'PRICE', `order_price_list_history`.`quantity` AS 'QUANTITY',ROUND((`order_price_list_history`.`price`*`order_price_list_history`.`quantity`),2) AS 'TOTAL',`order_price_list_history`.`date_added` AS 'DATE ORDERED',`order_price_list_history`.`added_by` AS 'ORDERED BY' FROM `order_price_list_history` WHERE `order_price_list_history`.`supplier_name`='" + this.supplierTextBox.Text + "' ORDER BY `order_price_list_history`.`supplier_name` ASC", con);
MySqlDataAdapter a = new MySqlDataAdapter();
a.SelectCommand = com;
dataTableOrder = new DataTable();
// Add autoincrement column.
dataTableOrder.Columns.Add("#", typeof(int));
dataTableOrder.PrimaryKey = new DataColumn[] { dataTableOrder.Columns["#"] };
dataTableOrder.Columns["#"].AutoIncrement = true;
dataTableOrder.Columns["#"].AutoIncrementSeed = 1;
dataTableOrder.Columns["#"].ReadOnly = true;
// End adding AI column.
a.Fill(dataTableOrder);
BindingSource bs = new BindingSource();
bs.DataSource = dataTableOrder;
reportOrderDataGridView.DataSource = bs;
a.Update(dataTableOrder);
// Count number of rows to return records.
Int64 count = Convert.ToInt64(reportOrderDataGridView.Rows.Count) - 1;
rowCountLabel.Text = count.ToString() + " Records";
}
catch (Exception)
{
//MessageBox.Show(ex.Message);
// MessageBox.Show("Error has occured while displaying price list ............!", "DISPLAY DRUG PRICE LIST", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
getSupplierListAmount();
}
// display order price list filter by drug name.
private void orderListGridViewFilterByDrugName()
{
string db = databaseConnectionStringTextBox.Text;
MySqlConnection con = new MySqlConnection(db);
try
{
con.Open();
MySqlCommand com = new MySqlCommand("SELECT `order_price_list_history`.`supplier_name` AS 'SUPPLIER',`order_price_list_history`.`product_name` AS 'PRODUCT',`order_price_list_history`.`price` AS 'PRICE', `order_price_list_history`.`quantity` AS 'QUANTITY',ROUND((`order_price_list_history`.`price`*`order_price_list_history`.`quantity`),2) AS 'TOTAL',`order_price_list_history`.`date_added` AS 'DATE ORDERED',`order_price_list_history`.`added_by` AS 'ORDERED BY' FROM `order_price_list_history` WHERE `order_price_list_history`.`product_name`='" + this.productNameTextBox.Text + "' ORDER BY `order_price_list_history`.`supplier_name` ASC", con);
MySqlDataAdapter a = new MySqlDataAdapter();
a.SelectCommand = com;
dataTableOrder = new DataTable();
// Add autoincrement column.
dataTableOrder.Columns.Add("#", typeof(int));
dataTableOrder.PrimaryKey = new DataColumn[] { dataTableOrder.Columns["#"] };
dataTableOrder.Columns["#"].AutoIncrement = true;
dataTableOrder.Columns["#"].AutoIncrementSeed = 1;
dataTableOrder.Columns["#"].ReadOnly = true;
// End adding AI column.
a.Fill(dataTableOrder);
BindingSource bs = new BindingSource();
bs.DataSource = dataTableOrder;
reportOrderDataGridView.DataSource = bs;
a.Update(dataTableOrder);
// Count number of rows to return records.
Int64 count = Convert.ToInt64(reportOrderDataGridView.Rows.Count) - 1;
rowCountLabel.Text = count.ToString() + " Records";
}
catch (Exception)
{
//MessageBox.Show(ex.Message);
// MessageBox.Show("Error has occured while displaying price list ............!", "DISPLAY DRUG PRICE LIST", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
getSupplierListAmount();
}
public void getSupplierListAmount()
{
double sum = 0.00;
for (int i = 0; i < reportOrderDataGridView.Rows.Count; ++i)
{
sum += Convert.ToDouble(reportOrderDataGridView.Rows[i].Cells[5].Value);
}
//string amt = "amount "+sum.ToString();
allSupplierToTalAmountLabel.Text = " " + sum.ToString() + " Kshs";
}
//print pdf for order price list.
public void orderPriceList()
{
try
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 0, 0, 0, 0);
PdfWriter PW = PdfWriter.GetInstance(doc, new FileStream("C:\\POS\\Reports\\Order List pdf", FileMode.Create));
doc.Open();//open document to write
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("C:\\pos\\Resources\\faith2.png");
img.ScalePercent(79f);
// img.SetAbsolutePosition(doc.PageSize.Width - 250f - 250f, doc.PageSize.Height - 30f - 20.6f);
doc.Add(img); //add image to document
Paragraph p = new Paragraph(" Order List");
doc.Add(p);
DateTime time = DateTime.Now;
Paragraph p2 = new Paragraph(" Supplier " + this.supplierTextBox.Text + " Amount " + this.allSupplierToTalAmountLabel.Text + " Produced On " + time.ToString() + " \n\n");
doc.Add(p2);
//load data from datagrid
PdfPTable table = new PdfPTable(reportOrderDataGridView.Columns.Count);
//add headers from the datagridview to the table
for (int j = 0; j < reportOrderDataGridView.Columns.Count; j++)
{
table.AddCell(new Phrase(reportOrderDataGridView.Columns[j].HeaderText));
}
//flag the first row as header
table.HeaderRows = 1;
//add the actual rows to the table from datagridview
for (int i = 0; i < reportOrderDataGridView.Rows.Count; i++)
{
for (int k = 0; k < reportOrderDataGridView.Columns.Count; k++)
{
if (reportOrderDataGridView[k, i].Value != null)
{
table.AddCell(new Phrase(reportOrderDataGridView[k, i].Value.ToString()));
}
}
}
doc.Add(table);
//end querying from datagrid
doc.Close();//close document after writting in
MessageBox.Show("Order List Report generated Successfully");
System.Diagnostics.Process.Start("C:\\POS\\Reports\\Order List pdf");
}
catch (Exception)
{
MessageBox.Show("Unable to open the report ","DOCUMENT ERROR!",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
finally
{
}
}
private void button10_Click_1(object sender, EventArgs e)
{
orderListGridView();
}
private void button1_Click_1(object sender, EventArgs e)
{
orderListGridViewFilterByDateBetweenAndSupplier();
}
private void button2_Click_1(object sender, EventArgs e)
{
orderListGridViewFilterByDateAndSupplier();
}
private void button5_Click_1(object sender, EventArgs e)
{
orderListGridViewFilterByDrugName();
}
private void productNameTextBox_TextChanged(object sender, EventArgs e)
{
orderListGridViewFilterByDrugName();
}
private void supplierTextBox_TextChanged_1(object sender, EventArgs e)
{
orderListGridViewFilterBySupplier();
}
private void button6_Click_1(object sender, EventArgs e)
{
orderListGridViewFilterBySupplier();
}
private void searchByDate_Click_1(object sender, EventArgs e)
{
orderListGridViewFilterByDateBetween();
}
private void endDateTimePicker_ValueChanged_1(object sender, EventArgs e)
{
orderListGridViewFilterByDateBetween();
}
private void startDateTimePicker_ValueChanged(object sender, EventArgs e)
{
orderListGridViewFilterByDateBetween();
}
private void minDateTimePicker_ValueChanged_1(object sender, EventArgs e)
{
orderListGridViewFilterByDateMinList();
}
private void button7_Click_1(object sender, EventArgs e)
{
orderListGridViewFilterByDateMinList();
}
private void dateBorrowedDateTimePicker_ValueChanged_1(object sender, EventArgs e)
{
orderListGridViewFilterByDate();
}
private void searchDate_Click_1(object sender, EventArgs e)
{
orderListGridViewFilterByDate();
}
private void button3_Click(object sender, EventArgs e)
{
orderPriceList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Windows.Forms.VisualStyles;
using System.IO;
using System.Net;
using System.Net.Mail;
namespace Cicek_Sepeti
{
public partial class PasswordReset : Form
{
SqlConnection baglanti = new SqlConnection("Data Source=DESKTOP-I3RRSTI;Initial Catalog=CicekSepeti;Integrated Security=True");
public PasswordReset()
{
InitializeComponent();
}
int sayi1, sayi2;
public bool MailGonder(string konu, string icerik)
{
MailMessage ePosta = new MailMessage();
ePosta.From = new MailAddress("ahmethasan4747@gmail.com");
ePosta.To.Add(txtMail.Text); //göndereceğimiz mail adresi
ePosta.Subject = konu; //mail konusu
ePosta.Body = icerik; //mail içeriği
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.Credentials = new System.Net.NetworkCredential("ahmethasan4747@gmail.com", "Gosfas0068.");
client.EnableSsl = true;
client.UseDefaultCredentials = true;
client.Send(ePosta);
object userState = true;
bool kontrol = true;
try
{
client.SendAsync(ePosta, (object)ePosta);
}
catch (SmtpException ex)
{
kontrol = false;
MessageBox.Show(ex.Message);
}
return kontrol;
}
private void button1_Click(object sender, EventArgs e)
{
if (txtCevap.Text == Convert.ToString(sayi1 + sayi2))
{
baglanti.Open();
SqlCommand komut = new SqlCommand("select * from Tbl_Kullanicilar where Email='" + txtMail.Text + "'");
komut.Connection = baglanti;
SqlDataReader oku = komut.ExecuteReader();
if (oku.Read())
{
Random rnd = new Random();
int sayi = rnd.Next(100000,999999);
MailGonder("Şifre Sıfırlama", "Şifre Sıfırlama Kodunuz : " + sayi );
MessageBox.Show("Mail Adresinize Bir Kod Gönderilmiştir Lütfen O Kodu Giriniz.");
}
baglanti.Close();
}
else
{
MessageBox.Show("İşlem Sonucu Yanlış Lütfen Tekrar Giriniz !", "Çiçek Sepeti", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void PasswordReset_Load(object sender, EventArgs e)
{
Random rnd = new Random();
sayi1 = rnd.Next(50);
sayi2 = rnd.Next(50);
label1.Text = Convert.ToString(sayi1);
label3.Text = Convert.ToString(sayi2);
}
}
}
|
using ReturnOfThePioneers.Common.Models;
using ReturnOfThePioneers.Common.Utils;
using System.ComponentModel.DataAnnotations;
namespace ReturnOfThePioneers.Infrastructure {
public class RawData {
[Key]
public string Id { get; set; }
public string Index { get; set; }
public string Fragment { get; set; }
[MaxLength(65535)]
public string Value { get; set; }
public T Parse<T>() => JsonUtils.Decode<T>(Value);
public Json ToJson() => Parse<Json>();
}
}
|
using Paint.Model.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Paint.Model.Models
{
public class Defect
{
public Defect()
{
Zones = new List<Int32>();
}
public int DefectId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageName { get; set; }
public List<Int32> Zones { get; set; }
public DateTime DateEntry { get; set; }
public DateTime DateUpdated { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.