text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Completed
{
public class HealthPickup : MonoBehaviour, IAgentInteractable
{
public int healthRestoreValue = 10;
/// <summary>
/// Checks if the given <c>Agent</c> is able to interact with this in current conditions.
/// Currently, only <c>Player</c> is able to interact.
/// </summary>
/// <param name="agent"> The <c>Agent</c> to check. </param>
/// <returns> If the <c>Agent</c> is able to interact with this. </returns>
public bool CanInteract(Agent agent)
{
if (!(agent is Player)) return false;
Player player = (Player)agent;
return (player.currentHp < player.maxHp);
}
/// <summary>
/// Changes the given <c>Player</c> health by <c>healthRestoreValue</c>.
/// </summary>
/// <param name="agent">The <c>Agent</c> to give health to.</param>
public void Interact(Agent agent)
{
if (agent is Player)
{
Player player = (Player)agent;
player.ChangeHpAmount(healthRestoreValue);
Destroy(this.gameObject);
}
}
}
}
|
using System;
using System.Linq;
using AutoMapper;
using CacheSqlXmlService;
using Demo.Service.DtoValidators;
using ExceptionMiddleService.DoTime;
using ExceptionService;
using FluentValidation.AspNetCore;
using Mapper.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using OauthService.Models.AuthContext;
using Quartz;
using Quartz.Impl;
using SAAS.Api.Validate;
using SAAS.FrameWork.Common;
using SAAS.FrameWork.IOC;
using SAAS.InfrastructureCore;
using SwaggerService;
using SwaggerService.Builder;
using SysBase.Domain;
using TaskService.Extensions;
namespace SAAS.Api
{
public class Startup
{
/// <summary>
/// 启动项
/// </summary>
/// <param name="configuration"></param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//获取引擎上下文实例
this.Engine = EngineContext.Current;
}
/// <summary>
/// 全局配置项
/// </summary>
public IConfiguration Configuration { get; }
/// <summary>
/// 定义服务引擎
/// </summary>
public IEngine Engine { get; private set; }
/// <summary>
/// 项目接口文档配置
/// </summary>
private CustsomSwaggerOptions CURRENT_SWAGGER_OPTIONS = InitService.GetSwaggerOpntion();
/// <summary>
/// 注册服务
/// </summary>
/// <param name="services"></param>
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddCors(o =>
o.AddPolicy("*",
builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
));
#region (01)服务注册-初始化基础服务,配置缓存和自动生成ID,配置JWT认证,加入缓存对象
services.AddMemoryCache();
services.AddHttpClient();
services.AddHttpContextAccessor();
services.AddSingleton<IPathProvider, PathProvider>();
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
services.AddAutoMapper(typeof(MapperProfiles));
InitService.Init(services, Configuration);
#endregion
#region (02)服务注册-添加总控异常处理拦截器动态注入验证类和依赖注入服务层和仓储层
services.AddMvc(options =>
{
options.Filters.Add(new ValidateModelAttribute());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(options =>
{
options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
options.SerializerSettings.Converters.Add(new IdToStringConverter());
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //options.SerializerSettings.ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() };
options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;//循环依赖的问题或者标记[JsonIgnore]
});
services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<DemoModleValidator>());//加入验证类 ;
#endregion
#region (03)服务注册-Swagger版本控制
services.AddMvcCore().AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV");
services.AddApiVersioning(option =>
{
option.AssumeDefaultVersionWhenUnspecified = true;
option.ReportApiVersions = false;
});
services.AddCustomSwagger(CURRENT_SWAGGER_OPTIONS);
#endregion
#region (04)AUTOFAC动态注入服务
var serviceProvider= this.Engine.ConfigureServices(services); //动态注入业务服务
return serviceProvider;
#endregion
}
/// <summary>
/// 处理服务中间件
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="provider"></param>
/// <param name="cache"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider, Microsoft.Extensions.Caching.Memory.IMemoryCache cache)
{
app.UseCalculateExecutionTime();//只需在此添加
#region (01)开发版本启用错误页面
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();//开发环境启用错误页面
}
#endregion
#region (02)中间件-认证
app.UseAuthentication();// 添加认证 //app.UseIdentityServer();// 添加认证服务器
#endregion
#region (03)异常处理及用户认证对象静态缓存
app.ConfigureCustomExceptionMiddleware();
var serviceProvider = app.ApplicationServices;
var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
AuthContextService.Configure(httpContextAccessor);
#endregion
#region (04)中间件-配置本资源服务器及跨域访问
app.UseCors("*");
#endregion
#region (05)中间件-自定义cache服务以及依赖注入的容器类
CacheFactory.Init(cache);//注册自定义cache服务给sqlxml用
#endregion
#region (06)中间件-Swagger自动检测存在的版本
CURRENT_SWAGGER_OPTIONS.ApiVersions = provider.ApiVersionDescriptions.Select(s => s.GroupName).ToArray();
app.UseCustomSwagger(CURRENT_SWAGGER_OPTIONS);
app.UseQuartz(env).UseStaticHttpContext();//执行本地job
#endregion
#region (07)启用WWW静态站点及MVC使用
app.UseStaticFiles();//允许访问静态资源
app.UseMvc();
#endregion
}
}
}
|
using UnityEngine;
public class PooledAudioSource : MonoBehaviour
{
public AudioManager AudioManager;
[SerializeField]
private AudioAsset _audio;
public AudioAsset Audio
{
get
{
return _audio;
}
set
{
_audio = value;
if (_audio != null)
{
mutableAudio = Instantiate(_audio);
}
}
}
public bool PlayOnAwake;
private Transform trans;
private AudioAsset mutableAudio;
private void Awake()
{
trans = GetComponent<Transform>();
Audio = _audio;
if (PlayOnAwake && Audio != null)
{
Play();
}
}
public void Play()
{
mutableAudio.Position = trans.position;
AudioManager.Play(mutableAudio);
}
public void Play(AudioAsset audio)
{
AudioAsset tmpAudio = Instantiate(audio);
AudioManager.Play(tmpAudio);
}
}
|
using System.Windows.Forms;
using GeoAPI.Extensions.Feature;
using GeoAPI.Geometries;
using log4net;
using SharpMap.Layers;
using ToolTip=System.Windows.Forms.ToolTip;
namespace SharpMap.UI.Tools
{
public class ToolTipTool: MapTool
{
private static readonly ILog log = LogManager.GetLogger(typeof (ToolTipTool));
ToolTip toolTip;
private string toolTipText;
private Layer layer;
private IFeature feature;
public ToolTipTool()
{
Name = "ToolTipTool";
toolTip = new ToolTip();
toolTip.ReshowDelay = 500;
toolTip.InitialDelay = 500;
toolTip.AutoPopDelay = 2500;
}
public override bool IsActive
{
get { return true; } // always active
set { }
}
public override void OnMouseMove(ICoordinate worldPosition, MouseEventArgs e)
{
/*
feature = null;
feature = FindNearestFeature(worldPosition, 5, out layer);
if (feature == null || layer == null)
{
toolTip.Active = false;
return;
}
string message = "Feature: " + feature + "\nLayer: " + layer.Name;
if (toolTipText != message)
{
toolTip.SetToolTip((Control) MapControl, toolTipText);
toolTip.Active = false;
toolTip.Active = true;
}
*/
}
}
}
|
using System;
using System.Globalization;
namespace Temp
{
class Program
{
static void Main(string[] args)
{
int[,] mat = new int[2, 3];
Console.WriteLine(mat.Length);
// Quantidade de linhas
Console.WriteLine(mat.Rank);
//Primeira dimensão - linhas
Console.WriteLine(mat.GetLength(0));
//Segunda dimensão - colunas
Console.WriteLine(mat.GetLength(1));
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CustomControlz.Validations;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.DXErrorProvider;
using Utilities;
namespace CustomControlz.XtraEditors.TextEdits
{
public partial class ccTextEdit : TextEdit
{
private bool _isEditable = true;
private EValueType _valueType = EValueType.Text;
private ClsCommonFn _oCommFn = new ClsCommonFn();
private EtextEditType _textEditType = EtextEditType.Normal;
public enum EvalidationType
{
IsNullOrEmpty = 0,
MatchPasswords = 1
}
public enum EValueType
{
Text = 0,
TextDecimal = 1,
Int = 2,
Decimal = 3
}
public enum EtextEditType
{
Normal = 0,
CodeSeries = 1,
Numeric = 2,
Disabled = 4
}
public ccTextEdit()
{
InitializeComponent();
if (ProvideValidation && ValidationProvider != null)
{
ValidationProvider.SetValidationRule(this, new IsNullOrEmpty()
{
ErrorText = string.Format("Please Enter {0}", Text),
ErrorType = ErrorType.Warning
});
}
}
void ccTextEdit_HandleCreated(object sender, EventArgs e)
{
if (ProvideValidation && ValidationProvider != null)
{
ValidationProvider.SetValidationRule(this, new IsNullOrEmpty()
{
ErrorText = string.Format("Please Enter {0}", Text),
ErrorType = ErrorType.Warning
});
}
}
private void ccTextEdit_KeyPress(object sender, KeyPressEventArgs e)
{
if (_valueType != EValueType.Text)
_oCommFn.DecimalTb(this, e);
}
public override sealed string Text
{
get { return base.Text; }
set { base.Text = value; }
}
public bool ProvideValidation { get; set; }
public ccDxValidationProvider ValidationProvider { get; set; }
public bool IsEditable
{
get { return _isEditable; }
set { _isEditable = value; }
}
public EValueType ValueType
{
get { return _valueType; }
set
{
_valueType = value;
if (value == EValueType.Int || value == EValueType.TextDecimal)
Tag = "int";
else if (value == EValueType.Decimal)
Tag = "decT";
}
}
public decimal? ValueDec
{
get
{
decimal x = 0;
Decimal.TryParse(Text, out x);
return x;
}
set
{
if (_valueType == EValueType.Decimal)
Text = value != null ? value.ToString() : "0";
}
}
public EtextEditType TextEditType
{
get { return _textEditType; }
set
{
_textEditType = value;
if (value == EtextEditType.CodeSeries || value == EtextEditType.Numeric)
{
this.Properties.AppearanceDisabled.BackColor = Color.Aqua;
this.Properties.AppearanceDisabled.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold);
this.Properties.AppearanceDisabled.ForeColor = Color.FromArgb(200, 25, 25);
this.Properties.AppearanceDisabled.Options.UseBackColor = true;
this.Properties.AppearanceDisabled.Options.UseFont = true;
this.Properties.AppearanceDisabled.Options.UseForeColor = true;
this.Properties.AppearanceDisabled.TextOptions.HAlignment = HorzAlignment.Center;
Properties.Enabled = false;
}
else
{
Properties.ReadOnly = false;
}
}
}
}
}
|
using Profiling2.Domain.Contracts.Tasks;
using Profiling2.Domain.Prf;
using Profiling2.Domain.Prf.Persons;
using Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels;
using Profiling2.Web.Mvc.Controllers;
using SharpArch.NHibernate.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers
{
[PermissionAuthorize(AdminPermission.CanChangePersons)]
public class PersonRelationshipTypesController : BaseController
{
protected readonly IPersonTasks personTasks;
public PersonRelationshipTypesController(IPersonTasks personTasks)
{
this.personTasks = personTasks;
}
public ActionResult Index()
{
return View(this.personTasks.GetAllPersonRelationshipTypes()
.Select(x => new PersonRelationshipTypeViewModel(x))
.ToList());
}
public ActionResult Details(int id)
{
PersonRelationshipType type = this.personTasks.GetPersonRelationshipType(id);
if (type != null)
return View(type);
return new HttpNotFoundResult();
}
public ActionResult Create()
{
return View(new PersonRelationshipTypeViewModel());
}
[HttpPost]
[Transaction]
public ActionResult Create(PersonRelationshipTypeViewModel vm)
{
if (ModelState.IsValid)
{
PersonRelationshipType type = new PersonRelationshipType();
type.PersonRelationshipTypeName = vm.PersonRelationshipTypeName;
type.IsCommutative = vm.IsCommutative;
type.Archive = vm.Archive;
type.Notes = vm.Notes;
type.Code = vm.PersonRelationshipTypeName.ToUpper().Replace(' ', '_');
type = this.personTasks.SavePersonRelationshipType(type);
return RedirectToAction("Details", new { id = type.Id });
}
return Create();
}
public ActionResult Edit(int id)
{
PersonRelationshipType type = this.personTasks.GetPersonRelationshipType(id);
if (type != null)
return View(new PersonRelationshipTypeViewModel(type));
return new HttpNotFoundResult();
}
[HttpPost]
[Transaction]
public ActionResult Edit(PersonRelationshipTypeViewModel vm)
{
PersonRelationshipType type = this.personTasks.GetPersonRelationshipType(vm.Id);
IList<PersonRelationshipType> types = this.personTasks.GetPersonRelationshipTypesByName(vm.PersonRelationshipTypeName);
if (type != null && types != null && types.Any() && types.Where(x => x.Id != type.Id).Any())
ModelState.AddModelError("PersonRelationshipTypeName", "Relationship type already exists.");
if (ModelState.IsValid)
{
type.PersonRelationshipTypeName = vm.PersonRelationshipTypeName;
type.IsCommutative = vm.IsCommutative;
type.Archive = vm.Archive;
type.Notes = vm.Notes;
type = this.personTasks.SavePersonRelationshipType(type);
return RedirectToAction("Details", new { id = vm.Id });
}
return Edit(vm.Id);
}
[Transaction]
public ActionResult Delete(int id)
{
PersonRelationshipType type = this.personTasks.GetPersonRelationshipType(id);
if (type != null)
{
if (this.personTasks.DeletePersonRelationshipType(type))
return RedirectToAction("Index");
else
return RedirectToAction("Details", new { id = id });
}
return new HttpNotFoundResult();
}
}
} |
using System.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System
{
/// <summary>Represents a time interval.</summary>
/// <remarks>
/// A TimeSpan2 object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number
/// of days, hours, minutes, seconds, and fractions of a second. The TimeSpan2 structure can also be used to represent the time of day,
/// but only if the time is unrelated to a particular date.
/// </remarks>
[Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)]
[TypeConverter(typeof(TimeSpan2Converter))]
public struct TimeSpan2 : IComparable, IComparable<TimeSpan2>, IComparable<TimeSpan>, IEquatable<TimeSpan2>, IEquatable<TimeSpan>, IFormattable, IConvertible, ISerializable, IXmlSerializable
{
[ComVisible(false)]
private TimeSpan core;
/// <summary>Represents the maximum <see cref="TimeSpan2"/> value. This field is read-only.</summary>
public static readonly TimeSpan2 MaxValue = new(TimeSpan.MaxValue);
/// <summary>Represents the minimum <see cref="TimeSpan2"/> value. This field is read-only.</summary>
public static readonly TimeSpan2 MinValue = new(TimeSpan.MinValue);
/// <summary>Represents the zero <see cref="TimeSpan2"/> value. This field is read-only.</summary>
public static readonly TimeSpan2 Zero = new(TimeSpan.Zero);
/// <summary>Represents the number of ticks in 1 day. This field is constant.</summary>
public static readonly long TicksPerDay = TimeSpan.TicksPerDay;
/// <summary>Represents the number of ticks in 1 hour. This field is constant.</summary>
public static readonly long TicksPerHour = TimeSpan.TicksPerHour;
/// <summary>Represents the number of ticks in 1 millisecond. This field is constant.</summary>
public static readonly long TicksPerMillisecond = TimeSpan.TicksPerMillisecond;
/// <summary>Represents the number of ticks in 1 minute. This field is constant.</summary>
public static readonly long TicksPerMinute = TimeSpan.TicksPerMinute;
/// <summary>Represents the number of ticks in 1 second. This field is constant.</summary>
public static readonly long TicksPerSecond = TimeSpan.TicksPerSecond;
/// <summary>Initializes a new <see cref="TimeSpan2"/> with the specified <see cref="TimeSpan"/>.</summary>
/// <param name="span">The initializing <see cref="TimeSpan"/>.</param>
public TimeSpan2(TimeSpan span) => core = span;
/// <summary>Initializes a new <see cref="TimeSpan2"/> with the specified number of ticks.</summary>
/// <param name="ticks">A time period expressed in 100-nanosecond units.</param>
public TimeSpan2(long ticks) => core = new TimeSpan(ticks);
/// <summary>Initializes a new <see cref="TimeSpan2"/> with the specified number of hours, minutes, and seconds.</summary>
/// <param name="hours">Number of hours.</param>
/// <param name="minutes">Number of minutes.</param>
/// <param name="seconds">Number of seconds.</param>
public TimeSpan2(int hours, int minutes, int seconds) => core = new TimeSpan(hours, minutes, seconds);
/// <summary>Initializes a new <see cref="TimeSpan2"/> with the specified number of days, hours, minutes, and seconds.</summary>
/// <param name="days">Number of days.</param>
/// <param name="hours">Number of hours.</param>
/// <param name="minutes">Number of minutes.</param>
/// <param name="seconds">Number of seconds.</param>
public TimeSpan2(int days, int hours, int minutes, int seconds)
: this(days, hours, minutes, seconds, 0)
{
}
/// <summary>Initializes a new <see cref="TimeSpan2"/> with the specified number of days, hours, minutes, seconds, and milliseconds.</summary>
/// <param name="days">Number of days.</param>
/// <param name="hours">Number of hours.</param>
/// <param name="minutes">Number of minutes.</param>
/// <param name="seconds">Number of seconds.</param>
/// <param name="milliseconds">Number of milliseconds</param>
public TimeSpan2(int days, int hours, int minutes, int seconds, int milliseconds) => core = new TimeSpan(days, hours, minutes, seconds, milliseconds);
/// <summary>Initializes a new instance of the <see cref="TimeSpan2"/> struct.</summary>
/// <param name="info">The serialization info.</param>
/// <param name="context">The serialization context.</param>
private TimeSpan2(SerializationInfo info, StreamingContext context) => core = new TimeSpan(info.GetInt64("ticks"));
/// <summary>Gets the days component of the time interval represented by the current <see cref="TimeSpan2"/> structure.</summary>
/// <value>The day component of this instance. The return value can be positive or negative.</value>
[Browsable(false)]
public int Days => core.Days;
/// <summary>Gets the hours component of the time interval represented by the current <see cref="TimeSpan2"/> structure.</summary>
/// <value>The hours component of this instance. The return value ranges from -23 through 23.</value>
[Browsable(false)]
public int Hours => core.Hours;
/// <summary>Gets a value indicating whether this instance is zero.</summary>
/// <value><c>true</c> if this instance is zero; otherwise, <c>false</c>.</value>
[Browsable(false)]
public bool IsZero => core == TimeSpan.Zero;
/// <summary>Gets the milliseconds component of the time interval represented by the current <see cref="TimeSpan2"/> structure.</summary>
/// <value>The milliseconds component of this instance. The return value ranges from -999 through 999.</value>
[Browsable(false)]
public int Milliseconds => core.Milliseconds;
/// <summary>Gets the minutes component of the time interval represented by the current <see cref="TimeSpan2"/> structure.</summary>
/// <value>The minutes component of this instance. The return value ranges from -59 through 59.</value>
[Browsable(false)]
public int Minutes => core.Minutes;
/// <summary>Gets the seconds component of the time interval represented by the current <see cref="TimeSpan2"/> structure.</summary>
/// <value>The seconds component of this instance. The return value ranges from -59 through 59.</value>
[Browsable(false)]
public int Seconds => core.Seconds;
/// <summary>Gets the number of ticks that represent the value of the current <see cref="TimeSpan2"/> structure.</summary>
/// <value>The number of ticks contained in this instance.</value>
[Browsable(false)]
public long Ticks => core.Ticks;
/// <summary>Gets the value of the current <see cref="TimeSpan2"/> structure expressed in whole and fractional days.</summary>
/// <value>The total number of days represented by this instance.</value>
[Browsable(false)]
public double TotalDays => core.TotalDays;
/// <summary>Gets the value of the current <see cref="TimeSpan2"/> structure expressed in whole and fractional hours.</summary>
/// <value>The total number of hours represented by this instance.</value>
[Browsable(false)]
public double TotalHours => core.TotalHours;
/// <summary>Gets the value of the current <see cref="TimeSpan2"/> structure expressed in whole and fractional milliseconds.</summary>
/// <value>The total number of milliseconds represented by this instance.</value>
[Browsable(false)]
public double TotalMilliseconds => core.TotalMilliseconds;
/// <summary>Gets the value of the current <see cref="TimeSpan2"/> structure expressed in whole and fractional minutes.</summary>
/// <value>The total number of minutes represented by this instance.</value>
[Browsable(false)]
public double TotalMinutes => core.TotalMinutes;
/// <summary>Gets the value of the current <see cref="TimeSpan2"/> structure expressed in whole and fractional seconds.</summary>
/// <value>The total number of seconds represented by this instance.</value>
[Browsable(false)]
public double TotalSeconds => core.TotalSeconds;
/// <summary>Performs an implicit conversion from <see cref="System.TimeSpan2"/> to <see cref="System.TimeSpan"/>.</summary>
/// <param name="ts2">The <see cref="TimeSpan2"/> structure to convert.</param>
/// <returns>The <see cref="TimeSpan"/> equivalent of the converted <see cref="TimeSpan2"/>.</returns>
public static implicit operator TimeSpan(TimeSpan2 ts2) => ts2.core;
/// <summary>Performs an implicit conversion from <see cref="System.TimeSpan"/> to <see cref="System.TimeSpan2"/>.</summary>
/// <param name="ts">The <see cref="TimeSpan"/> structure to convert.</param>
/// <returns>The <see cref="TimeSpan2"/> equivalent of the converted <see cref="TimeSpan"/>.</returns>
public static implicit operator TimeSpan2(TimeSpan ts) => new(ts);
/// <summary>Indicates whether two <see cref="TimeSpan2"/> instances are not equal.</summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns><c>true</c> if the values of <paramref name="t1"/> and <paramref name="t2"/> are not equal; otherwise, <c>false</c>.</returns>
public static bool operator !=(TimeSpan2 t1, TimeSpan2 t2) => t1.core != t2.core;
/// <summary>Returns the specified instance of <see cref="TimeSpan2"/>.</summary>
/// <param name="t">A <see cref="TimeSpan2"/>.</param>
/// <returns>Returns <paramref name="t"/>.</returns>
public static TimeSpan2 operator +(TimeSpan2 t) => t;
/// <summary>Adds two specified <see cref="TimeSpan2"/> instances.</summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns>A <see cref="TimeSpan2"/> whose value is the sum of the values of <paramref name="t1"/> and <paramref name="t2"/>.</returns>
public static TimeSpan2 operator +(TimeSpan2 t1, TimeSpan2 t2) => t1.Add(t2);
/// <summary>Returns a <see cref="TimeSpan2"/> whose value is the negated value of the specified instance.</summary>
/// <param name="t">A <see cref="TimeSpan2"/>.</param>
/// <returns>A <see cref="TimeSpan2"/> with the same numeric value as this instance, but the opposite sign.</returns>
public static TimeSpan2 operator -(TimeSpan2 t) => new(-t.core);
/// <summary>Subtracts a specified <see cref="TimeSpan2"/> from another specified <c>TimeSpan2</c>.</summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns>
/// A <see cref="TimeSpan2"/> whose value is the result of the value of <paramref name="t1"/> minus the value of <paramref name="t2"/>.
/// </returns>
public static TimeSpan2 operator -(TimeSpan2 t1, TimeSpan2 t2) => t1.Subtract(t2);
/// <summary>Indicates whether a specified <see cref="TimeSpan2"/> is less than another specified <see cref="TimeSpan2"/>.</summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns><c>true</c> if the value of <paramref name="t1"/> is less than the value of <paramref name="t2"/>; otherwise, <c>false</c>.</returns>
public static bool operator <(TimeSpan2 t1, TimeSpan2 t2) => t1.core < t2.core;
/// <summary>Indicates whether a specified <see cref="TimeSpan2"/> is less than or equal to another specified <see cref="TimeSpan2"/>.</summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns>
/// <c>true</c> if the value of <paramref name="t1"/> is less than or equal to the value of <paramref name="t2"/>; otherwise, <c>false</c>.
/// </returns>
public static bool operator <=(TimeSpan2 t1, TimeSpan2 t2) => t1.core <= t2.core;
/// <summary>Indicates whether two <see cref="TimeSpan2"/> instances are equal.</summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns><c>true</c> if the values of <paramref name="t1"/> and <paramref name="t2"/> are equal; otherwise, <c>false</c>.</returns>
public static bool operator ==(TimeSpan2 t1, TimeSpan2 t2) => t1.core == t2.core;
/// <summary>Indicates whether a specified <see cref="TimeSpan2"/> is greater than another specified <see cref="TimeSpan2"/>.</summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns>
/// <c>true</c> if the value of <paramref name="t1"/> is greater than the value of <paramref name="t2"/>; otherwise, <c>false</c>.
/// </returns>
public static bool operator >(TimeSpan2 t1, TimeSpan2 t2) => t1.core > t2.core;
/// <summary>Indicates whether a specified <see cref="TimeSpan2"/> is greater than or equal to another specified <see cref="TimeSpan2"/>.</summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns>
/// <c>true</c> if the value of <paramref name="t1"/> is greater than or equal to the value of <paramref name="t2"/>; otherwise, <c>false</c>.
/// </returns>
public static bool operator >=(TimeSpan2 t1, TimeSpan2 t2) => t1.core >= t2.core;
/// <summary>
/// Compares two <see cref="TimeSpan2"/> values and returns an integer that indicates whether the first value is shorter than, equal
/// to, or longer than the second value.
/// </summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns>
/// <list>
/// <listheader>
/// <term>Value</term>
/// <description>Condition</description>
/// </listheader>
/// <item>
/// <term>-1</term>
/// <description><paramref name="t1"/> is shorter than <paramref name="t2"/></description>
/// </item>
/// <item>
/// <term>0</term>
/// <description><paramref name="t1"/> is equal to <paramref name="t2"/></description>
/// </item>
/// <item>
/// <term>1</term>
/// <description><paramref name="t1"/> is longer than <paramref name="t2"/></description>
/// </item>
/// </list>
/// </returns>
public static int Compare(TimeSpan2 t1, TimeSpan2 t2) => TimeSpan.Compare(t1.core, t2.core);
/// <summary>Indicates whether two <see cref="TimeSpan2"/> instances are equal.</summary>
/// <param name="t1">A <see cref="TimeSpan2"/>.</param>
/// <param name="t2">A <c>TimeSpan2</c>.</param>
/// <returns><c>true</c> if the values of <paramref name="t1"/> and <paramref name="t2"/> are equal; otherwise, <c>false</c>.</returns>
public static bool Equals(TimeSpan2 t1, TimeSpan2 t2) => t1.core == t2.core;
/// <summary>
/// Returns a <see cref="TimeSpan2"/> that represents a specified number of days, where the specification is accurate to the nearest millisecond.
/// </summary>
/// <param name="value">A number of days, accurate to the nearest millisecond.</param>
/// <returns>A <see cref="TimeSpan2"/> that represents <paramref name="value"/>.</returns>
public static TimeSpan2 FromDays(double value) => new(TimeSpan.FromDays(value));
/// <summary>
/// Returns a <see cref="TimeSpan2"/> that represents a specified number of hours, where the specification is accurate to the
/// nearest millisecond.
/// </summary>
/// <param name="value">A number of hours, accurate to the nearest millisecond.</param>
/// <returns>A <see cref="TimeSpan2"/> that represents <paramref name="value"/>.</returns>
public static TimeSpan2 FromHours(double value) => new(TimeSpan.FromHours(value));
/// <summary>Returns a <see cref="TimeSpan2"/> that represents a specified number of milliseconds.</summary>
/// <param name="value">A number of milliseconds.</param>
/// <returns>A <see cref="TimeSpan2"/> that represents <paramref name="value"/>.</returns>
public static TimeSpan2 FromMilliseconds(double value) => new(TimeSpan.FromMilliseconds(value));
/// <summary>
/// Returns a <see cref="TimeSpan2"/> that represents a specified number of minutes, where the specification is accurate to the
/// nearest millisecond.
/// </summary>
/// <param name="value">A number of minutes, accurate to the nearest millisecond.</param>
/// <returns>A <see cref="TimeSpan2"/> that represents <paramref name="value"/>.</returns>
public static TimeSpan2 FromMinutes(double value) => new(TimeSpan.FromMinutes(value));
/// <summary>
/// Returns a <see cref="TimeSpan2"/> that represents a specified number of seconds, where the specification is accurate to the
/// nearest millisecond.
/// </summary>
/// <param name="value">A number of seconds, accurate to the nearest millisecond.</param>
/// <returns>A <see cref="TimeSpan2"/> that represents <paramref name="value"/>.</returns>
public static TimeSpan2 FromSeconds(double value) => new(TimeSpan.FromSeconds(value));
/// <summary>Returns a <see cref="TimeSpan2"/> that represents a specified time, where the specification is in units of ticks.</summary>
/// <param name="value">A number of ticks that represent a time.</param>
/// <returns>A <see cref="TimeSpan2"/> with a value of <paramref name="value"/>.</returns>
public static TimeSpan2 FromTicks(long value) => new(TimeSpan.FromTicks(value));
/// <summary>Converts the specified string representation of a time span to its <see cref="TimeSpan2"/> equivalent.</summary>
/// <param name="value">A string containing a time span to parse.</param>
/// <returns>A <see cref="TimeSpan2"/> equivalent to the time span contained in <paramref name="value"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c>.</exception>
/// <exception cref="FormatException"><paramref name="value"/> does not contain a valid string representation of a time span.</exception>
public static TimeSpan2 Parse(string value) => Parse(value, null);
/// <summary>
/// Converts the specified string representation of a time span to its <see cref="TimeSpan2"/> equivalent using the specified
/// culture-specific format information.
/// </summary>
/// <param name="value">A string containing a time span to parse.</param>
/// <param name="formatProvider">An object that supplies culture-specific format information about <paramref name="value"/>.</param>
/// <returns>
/// A <see cref="TimeSpan2"/> equivalent to the time span contained in <paramref name="value"/> as specified by <paramref name="formatProvider"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c>.</exception>
/// <exception cref="FormatException"><paramref name="value"/> does not contain a valid string representation of a time span.</exception>
public static TimeSpan2 Parse(string value, IFormatProvider formatProvider)
{
TimeSpan2FormatInfo fi = TimeSpan2FormatInfo.GetInstance(formatProvider);
return new TimeSpan2(fi.Parse(value, null));
}
/// <summary>
/// Converts the string representation of a time interval to its <see cref="TimeSpan2"/> equivalent by using the specified array of
/// format strings and culture-specific format information. The format of the string representation must match the specified format exactly.
/// </summary>
/// <param name="input">A string that specifies the time interval to convert.</param>
/// <param name="format">A standard or custom format string that defines the required format of <paramref name="input"/>.</param>
/// <param name="formatProvider">An object that provides culture-specific formatting information.</param>
/// <returns>
/// A time interval that corresponds to <paramref name="input"/>, as specified by <paramref name="format"/> and <paramref name="formatProvider"/>.
/// </returns>
public static TimeSpan2 ParseExact(string input, string format, IFormatProvider formatProvider) => ParseExact(input, new[] { format }, formatProvider);
/// <summary>
/// Converts the string representation of a time interval to its <see cref="TimeSpan2"/> equivalent by using the specified format
/// and culture-specific format information. The format of the string representation must match the specified format exactly.
/// </summary>
/// <param name="input">A string that specifies the time interval to convert.</param>
/// <param name="formats">A array of standard or custom format strings that defines the required format of <paramref name="input"/>.</param>
/// <param name="formatProvider">An object that provides culture-specific formatting information.</param>
/// <returns>
/// A time interval that corresponds to <paramref name="input"/>, as specified by <paramref name="formats"/> and <paramref name="formatProvider"/>.
/// </returns>
public static TimeSpan2 ParseExact(string input, string[] formats, IFormatProvider formatProvider)
{
TimeSpan2FormatInfo fi = TimeSpan2FormatInfo.GetInstance(formatProvider);
return fi.ParseExact(input, formats, null);
}
/// <summary>
/// Converts the specified string representation of a date and time to its <see cref="TimeSpan2"/> equivalent and returns a value
/// that indicates whether the conversion succeeded.
/// </summary>
/// <param name="s">A string containing a time span to convert.</param>
/// <param name="result">
/// When this method returns, contains the <see cref="TimeSpan2"/> value equivalent to the time span contained in <paramref
/// name="s"/>, if the conversion succeeded, or <c>TimeSpan.Zero</c> if the conversion failed. The conversion fails if the <paramref
/// name="s"/> parameter is <c>null</c>, is an empty string (""), or does not contain a valid string representation of a time span.
/// This parameter is passed uninitialized.
/// </param>
/// <returns><c>true</c> if the <paramref name="s"/> parameter was converted successfully; otherwise, <c>false</c>.</returns>
public static bool TryParse(string s, out TimeSpan2 result) => TryParse(s, null, out result);
/// <summary>
/// Converts the specified string representation of a date and time to its <see cref="TimeSpan2"/> equivalent and returns a value
/// that indicates whether the conversion succeeded.
/// </summary>
/// <param name="s">A string containing a time span to convert.</param>
/// <param name="formatProvider">An object that supplies culture-specific format information about <paramref name="s"/>.</param>
/// <param name="result">
/// When this method returns, contains the <see cref="TimeSpan2"/> value equivalent to the time span contained in <paramref
/// name="s"/>, if the conversion succeeded, or <c>TimeSpan.Zero</c> if the conversion failed. The conversion fails if the <paramref
/// name="s"/> parameter is <c>null</c>, is an empty string (""), or does not contain a valid string representation of a time span.
/// This parameter is passed uninitialized.
/// </param>
/// <returns><c>true</c> if the <paramref name="s"/> parameter was converted successfully; otherwise, <c>false</c>.</returns>
public static bool TryParse(string s, IFormatProvider formatProvider, out TimeSpan2 result)
{
TimeSpan2FormatInfo fi = TimeSpan2FormatInfo.GetInstance(formatProvider);
return fi.TryParse(s, null, out result.core);
}
/// <summary>
/// Converts the string representation of a time interval to its <see cref="TimeSpan2"/> equivalent by using the specified format
/// and culture-specific format information, and returns a value that indicates whether the conversion succeeded. The format of the
/// string representation must match the specified format exactly.
/// </summary>
/// <param name="input">A string that specifies the time interval to convert.</param>
/// <param name="format">A standard or custom format string that defines the required format of <paramref name="input"/>.</param>
/// <param name="formatProvider">An object that supplies culture-specific format information about <paramref name="input"/>.</param>
/// <param name="result">
/// When this method returns, contains an object that represents the time interval specified by <paramref name="input"/>, or <see
/// cref="TimeSpan.Zero"/> if the conversion failed. This parameter is passed uninitialized.
/// </param>
/// <returns><c>true</c> if <paramref name="input"/> was converted successfully; otherwise, <c>false</c>.</returns>
public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, out TimeSpan2 result) => TryParseExact(input, new[] { format }, formatProvider, out result);
/// <summary>
/// Converts the string representation of a time interval to its <see cref="TimeSpan2"/> equivalent by using the specified formats
/// and culture-specific format information, and returns a value that indicates whether the conversion succeeded. The format of the
/// string representation must match one of the specified formats exactly.
/// </summary>
/// <param name="input">A string that specifies the time interval to convert.</param>
/// <param name="formats">A array of standard or custom format strings that define the acceptable formats of <paramref name="input"/>.</param>
/// <param name="formatProvider">An object that supplies culture-specific format information about <paramref name="input"/>.</param>
/// <param name="result">
/// When this method returns, contains an object that represents the time interval specified by <paramref name="input"/>, or <see
/// cref="TimeSpan.Zero"/> if the conversion failed. This parameter is passed uninitialized.
/// </param>
/// <returns><c>true</c> if <paramref name="input"/> was converted successfully; otherwise, <c>false</c>.</returns>
public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, out TimeSpan2 result)
{
TimeSpan2FormatInfo fi = TimeSpan2FormatInfo.GetInstance(formatProvider);
return fi.TryParseExact(input, formats, null, out result.core);
}
/// <summary>Adds the specified <see cref="TimeSpan2"/> to this instance.</summary>
/// <param name="ts">A <see cref="TimeSpan2"/>.</param>
/// <returns>A <see cref="TimeSpan2"/> that represents the value of this instance plus the value of <paramref name="ts"/>.</returns>
public TimeSpan2 Add(TimeSpan2 ts) => new(core.Add(ts.core));
/// <summary>
/// Compares this instance to a specified object and returns an integer that indicates whether this [instance] is shorter than,
/// equal to, or longer than the specified object.
/// </summary>
/// <param name="obj">An object to compare, or <c>null</c>.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="obj"/>.
/// <list>
/// <listheader>
/// <term>Value</term>
/// <description>Condition</description>
/// </listheader>
/// <item>
/// <term>-1</term>
/// <description>This instance is shorter than <paramref name="obj"/></description>
/// </item>
/// <item>
/// <term>0</term>
/// <description>This instance is equal to <paramref name="obj"/></description>
/// </item>
/// <item>
/// <term>1</term>
/// <description>This instance is longer than <paramref name="obj"/></description>
/// </item>
/// </list>
/// </returns>
public int CompareTo(object obj) => core.CompareTo(obj is TimeSpan2 ts2 ? ts2.core : obj);
/// <summary>
/// Compares this instance to a specified <see cref="TimeSpan2"/> object and returns an integer that indicates whether this
/// [instance] is shorter than, equal to, or longer than the <see cref="TimeSpan2"/> object.
/// </summary>
/// <param name="other">A <see cref="TimeSpan2"/> object to compare to this instance.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// <list>
/// <listheader>
/// <term>Value</term>
/// <description>Condition</description>
/// </listheader>
/// <item>
/// <term>-1</term>
/// <description>This instance is shorter than <paramref name="other"/></description>
/// </item>
/// <item>
/// <term>0</term>
/// <description>This instance is equal to <paramref name="other"/></description>
/// </item>
/// <item>
/// <term>1</term>
/// <description>This instance is longer than <paramref name="other"/></description>
/// </item>
/// </list>
/// </returns>
public int CompareTo(TimeSpan2 other) => core.CompareTo(other.core);
/// <summary>
/// Compares this instance to a specified <see cref="TimeSpan"/> object and returns an integer that indicates whether this
/// [instance] is shorter than, equal to, or longer than the <see cref="TimeSpan2"/> object.
/// </summary>
/// <param name="other">A <see cref="TimeSpan"/> object to compare to this instance.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// <list>
/// <listheader>
/// <term>Value</term>
/// <description>Condition</description>
/// </listheader>
/// <item>
/// <term>-1</term>
/// <description>This instance is shorter than <paramref name="other"/></description>
/// </item>
/// <item>
/// <term>0</term>
/// <description>This instance is equal to <paramref name="other"/></description>
/// </item>
/// <item>
/// <term>1</term>
/// <description>This instance is longer than <paramref name="other"/></description>
/// </item>
/// </list>
/// </returns>
public int CompareTo(TimeSpan other) => core.CompareTo(other);
/// <summary>
/// Returns a new <see cref="TimeSpan2"/> object whose value is the absolute value of the current <see cref="TimeSpan2"/> object.
/// </summary>
/// <returns>A new <see cref="TimeSpan2"/> object whose value is the absolute value of the current <see cref="TimeSpan2"/> object.</returns>
public TimeSpan2 Duration() => new(core.Duration());
/// <summary>Indicates whether the current object is equal to another object.</summary>
/// <param name="obj">An object to compare with this object.</param>
/// <returns><c>true</c> if the current object is equal to the <paramref name="obj"/> parameter; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj) => obj is TimeSpan2 ts2 ? core.Equals(ts2.core) : core.Equals(obj);
/// <summary>Indicates whether the current object is equal to a specified <see cref="string"/>.</summary>
/// <param name="str">A <see cref="string"/> to compare with this object.</param>
/// <returns>
/// <c>true</c> if the current object is equal to the <paramref name="str"/> parameter once converted to a <see cref="TimeSpan2"/>;
/// otherwise, <c>false</c>.
/// </returns>
public bool Equals(string str)
{
try { return Equals(Parse(str, CultureInfo.CurrentUICulture)); } catch { }
return false;
}
/// <summary>Indicates whether the current object is equal to a specified <see cref="TimeSpan2"/> object.</summary>
/// <param name="other">A <see cref="TimeSpan2"/> object to compare with this object.</param>
/// <returns><c>true</c> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <c>false</c>.</returns>
public bool Equals(TimeSpan2 other) => core.Equals(other.core);
/// <summary>Indicates whether the current object is equal to a specified <see cref="TimeSpan"/> object.</summary>
/// <param name="other">A <see cref="TimeSpan"/> object to compare with this object.</param>
/// <returns><c>true</c> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <c>false</c>.</returns>
public bool Equals(TimeSpan other) => core.Equals(other);
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>A 32-bit signed integer that is the hash code for this instance.</returns>
public override int GetHashCode() => core.GetHashCode();
TypeCode IConvertible.GetTypeCode() => TypeCode.Object;
bool IConvertible.ToBoolean(IFormatProvider provider) => throw new InvalidCastException();
byte IConvertible.ToByte(IFormatProvider provider) => Convert.ToByte(core.Ticks);
char IConvertible.ToChar(IFormatProvider provider) => throw new InvalidCastException();
DateTime IConvertible.ToDateTime(IFormatProvider provider) => throw new InvalidCastException();
decimal IConvertible.ToDecimal(IFormatProvider provider) => Convert.ToDecimal(core.Ticks);
double IConvertible.ToDouble(IFormatProvider provider) => Convert.ToDouble(core.Ticks);
short IConvertible.ToInt16(IFormatProvider provider) => Convert.ToInt16(core.Ticks);
int IConvertible.ToInt32(IFormatProvider provider) => Convert.ToInt32(core.Ticks);
long IConvertible.ToInt64(IFormatProvider provider) => core.Ticks;
sbyte IConvertible.ToSByte(IFormatProvider provider) => Convert.ToSByte(core.Ticks);
float IConvertible.ToSingle(IFormatProvider provider) => Convert.ToSingle(core.Ticks);
string IConvertible.ToString(IFormatProvider provider) => ToString(null, provider);
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if (conversionType == typeof(TimeSpan))
{
return core;
}
if (conversionType == typeof(TimeSpan2))
{
return this;
}
return Convert.ChangeType(this, conversionType, provider);
}
ushort IConvertible.ToUInt16(IFormatProvider provider) => Convert.ToUInt16(core.Ticks);
uint IConvertible.ToUInt32(IFormatProvider provider) => Convert.ToUInt32(core.Ticks);
ulong IConvertible.ToUInt64(IFormatProvider provider) => Convert.ToUInt64(core.Ticks);
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info is null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue("ticks", core.Ticks);
}
XmlSchema IXmlSerializable.GetSchema() => null;
void IXmlSerializable.ReadXml(XmlReader reader) => core = XmlConvert.ToTimeSpan(reader?.ReadContentAsString());
void IXmlSerializable.WriteXml(XmlWriter writer) => writer?.WriteValue(XmlConvert.ToString(core));
/// <summary>Returns a <see cref="TimeSpan2"/> whose value is the negated value of this instance.</summary>
/// <returns>The same numeric value as this instance, but with the opposite sign.</returns>
public TimeSpan2 Negate() => new(core.Negate());
/// <summary>Subtracts the specified <see cref="TimeSpan2"/> from this instance.</summary>
/// <param name="ts">A <see cref="TimeSpan2"/>.</param>
/// <returns>A <see cref="TimeSpan2"/> whose value is the result of the value of this instance minus the value of <paramref name="ts"/>.</returns>
public TimeSpan2 Subtract(TimeSpan2 ts) => new(core.Subtract(ts.core));
/// <summary>Returns string representation of the value of this instance using the specified format.</summary>
/// <param name="format">A TimeSpan format string.</param>
/// <param name="formatProvider">
/// An <see cref="T:System.IFormatProvider"/> object that supplies format information about the current instance.
/// </param>
/// <returns>A string representation of value of the current <see cref="TimeSpan2"/> object as specified by format.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
TimeSpan2FormatInfo tfi = TimeSpan2FormatInfo.GetInstance(formatProvider);
return tfi.Format(format, this, formatProvider);
}
/// <summary>Returns string representation of the value of this instance using the specified format.</summary>
/// <param name="format">A TimeSpan format string.</param>
/// <returns>A string representation of value of the current <see cref="TimeSpan2"/> object as specified by format.</returns>
/// <remarks>
/// <para>The following table lists the standard TimeSpan format patterns.</para>
/// <list type="table">
/// <listheader>
/// <term>Format specifier</term>
/// <description>Name</description>
/// <description>Description</description>
/// <description>Examples</description>
/// </listheader>
/// <item>
/// <term>"c"</term>
/// <description>Constant (invariant) format</description>
/// <description>This specifier is not culture-sensitive. It takes the form
/// <code>
///[-][d’.’]hh’:’mm’:’ss[‘.’fffffff]
/// </code>
/// .
/// </description>
/// <description></description>
/// </item>
/// <item>
/// <term>"f"</term>
/// <description>General word format</description>
/// <description></description>
/// <description></description>
/// </item>
/// <item>
/// <term>"g"</term>
/// <description>General short format</description>
/// <description>This specifier outputs only what is needed. It is culture-sensitive and takes the form
/// <code>
///[-][d’:’]h’:’mm’:’ss[.FFFFFFF]
/// </code>
/// .
/// </description>
/// <description></description>
/// </item>
/// <item>
/// <term>"G"</term>
/// <description>General long format</description>
/// <description>This specifier always outputs days and seven fractional digits. It is culture-sensitive and takes the form
/// <code>
///[-]d’:’hh’:’mm’:’ss.fffffff
/// </code>
/// .
/// </description>
/// <description></description>
/// </item>
/// <item>
/// <term>"j"</term>
/// <description>JIRA duration format</description>
/// <description>This specifier outputs days, hours, minutes and seconds in the style defined by JIRA. It takes the form
/// <code>
///[w'w'] [d'd'] [h'h'] [m'm'] [s's']
/// </code>
/// .
/// </description>
/// <description></description>
/// </item>
/// <item>
/// <term>"x"</term>
/// <description>ISO 8601 format for time intervals</description>
/// <description>
/// This specifier outputs days, hours, minutes, seconds and milliseconds in the style defined by ISO 8601. It takes the form
/// <code>
///'P'[d'D']['T'[h'H'][m'M'][p3'S']]
/// </code>
/// .
/// </description>
/// <description></description>
/// </item>
/// </list>
/// <para>The following table lists the standard TimeSpan format patterns.</para>
/// <list type="table">
/// <listheader>
/// <term>Format specifier</term>
/// <description>Description</description>
/// <description>Examples</description>
/// </listheader>
/// <item>
/// <term>"d", "%d"</term>
/// <description>The number of whole days in the time interval.</description>
/// <description></description>
/// </item>
/// <item>
/// <term>"dd"-"dddddddd"</term>
/// <description>The number of whole days in the time interval, padded with leading zeros as needed.</description>
/// <description></description>
/// </item>
/// <item>
/// <term>"h", "%h"</term>
/// <description>
/// The number of whole hours in the time interval that are not counted as part of days. Single-digit hours do not have a leading zero.
/// </description>
/// <description></description>
/// </item>
/// <item>
/// <term>"hh"</term>
/// <description>
/// The number of whole hours in the time interval that are not counted as part of days. Single-digit hours have a leading zero.
/// </description>
/// <description></description>
/// </item>
/// </list>
/// </remarks>
public string ToString(string format) => TimeSpan2FormatInfo.CurrentInfo.Format(format, this, null);
/// <summary>Returns the string representation of the value of this instance.</summary>
/// <returns>
/// A string that represents the value of this instance. The return value is of the form:
/// <para>[-][d.]hh:mm:ss[.fffffff]</para>
/// </returns>
public override string ToString() => core.ToString();
}
} |
using System;
using UIKit;
namespace AppExercise.iOS.Theme
{
public static class Colors
{
private static Lazy<UIColor> strongBlue = new Lazy<UIColor>(() => UIColor.FromRGB(0, 64, 117));
public static UIColor StrongBlue
{
get { return strongBlue.Value; }
}
}
}
|
using System;
using System.Collections;
using System.Linq;
using System.Windows.Forms;
using DelftTools.Functions.Filters;
using DelftTools.Utils;
using GeoAPI.Extensions.Coverages;
using GeoAPI.Geometries;
using GisSharpBlog.NetTopologySuite.Geometries;
using NetTopologySuite.Extensions.Coverages;
using SharpMap.Layers;
using SharpMap.UI.Forms;
namespace SharpMap.UI.Tools
{
public class QueryTool : MapTool
{
private readonly ToolTip tooltipControl = new ToolTip()
{
AutomaticDelay = 1000,
ToolTipIcon = ToolTipIcon.Info
};
public QueryTool(MapControl mapControl): base(mapControl)
{
Name = "Query";
}
/// <summary>
/// Use this property to enable or disable tool. When the measure tool is deactivated, it cleans up old measurements.
/// </summary>
public override bool IsActive
{
get { return base.IsActive; }
set
{
base.IsActive = value;
if (!IsActive)
Clear();
}
}
private void Clear()
{
tooltipControl.SetToolTip((Control) MapControl, "");
}
private string GetCoverageValues(ICoordinate worldPosition)
{
if (!IsActive || worldPosition == null)
return "";
var layerValues = "";
ICoordinate coordinate = new Coordinate(worldPosition.X, worldPosition.Y);
var allLayers = Map.GetAllLayers(true).Where(l => l.Visible);
foreach (var layer in allLayers)
{
if (!(layer is ICoverageLayer))
continue;
var envelope = (IEnvelope)layer.Envelope.Clone();
envelope.ExpandBy(layer.Envelope.Width*0.1); //10% margin
if (!envelope.Contains(coordinate))
continue;
var coverage = ((ICoverageLayer)layer).Coverage;
if (coverage.IsTimeDependent)
{
if (layer is ITimeNavigatable)
{
var timeNav = (layer as ITimeNavigatable);
if (timeNav.TimeSelectionStart.HasValue)
{
var time = timeNav.TimeSelectionStart.Value;
coverage = coverage.FilterTime(time);
}
}
else
{
continue; //nothing to filter on
}
}
SetEvaluationTolerance(coverage);
var value = coverage.Evaluate(coordinate);
layerValues += layer.Name + " : " + GetValueString(value) + "\n";
}
return layerValues;
}
private static string GetValueString(object value)
{
var valueString = "";
if (value is IEnumerable)
{
foreach (var valueItem in value as IEnumerable)
{
valueString += valueItem + ",";
}
valueString = (valueString == "") ? "<empty>" : valueString.TrimEnd(',');
}
else
{
valueString = (value?? "<empty>").ToString();
}
return valueString;
}
private void SetEvaluationTolerance(ICoverage coverage)
{
if (coverage is FeatureCoverage)
{
var tolerance = Map.PixelSize * 5;
var featureCoverage = ((FeatureCoverage) coverage);
if (featureCoverage.EvaluateTolerance != tolerance)
{
featureCoverage.EvaluateTolerance = tolerance;
}
}
if (coverage is NetworkCoverage)
{
var tolerance = Map.PixelSize * 20;
var networkCoverage = (NetworkCoverage) coverage;
if (networkCoverage.EvaluateTolerance != tolerance)
{
networkCoverage.EvaluateTolerance = tolerance;
}
}
}
private System.Drawing.Point previousLocation;
public override void OnMouseMove(ICoordinate worldPosition, MouseEventArgs e)
{
if (previousLocation.X == e.Location.X && previousLocation.Y == e.Location.Y)
{
return;
}
previousLocation = e.Location;
tooltipControl.SetToolTip((Control)MapControl, GetCoverageValues(worldPosition));
}
}
} |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("BuildTools")]
[assembly: AssemblyDescription("Generates manifest for mod.")]
[assembly: AssemblyCompany("Igorious")]
[assembly: AssemblyProduct("BuildTools")]
[assembly: AssemblyCopyright("© Igorious 2017")]
[assembly: Guid("b4babc77-4799-4cf8-9ad8-78613286ef75")]
[assembly: AssemblyVersion("1.0.0.0")] |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using OdeToFood.Core;
using OdeToFood.Data;
using static OdeToFood.Core.Restaurant;
namespace OdeToFood.Pages.Restaurants
{
public class EditModel : PageModel
{
private readonly IRestaurantData restaurantData;
private readonly IHtmlHelper htmlHelper;
[BindProperty]
public Restaurant Restaurant { get; set; }
public IEnumerable<SelectListItem> Cuisines { get; set; }
public EditModel(IRestaurantData restaurantData, IHtmlHelper htmlHelper)
{
this.restaurantData = restaurantData;
this.htmlHelper = htmlHelper;
}
/// <summary>
/// Den här funktionen kontrollerar att det finns en resturang som det resturangId som behandlas,
/// Om den restaurangen inte finns, så skickas användaren istället till sidan NotFound.
///
///Nu har den även stöd för att kontrollera om det skickas med ett id eller inte.
///Om det inte gör det, så skapas istället en ny resturang.
/// </summary>
/// <param name="restaurantId"></param>
/// <returns></returns>
public IActionResult OnGet(int? restaurantId)
{
Cuisines = htmlHelper.GetEnumSelectList<CuisineType>();
if (restaurantId.HasValue)
{
Restaurant = restaurantData.GetById(restaurantId.Value);
}
else
{
Restaurant = new Restaurant();
}
if (Restaurant == null)
{
return RedirectToPage("./NotFound");
}
return Page();
}
/// <summary>
/// Den här metoden kontrollerar om den information som
/// användaren fyller i på Edit sidan är korrekt.
/// Om den är det så redirectar den till den specifika resturangens detalj-sidan.
/// </summary>
/// <returns></returns>
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
Cuisines = htmlHelper.GetEnumSelectList<CuisineType>();
return Page();
}
if (Restaurant.Id > 0)
{
restaurantData.Update(Restaurant);
TempData["Message"] = Restaurant.Name + " updated!";
}
else
{
restaurantData.Add(Restaurant);
TempData["Message"] = Restaurant.Name + " saved!";
}
restaurantData.Commit();
return RedirectToPage("./Detail", new { restaurantId = Restaurant.Id });
}
}
} |
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 DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraNavBar;
using Model;
namespace AccManagerKw
{
public partial class Test : Form
{
public Test()
{
InitializeComponent();
}
private void Test_Shown(object sender, EventArgs e)
{
try
{
rcMenu.Pages.Clear();
FillMenu();
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
private void FillMenu()
{
using (var context = new AccManagerEntities())
{
var lst = context.MenuMasters.ToList();
foreach (var menu in lst.Where(x => x.ParentId == 0).OrderBy(x => x.MenuId))
{
rcMenu.Pages.Add(new RibbonPage(menu.MenuName) { Tag = menu.MenuId });
}
foreach (RibbonPage page in rcMenu.Pages)
{
if (page != null)
{
var subMenu = lst.Where(x => x.ParentId == Convert.ToInt64(page.Tag));
foreach (var menu in subMenu)
{
var index = page.Groups.Add(new RibbonPageGroup(menu.MenuName) { Tag = menu.MenuId });
foreach (var innerMenu in lst.Where(x => x.ParentId == menu.MenuId))
{
var bItem = page.Groups[index].ItemLinks.Add(new BarButtonItem()
{
Caption = innerMenu.MenuName,
Tag = innerMenu.MenuId
});
bItem.Item.ItemClick += OwnerItem_ItemClick;
}
}
}
else
{
Console.WriteLine("Group Is Null");
}
}
//foreach (var VARIABLE in COLLECTION)
//{
//}
}
}
void OwnerItem_ItemClick(object sender, ItemClickEventArgs e)
{
try
{
Console.WriteLine("MenuId -> {0}", e.Item.Tag.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Timers;
using System.Linq;
using Orleans;
using Orleans.Concurrency;
using Orleans.Providers;
using MWMROrleansInterfaces;
namespace MWMROrleansGrains
{
/// <summary>
/// Grain implementation class Grain1.
/// </summary>
[StorageProvider(ProviderName = "MemoryStore")]
public class StatefulGrain : Grain<StatefulGrainState>, MWMROrleansInterfaces.IStatefulGrain
{
public override async Task OnActivateAsync()
{
if (State.Prefs == null)
State.Prefs = new Dictionary<string, string>();
if (State.readers == null)
State.readers = new Dictionary<string, ConsistencyLevel>();
if (State.writers == null)
State.writers = new Dictionary<string, ConsistencyLevel>();
await base.OnActivateAsync();
}
public virtual Task SetState(GrainState state)
{
State.Prefs = (state as StatefulGrainState).Prefs;
State.currentContext = (state as StatefulGrainState).currentContext;
// Metadata grain should be doing this. This is not state for the grain to maintain
//State.readers = (state as StatefulGrainState).readers;
//State.writers = (state as StatefulGrainState).writers;
return TaskDone.Done;
}
public virtual Task<GrainState> GetState()
{
return Task.FromResult<GrainState>(State);
}
public virtual Task<string> GetValue(string key, Context cntxt)
{
throw new NotImplementedException();
}
public virtual Task<IDictionary<string, string>> GetAllEntries(Context cntxt)
{
throw new NotImplementedException();
}
public virtual Task<Context> SetValue(KeyValuePair<string, string> entry)
{
throw new NotImplementedException();
}
public virtual Task<Context> ClearValues()
{
throw new NotImplementedException();
}
public virtual Task RegisterReaderGrain(string key, ConsistencyLevel level)
{
if (State.readers.ContainsKey(key) == true)
{
throw new Exception();
}
State.readers.Add(key, level);
return TaskDone.Done;
}
public virtual Task DeregisterReaderGrain(string key)
{
if (State.readers.ContainsKey(key) == false)
{
throw new KeyNotFoundException();
}
State.readers.Remove(key);
return TaskDone.Done;
}
public virtual Task RegisterWriterGrain(string key, ConsistencyLevel level)
{
if (State.writers.ContainsKey(key) == true)
{
throw new Exception();
}
State.writers.Add(key, level);
return TaskDone.Done;
}
public virtual Task DeregisterWriterGrain(string key)
{
if (State.writers.ContainsKey(key) == false)
{
throw new KeyNotFoundException();
}
State.writers.Remove(key);
return TaskDone.Done;
}
}
[Serializable]
public class StatefulGrainState : GrainState
{
public IDictionary<string, string> Prefs { get; set; }
public Context currentContext;
public IDictionary<string, ConsistencyLevel> readers { get; set; }
public IDictionary<string, ConsistencyLevel> writers { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIResume : View
{
public override string M_Name
{
get
{
return Consts.V_Resume;
}
}
[SerializeField]
private Image m_imageCount;
public Sprite[] M_SpriteCount;
public void StartCount()
{
Show();
StartCoroutine(StartCountCoroutine());
}
IEnumerator StartCountCoroutine()
{
int i = 3;
while (i > 0)
{
m_imageCount.sprite = M_SpriteCount[i - 1];
i--;
yield return new WaitForSeconds(1);
if (i <= 0)
{
break;
}
}
Hide();
MVC.SendEvent(Consts.E_ContinueGameController);
}
public void Show()
{
gameObject.SetActive(true);
}
public void Hide()
{
gameObject.SetActive(false);
}
public override void RegisterAttentionEvent()
{
}
public override void HandleEvent(string name, object data)
{
}
}
|
using UnityEngine;
using UnityEngine.Events;
public class heroMoveInput : MonoBehaviour
{
public Rigidbody rb;
public UnityEvent MoveToRightStart;
public UnityEvent MoveToLefttStart;
public UnityEvent DeepColision;
public UnityEvent Dead;
public UnityEvent EndGame;
public float movingSpeed = 2;
public UnityEvent Idle;
private bool moving;
[SerializeField] private Animator animator;
public bool longFlight = false;
void Update()
{
animator.SetBool("moving", moving);
if (longFlight)
return;
if (Input.GetKey("a"))
{
rb.AddRelativeForce(Vector3.left * movingSpeed);
//rb.velocity = Vector3.left * movingSpeed;
MoveToLefttStart.Invoke();
moving = true;
}
if (Input.GetKey("d"))
{
rb.AddRelativeForce(Vector3.right * movingSpeed);
//rb.velocity = Vector3.right * movingSpeed;
MoveToRightStart.Invoke();
moving = true;
}
if (!Input.GetKey("d") && !Input.GetKey("a"))
{
moving = false;
Idle.Invoke();
}
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Finish")
{
DeepColision.Invoke();
Destroy(other.gameObject);
}
if (other.tag == "DamageZone")
{
longFlight = true;
Dead.Invoke();
animator.SetBool("dead", longFlight);
}
if (other.tag == "EndGame")
{
Debug.Log("donut");
EndGame.Invoke();
}
}
private void OnCollisionEnter(Collision other)
{
if (longFlight)
{
Dead.Invoke();
animator.SetBool("dead", longFlight);
}
}
public void LongFlight()
{
longFlight = true;
}
}
|
namespace TripDestination.Data.Models
{
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using TripDestination.Common.Infrastructure.Constants;
using Common.Models;
public class Car : BaseModel<int>
{
private ICollection<Photo> photos;
public Car()
{
this.TotalSeats = 5;
this.photos = new HashSet<Photo>();
this.SpaceForLugage = SpaceForLugage.None;
}
[Required]
[Range(ModelConstants.CarTotalSeatsMinLength, ModelConstants.CarTotalSeatsMaxLength, ErrorMessage = "Car total seat must be between 1 and 5.")]
public int TotalSeats { get; set; }
[Required]
[MinLength(ModelConstants.CarBrandMinLength, ErrorMessage = "Car brand can no be less than 3 symbols long.")]
[MaxLength(ModelConstants.CarBrandMaxLength, ErrorMessage = "Car brand can no be more than 50 symbols long.")]
public string Brand { get; set; }
[Required]
[MinLength(ModelConstants.CarModelMinLength, ErrorMessage = "Car model can no be less than 3 symbols long.")]
[MaxLength(ModelConstants.CarModelMaxLength, ErrorMessage = "Car model can no be more than 50 symbols long.")]
public string Model { get; set; }
[Required]
[MinLength(ModelConstants.CarColorMinLength, ErrorMessage = "Car color can no be less than 3 symbols long.")]
[MaxLength(ModelConstants.CarColorMaxLength, ErrorMessage = "Car color can no be more than 50 symbols long.")]
public string Color { get; set; }
[Range(ModelConstants.CarYearMinYear, ModelConstants.CarYearMaxYear, ErrorMessage = "Car year is not in range.")]
public int? Year { get; set; }
[Required]
public SpaceForLugage SpaceForLugage { get; set; }
[AllowHtml]
[MinLength(ModelConstants.CarDescriptionMinLength, ErrorMessage = "Car description can no be less than 20 symbols long.")]
[MaxLength(ModelConstants.CarDescriptionMaxLength, ErrorMessage = "Car description can no be more than 1000 symbols long.")]
public string Description { get; set; }
[Required]
public string OwnerId { get; set; }
public virtual User Owner { get; set; }
public virtual ICollection<Photo> Photos
{
get { return this.photos; }
set { this.photos = value; }
}
}
}
|
using EventLite;
namespace DocumentsApproval
{
public class AggregateSettings : IAggregateSettings
{
public int CommitsBeforeSnapshot { get; set; }
}
} |
using System.Data;
using System.Data.SqlClient;
namespace CapaDatos
{
public class DMedida
{
SqlConnection cn;
public DataTable SelectMedidas()
{
DataTable miTabla = new DataTable("1_medida");
SqlDataAdapter adapter;
using (cn = Conexion.ConexionDB())
{
SqlCommand cmd = new SqlCommand("SelectMedidas", cn)
{
CommandType = CommandType.StoredProcedure
};
adapter = new SqlDataAdapter(cmd);
adapter.Fill(miTabla);
}
cn.Close();
return miTabla;
}
public DataTable SelectCodAndNombreMedidaByCategoria(string categoria)
{
DataTable miTabla = new DataTable("1_medida");
SqlDataAdapter adapter;
using (cn = Conexion.ConexionDB())
{
SqlCommand cmd = new SqlCommand("SelectCodAndNombreMedidaByCategoria", cn)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("@categoria", categoria);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(miTabla);
}
cn.Close();
return miTabla;
}
public DataTable SelectMedidasByCodStock(int codStock)
{
DataTable miTabla = new DataTable("1_stock_medida");
SqlDataAdapter adapter;
using (cn = Conexion.ConexionDB())
{
SqlCommand cmd = new SqlCommand("SelectMEdidasByCodStock", cn)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("@cod_pro_stock", codStock);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(miTabla);
}
cn.Close();
return miTabla;
}
public string GetMedidaByCodMedida(int cod_med)
{
string resultado;
using (cn = Conexion.ConexionDB())
{
SqlCommand cmd = new SqlCommand("GetMedidaByCodMedida", cn)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("@cod_med", cod_med);
resultado = cmd.ExecuteScalar().ToString();
cn.Close();
}
return resultado;
}
public int GetCodMedidaByNombreMedida(string nombre)
{
int resultado;
using (cn = Conexion.ConexionDB())
{
SqlCommand cmd = new SqlCommand("GetCodMedidaByNombreMedida", cn)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("@nombre", nombre);
resultado = (int)cmd.ExecuteScalar();
cn.Close();
}
return resultado;
}
}
}
|
using System;
namespace SpeedInfo
{
class Program
{
static void Main(string[] args)
{
double speed = double.Parse(Console.ReadLine());
if(speed<=10)
{
Console.WriteLine("Slow");
}
else if(speed<=50)
{
Console.WriteLine("Average");
}
else if(speed<=150)
{
Console.WriteLine("fast");
}
else if(speed<=1000)
{
Console.WriteLine("ultra fast");
}
else if(speed>1000)
{
Console.WriteLine("extremely fast");
}
}
}
}
|
namespace BoatRacingSimulator.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Database;
using Enumerations;
using Exceptions;
using Interfaces;
using Models;
using Models.Boats;
using Models.Engines;
using Utility;
public class BoatSimulatorController : IBoatSimulatorController
{
public BoatSimulatorController(BoatSimulatorDatabase database, IRace currentRace)
{
this.Database = database;
this.CurrentRace = currentRace;
}
public BoatSimulatorController() : this(new BoatSimulatorDatabase(), null)
{
}
public IRace CurrentRace { get; private set; }
public BoatSimulatorDatabase Database { get; }
public string CreateBoatEngine(string model, int horsepower, int displacement, EngineType engineType)
{
IEngine engine = null;
switch (engineType)
{
case EngineType.Jet:
engine = new JetEngine(model, horsepower, displacement);
break;
case EngineType.Sterndrive:
engine = new SterndriveEngine(model, horsepower, displacement);
break;
}
this.Database.Engines.Add(engine);
return $"Engine model {model} with {horsepower} HP and displacement {displacement} cm3 created successfully.";
}
public string CreateRowBoat(string model, int weight, int oars)
{
IBoat boat = new RowBoat(model, weight, oars);
this.Database.Boats.Add(boat);
return $"Row boat with model {model} registered successfully.";
}
public string CreateSailBoat(string model, int weight, int sailEfficiency)
{
IBoat boat = new SailBoat(model, weight, sailEfficiency);
this.Database.Boats.Add(boat);
return $"Sail boat with model {model} registered successfully.";
}
public string CreatePowerBoat(string model, int weight, string firstEngineModel, string secondEngineModel)
{
IEngine firstEngine = this.Database.Engines.GetItem(firstEngineModel);
IEngine secondEngine = this.Database.Engines.GetItem(secondEngineModel);
IBoat boat = new PowerBoat(model, weight, firstEngine, secondEngine);
this.Database.Boats.Add(boat);
return $"Power boat with model {model} registered successfully.";
}
public string CreateYacht(string model, int weight, string engineModel, int cargoWeight)
{
var engine = this.Database.Engines.GetItem(engineModel) as Engine;
IBoat boat = new Yacht(model, weight, engine, cargoWeight);
this.Database.Boats.Add(boat);
return $"Yacht with model {model} registered successfully.";
}
public string OpenRace(int distance, int windSpeed, int oceanCurrentSpeed, bool allowsMotorboats)
{
IRace race = new Race(distance, windSpeed, oceanCurrentSpeed, allowsMotorboats);
this.ValidateRaceIsEmpty();
this.CurrentRace = race;
return $"A new race with distance {distance} meters, wind speed {windSpeed} m/s and ocean current speed {oceanCurrentSpeed} m/s has been set.";
}
public string SignUpBoat(string model)
{
var boat = this.Database.Boats.GetItem(model);
this.ValidateRaceIsSet();
if (!this.CurrentRace.AllowsMotorboats && boat.IsMotorBoat)
{
throw new ArgumentException(Constants.IncorrectBoatTypeMessage);
}
this.CurrentRace.AddParticipant(boat);
return $"Boat with model {model} has signed up for the current Race.";
}
public string StartRace()
{
this.ValidateRaceIsSet();
var participants = this.CurrentRace.GetParticipants();
if (participants.Count < 3)
{
throw new InsufficientContestantsException(Constants.InsufficientContestantsMessage);
}
var raceResults = new List<KeyValuePair<double, IBoat>>();
foreach (var participant in participants)
{
var speed = participant.CalculateRaceSpeed(this.CurrentRace);
if (speed <= 0)
{
raceResults.Add(new KeyValuePair<double, IBoat>(double.PositiveInfinity, participant));
}
else
{
var time = this.CurrentRace.Distance / speed;
raceResults.Add(new KeyValuePair<double, IBoat>(time, participant));
}
}
raceResults = raceResults.OrderBy(x => x.Key).ToList();
var first = raceResults[0];
var second = raceResults[1];
var third = raceResults[2];
var result = new StringBuilder();
result.AppendLine($"First place: {first.Value.GetType().Name} Model: {first.Value.Model} Time: {(double.IsInfinity(first.Key) ? "Did not finish!" : first.Key.ToString("0.00") + " sec")}");
result.AppendLine($"Second place: {second.Value.GetType().Name} Model: {second.Value.Model} Time: {(double.IsInfinity(second.Key) ? "Did not finish!" : second.Key.ToString("0.00") + " sec")}");
result.Append($"Third place: {third.Value.GetType().Name} Model: {third.Value.Model} Time: {(double.IsInfinity(third.Key) ? "Did not finish!" : third.Key.ToString("0.00") + " sec")}");
this.CurrentRace = null;
return result.ToString();
}
public string GetStatistic()
{
var builder = new StringBuilder();
var participants = this.CurrentRace.GetParticipants();
var boatTypeNames = Enum.GetNames(typeof(BoatType));
IDictionary<BoatType, int> countByBoatType = new Dictionary<BoatType, int>();
foreach (var boatType in boatTypeNames)
{
var type = (BoatType)Enum.Parse(typeof(BoatType), boatType);
countByBoatType[type] = this.GetCountByParticipantsBoatType(participants, type);
}
var allBoatCount = countByBoatType.Values.Sum();
var orderedBoats = countByBoatType.OrderBy(b => b.Key.ToString());
foreach (var boat in orderedBoats)
{
builder.AppendLine($"{boat.Key} -> {100 * ((double)boat.Value / allBoatCount):F2}%");
}
return builder.ToString().Trim();
}
private int GetCountByParticipantsBoatType(IEnumerable<IBoat> participants, BoatType boatType)
{
return participants.Count(p => p.BoatType == boatType);
}
private void ValidateRaceIsSet()
{
if (this.CurrentRace == null)
{
throw new NoSetRaceException(Constants.NoSetRaceMessage);
}
}
private void ValidateRaceIsEmpty()
{
if (this.CurrentRace != null)
{
throw new RaceAlreadyExistsException(Constants.RaceAlreadyExistsMessage);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using WindowsFormsApplication2;
public partial class zjdlright21 : System.Web.UI.Page
{
SqlConnection mycn;
string zjID;
string mycns = ConfigurationSettings.AppSettings["connString"];
protected void Page_Load(object sender, EventArgs e)
{
if (Session["zjuser"] == null)
{
Response.Write("<script>alert('账号已失效,请重新登录!');top.location.href = 'login.aspx';</script>");
return;
}
if (!Page.IsPostBack)
{
using (SqlConnection mycn = new SqlConnection(mycns))
{
using (SqlCommand sqlcmm = mycn.CreateCommand())
{
//专家ID
mycn.Open();
string IDs;
string users = Session["zjuser"].ToString();
string mycm1 = "select userID from User_Reg where username='" + users + "'";
SqlCommand mycmd1 = new SqlCommand(mycm1, mycn);
SqlDataReader myrd1;
myrd1 = mycmd1.ExecuteReader();
myrd1.Read();
IDs = myrd1[0].ToString();
myrd1.Close();
zjID = IDs;
sqlcmm.CommandText = "select * from nryqyxxk where ryzt != '在园' and ryzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "')";
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmm);
adapter.Fill(dt);
if (dt.Rows.Count > 0) //当数据库有数据的时候绑定数据
{
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
bindgrid();
}
else
{
img_nodigit.Visible = true;
}
mycn.Close();
}
}
}
}
void bindgrid()
{
//专家ID
SqlConnection mycn = new SqlConnection(mycns);
mycn.Open();
string IDs;
string users = Session["zjuser"].ToString();
string mycm1 = "select userID from User_Reg where username='" + users + "'";
SqlCommand mycmd1 = new SqlCommand(mycm1, mycn);
SqlDataReader myrd1;
myrd1 = mycmd1.ExecuteReader();
myrd1.Read();
IDs = myrd1[0].ToString();
myrd1.Close();
//查询数据库
DataSet ds = new DataSet();
using (SqlConnection sqlconn = new SqlConnection(mycns))
{
SqlDataAdapter sqld = new SqlDataAdapter("select qyID,qymc,qylx,sshy,zjshzt,zjshzt2,zjshzt3,spzjID,spzjID2,spzjID3 from nryqyxxk where ryzt != '在园' and ryzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "') order by ryzt", sqlconn);
sqld.Fill(ds, "tabenterprise");
}
//ds.Tables[0].Rows[0]["字段"]
foreach (DataRow row in ds.Tables[0].Rows)
{
//判断与那个专家几与此专家账号ID相同
bool t1=true, t2=true, t3=true;
//if (row[7].ToString() == zjID)
//{
// t1 = false;
//}
if (row[8].ToString() == zjID)
{
row[4] = row[5];
}
if (row[9].ToString() == zjID)
{
row[4] = row[6];
}
}
//排序,将未审核的放在上面
ds.Tables[0].DefaultView.Sort = "zjshzt DESC";
//为控件绑定数据
GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView;
GridView1.DataBind();
mycn.Close();
//countDropDownList();
}
protected void gridList_RowDataBound(object sender, GridViewRowEventArgs e)
{
string gridViewHeight = ConfigurationSettings.AppSettings["gridViewHeight"];
GridView1.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
//如果是绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//鼠标经过时,行背景色变
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#e5ebee'");
//鼠标移出时,行背景色变
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
// 控制每一行的高度
e.Row.Attributes.Add("style", gridViewHeight);
// 点击一行是复选框选中
CheckBox chk = (CheckBox)e.Row.FindControl("CheckBox1");
//e.Row.Attributes["onclick"] = "if(" + chk.ClientID + ".checked) " + chk.ClientID + ".checked = false ; else " + chk.ClientID + ".checked = true ;";
// 双击弹出新页面,并传递id值
int row_index = e.Row.RowIndex;
string ID = GridView1.DataKeys[row_index].Value.ToString();
e.Row.Attributes.Add("ondblclick", "newwin=window.open('zjdlright2.aspx?qyID=" + ID + "','newwin')");
// 未审核的行为红色
var drv = (DataRowView)e.Row.DataItem;
string status = drv["zjshzt"].ToString().Trim();
if (status.Trim() == "未审核")
{
e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;
}
}
}
protected void sshs(object sender, EventArgs e)
{
//专家ID
SqlConnection mycn = new SqlConnection(mycns);
mycn.Open();
string IDs;
string users = Session["zjuser"].ToString();
string mycm1 = "select userID from User_Reg where username='" + users + "'";
SqlCommand mycmd1 = new SqlCommand(mycm1, mycn);
SqlDataReader myrd1;
myrd1 = mycmd1.ExecuteReader();
myrd1.Read();
IDs = myrd1[0].ToString();
myrd1.Close();
//查询数据库
//string sqlconnstr = ConfigurationManager.ConnectionStrings["server=LAPTOP-JFN4NKUE;database=teaching;User ID=zl;pwd=123456;Trusted_Connection=no"].ConnectionString;
// Label1.Text = "查找成功";
DataSet ds = new DataSet();
//mycn.Open();
string userss = ss_text.Text.Trim().ToString();
String cxtj = DropDownList1.SelectedItem.Text;
if (cxtj == "企业名称")
{
cxtj = "qymc";
}
else if (cxtj == "企业类型")
{
cxtj = "qylx";
}
using (SqlConnection sqlconn = new SqlConnection(mycns))
{
SqlDataAdapter sqld = new SqlDataAdapter("select * from nryqyxxk where " + cxtj + " like '%" + userss + "%' and ryzt != '在园' and ryzt != '毕业' and tj = 1 and (spzjID = '" + IDs + "' or spzjID2 = '" + IDs + "' or spzjID3 = '" + IDs + "')", sqlconn);
sqld.Fill(ds, "tabenterprise");
mycn.Close();
}
//为控件绑定数据
GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindgrid(); //数据绑定
}
protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
{
// Retrieve the pager row.
GridViewRow pagerRow = GridView1.BottomPagerRow;
// Retrieve the PageDropDownList DropDownList from the bottom pager row.
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
// Set the PageIndex property to display that page selected by the user.
GridView1.PageIndex = pageList.SelectedIndex;
bindgrid(); //数据绑定
}
protected void GridView1_DataBound(Object sender, EventArgs e)
{
GridView1.BottomPagerRow.Visible = true;//只有一页数据的时候也再下面显示pagerrow,需要top的再加Top
// Retrieve the pager row.
GridViewRow pagerRow = GridView1.BottomPagerRow;
// Retrieve the DropDownList and Label controls from the row.
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (pageList != null)
{
// Create the values for the DropDownList control based on
// the total number of pages required to display the data
// source.
for (int i = 0; i < GridView1.PageCount; i++)
{
// Create a ListItem object to represent a page.
int pageNumber = i + 1;
ListItem item = new ListItem(pageNumber.ToString());
// If the ListItem object matches the currently selected
// page, flag the ListItem object as being selected. Because
// the DropDownList control is recreated each time the pager
// row gets created, this will persist the selected item in
// the DropDownList control.
if (i == GridView1.PageIndex)
{
item.Selected = true;
}
// Add the ListItem object to the Items collection of the
// DropDownList.
pageList.Items.Add(item);
}
}
if (pageLabel != null)
{
// Calculate the current page number.
int currentPage = GridView1.PageIndex + 1;
// Update the Label control with the current page information.
pageLabel.Text = "Page " + currentPage.ToString() +
" of " + GridView1.PageCount.ToString();
}
}
//protected void countDropDownList()
//{
// GridViewRow pagerRow = GridView1.BottomPagerRow;
// DropDownList countList = (DropDownList)pagerRow.Cells[0].FindControl("CountDropDownList");
// countList.Items.Add(new ListItem("默认"));
// countList.Items.Add(new ListItem("10"));
// countList.Items.Add(new ListItem("20"));
// countList.Items.Add(new ListItem("全部"));
// switch (GridView1.PageSize)
// {
// case 7:
// countList.Text = "默认";
// break;
// case 10:
// countList.Text = "10";
// break;
// case 20:
// countList.Text = "20";
// break;
// default:
// countList.Text = "全部";
// break;
// }
//}
protected void CountDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
{
GridViewRow pagerRow = GridView1.BottomPagerRow;
DropDownList countList = (DropDownList)pagerRow.Cells[0].FindControl("CountDropDownList");
string selectText = countList.SelectedItem.Text;
switch (selectText)
{
case "默认":
{
GridView1.PageSize = 7;
}
break;
case "10":
{
GridView1.PageSize = 10;
}
break;
case "20":
{
GridView1.PageSize = 20;
}
break;
case "全部":
{
mycn = new SqlConnection(mycns);
SqlCommand mycmm = new SqlCommand("select count(*) from nryqyxxk", mycn);
mycn.Open();
int count = (int)mycmm.ExecuteScalar();
mycn.Close();
GridView1.PageSize = count;
}
break;
default:
break;
}
bindgrid();
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace ElectronBlazorSpa.Shared
{
public class UsbLister
{
public static List<UsbDeviceInfo> GetUSBDevices()
{
List<UsbDeviceInfo> devices = new List<UsbDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new UsbDeviceInfo()
{
DeviceID = (string)device.GetPropertyValue("DeviceID"),
PnpDeviceID = (string)device.GetPropertyValue("PNPDeviceID"),
Description = (string)device.GetPropertyValue("Description")
});
}
collection.Dispose();
return devices;
}
}
}
|
namespace Draft_FF.Frontend.Entities
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Owner : CDbEntity
{
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
[MaxLength(50)]
public string TeamName { get; set; }
[Required]
[MaxLength(4)]
public string ShortName { get; set; }
public ICollection<Player> Players { get; set; }
[Required]
public int EspnId { get; set; }
public ICollection<DraftPickSlot> DraftPickSlots { get; set; }
public bool IsExpansionTeam { get; set; }
public int DraftRank { get; set; }
}
} |
using System;
using System.Collections.Generic;
using Alabo.Industry.Shop.Categories.Domain.Entities;
using Alabo.Industry.Shop.Products.Domain.Entities;
using Microsoft.AspNetCore.Http;
namespace Alabo.Industry.Shop.Products.Domain.Services
{
/// <summary>
/// ProductHelper 类为产品帮助工具类
/// </summary>
public static class ProductHelper
{
/// <summary>
/// 将现金价格转换为 积分,授信,虚拟货币等,如果不是以上类型不转换
/// </summary>
/// <param name="product"></param>
public static void PriceFromCash(this Product product)
{
//switch (product.PriceStyle)
//{
// case PriceStyle.PointProduct:
// case PriceStyle.CreditProduct:
// case PriceStyle.VirtualProduct:
// var psc =
// Alabo.Helpers.Ioc.Resolve<IAutoConfigService>()
// .GetList<PriceStyleConfig>()
// .FirstOrDefault(p => p.PriceStyle == product.PriceStyle);
// var mtc =
// Alabo.Helpers.Ioc.Resolve<IAutoConfigService>().GetList<MoneyTypeConfig>().First(p => p.Id == psc.MoneyTypeId);
// product.Price *= mtc.RateFee;
// break;
//}
}
/// <summary>
/// 将积分,授信,虚拟货币等 转换为现金,如果不是以上类型不转换
/// </summary>
/// <param name="product"></param>
public static void PriceToCash(this Product product)
{
//switch (product.PriceStyle)
//{
// case PriceStyle.PointProduct:
// case PriceStyle.CreditProduct:
// case PriceStyle.VirtualProduct:
// var psc =
// Alabo.Helpers.Ioc.Resolve<IAutoConfigService>()
// .GetList<PriceStyleConfig>()
// .FirstOrDefault(p => p.PriceStyle == product.PriceStyle);
// var mtc =
// Alabo.Helpers.Ioc.Resolve<IAutoConfigService>().GetList<MoneyTypeConfig>().First(p => p.Id == psc.MoneyTypeId);
// product.Price /= mtc.RateFee;
// break;
//}
}
#region 商品图片处理
/// <summary>
/// 商品属性处理
/// </summary>
/// <param name="product"></param>
/// <param name="request"></param>
/// <param name="category"></param>
public static Product HanderProperty(Product product, HttpRequest request,
Category category)
{
// product.ProductPropertys.AllPropertys = new List<PropertyItem>();
//foreach (var item in category.SalePropertys) {
// //var values = category.PropertyValues.Where(r => r.PropertyId == item.Id);
// //foreach (var temp in values) {
// // var value = request.Form["sale_" + temp.Id];
// // if (!value.IsNullOrEmpty()) {
// // var property = new PropertyItem {
// // ValueName = temp.ValueName,
// // PropertyGuid = item.Id
// // };
// // ;
// // property.PropertyValueGuid = temp.Id;
// // property.ValueAlias = temp.ValueAlias;//别名后期设置
// // property.IsSale = true;
// // product.ProductPropertys.AllPropertys.Add(property);
// // }
// //}
//}
//foreach (var item in category.DisplayPropertys) {
// //复选框多条记录
// if (item.ControlsType == ControlsType.CheckBox) {
// //var values = category.PropertyValues.Where(r => r.PropertyId == item.Id);
// //foreach (var temp in values) {
// // var value = request.Form["display_" + temp.Id];
// // if (!value.IsNullOrEmpty()) {
// // var property = new PropertyItem {
// // ValueName = temp.ValueName,
// // PropertyGuid = item.Id
// // };
// // ;
// // property.PropertyValueGuid = temp.Id;
// // property.IsSale = false;
// // property.ValueAlias = temp.ValueAlias;
// // product.ProductPropertys.AllPropertys.Add(property);
// // }
// }
// } else {
// //其他框一条记录
// var value = request.Form["display_" + item.Id];
// if (!value.IsNullOrEmpty()) {
// var property = new PropertyItem {
// ValueName = value,
// ValueAlias = value,
// PropertyGuid = item.Id,
// IsSale = false
// };
// product.ProductPropertys.AllPropertys.Add(property);
// }
// }
//}
//// product.PropertyJson = product.ProductPropertys.ToJson();
//return product;
return null;
}
/// <summary>
/// 商品属性处理
/// </summary>
/// <param name="product"></param>
/// <param name="saleProperties"></param>
/// <param name="displayProperties"></param>
/// <param name="category"></param>
public static void HanderProperty(Product product, List<Guid> saleProperties,
List<Guid> displayProperties, Category category)
{
//product.ProductPropertys.AllPropertys = new List<PropertyItem>();
//foreach (var item in category.SalePropertys) {
// var values = category.PropertyValues.Where(r => r.PropertyId == item.Id && saleProperties.Contains(r.Id));
// foreach (var temp in values) {
// var property = new PropertyItem {
// ValueName = temp.ValueName,
// PropertyGuid = item.Id
// };
// ;
// property.PropertyValueGuid = temp.Id;
// property.ValueAlias = temp.ValueAlias;//别名后期设置
// property.IsSale = true;
// product.ProductPropertys.AllPropertys.Add(property);
// }
//}
//foreach (var item in category.DisplayPropertys) {
// //复选框多条记录
// if (item.ControlsType == ControlsType.CheckBox) {
// var values = category.PropertyValues.Where(r => r.PropertyId == item.Id && displayProperties.Contains(r.Id));
// foreach (var temp in values) {
// var property = new PropertyItem {
// ValueName = temp.ValueName,
// PropertyGuid = item.Id
// };
// ;
// property.PropertyValueGuid = temp.Id;
// property.IsSale = false;
// property.ValueAlias = temp.ValueAlias;
// product.ProductPropertys.AllPropertys.Add(property);
// }
// } else {
// var value = displayProperties.Where(id => id.Equals(item.Id)).FirstOrDefault();
// if (!value.IsGuidNullOrEmpty()) {
// //其他框一条记录
// var property = new PropertyItem {
// ValueName = value.ToString(),
// ValueAlias = value.ToString(),
// PropertyGuid = item.Id,
// IsSale = false
// };
// product.ProductPropertys.AllPropertys.Add(property);
// }
// }
//}
//product.PropertyJson = product.ProductPropertys.ToJson();
// return null;
}
#endregion 商品图片处理
}
} |
using Alabo.Domains.Entities;
using System;
namespace Alabo.UI.Design.AutoLists {
/// <summary>
/// 自动列表接口
/// 对应移动端zk-list
/// </summary>
public interface IAutoList {
/// <summary>
/// 通用分页查询列表
/// </summary>
/// <param name="query"></param>
/// <param name="autoModel"></param>
/// <returns></returns>
PageResult<AutoListItem> PageList(object query, AutoBaseModel autoModel);
/// <summary>
/// 构建zk-list搜索和标签功能
/// 一般为数据库实体
/// </summary>
/// <returns></returns>
Type SearchType();
}
} |
using System;
using System.Collections.Generic;
using FluentAssertions;
using ILogging;
using Moq;
using NUnit.Framework;
using ServiceDeskSVC.Controllers.API;
using ServiceDeskSVC.Controllers.API.AssetManager;
using ServiceDeskSVC.DataAccess;
using ServiceDeskSVC.DataAccess.Models;
using ServiceDeskSVC.Domain.Entities.ViewModels.AssetManager;
using ServiceDeskSVC.Managers;
using ServiceDeskSVC.Managers.Managers;
namespace ServiceDeskSVC.Tests.Controllers
{
[TestFixture]
public class SoftwareTypeControllerTest
{
private SoftwareTypeController _SoftwareTypeController;
private Mock<IAssetManagerSoftwareAssetTypeRepository> _assetSoftwareTypeRepository;
private IAssetManagerSoftwareTypeManager _assetSoftwareTypeManager;
private Mock<ILogger> _logger;
[SetUp]
public void BeforeEach()
{
_assetSoftwareTypeRepository = new Mock<IAssetManagerSoftwareAssetTypeRepository>();
_logger = new Mock<ILogger>();
_assetSoftwareTypeManager = new AssetManagerSoftwareTypeManager(_assetSoftwareTypeRepository.Object, _logger.Object);
_SoftwareTypeController = new SoftwareTypeController(_assetSoftwareTypeManager, _logger.Object);
}
[Test]
public void TestEntities_ConfirmMapsIntoViewModel()
{
// Arrange
_assetSoftwareTypeRepository.Setup(x => x.GetAllSoftwareAssetTypes()).Returns(GetSoftwareTypeList);
// Act
var allSoftwareType = _SoftwareTypeController.Get();
var expectedResult = GetSoftwareTypeList_ResultForMappingToVM();
// Assert
Assert.IsNotNull(allSoftwareType, "Result is null");
allSoftwareType.ShouldBeEquivalentTo(expectedResult);
}
[Test]
public void TestAddingNewSoftwareType_DoesntReturnNull_ReturnsNewSoftwareTypeID()
{
// Arrange
_assetSoftwareTypeRepository.Setup(x => x.CreateSoftwareAssetTypes(It.IsAny<AssetManager_Software_AssetType>()))
.Returns(PostSoftwareType_ResultFromPostReturnInt());
// Act
var postTaskTypeID = _SoftwareTypeController.Post(PostSoftwareType());
// Assert
Assert.IsNotNull(postTaskTypeID, "Result is null");
postTaskTypeID.ShouldBeEquivalentTo(1);
}
[Test]
public void TestEditingSoftwareType_DoesntReturnNull_ReturnsSameTaskTypeID()
{
//Arrange
_assetSoftwareTypeRepository.Setup(
x => x.EditSoftwareAssetTypes(It.IsAny<int>(), It.IsAny<AssetManager_Software_AssetType>()))
.Returns(PutSoftwareType_ResultFromPutReturnInt());
//Act
var putSoftwareTypeID = _SoftwareTypeController.Put(1, PutSoftwareType());
//Assert
Assert.IsNotNull(putSoftwareTypeID, "Result is null");
putSoftwareTypeID.ShouldBeEquivalentTo(1);
}
[Test]
public void TestDeleteSoftwareType_ReturnedTrue()
{
//Arrange
_assetSoftwareTypeRepository.Setup(x => x.DeleteSoftwareAssetTypes(It.IsAny<int>())).Returns(true);
//Act
var isDeleted = _SoftwareTypeController.Delete(1);
//Assert
Assert.IsTrue(isDeleted);
}
private List<AssetManager_Software_AssetType> GetSoftwareTypeList()
{
var SoftwareTypeValues = new List<AssetManager_Software_AssetType>
{
new AssetManager_Software_AssetType
{
Id = 1,
Name = "Printers",
DescriptionNotes = "All printer deivces",
EndOfLifeMo = 24,
CategoryCode = 2
},
new AssetManager_Software_AssetType
{
Id = 2,
Name = "Laptops",
DescriptionNotes = "All laptop devices",
EndOfLifeMo = 36,
CategoryCode = 1,
}
};
return SoftwareTypeValues;
}
private List<AssetManager_SoftwareType_vm> GetSoftwareTypeList_ResultForMappingToVM()
{
var SoftwareTypeValues_Result = new List<AssetManager_SoftwareType_vm>
{
new AssetManager_SoftwareType_vm
{
Id = 1,
Name = "Printers",
DescriptionNotes = "All printer deivces",
EndOfLifeMo = 24,
CategoryCode = 2
},
new AssetManager_SoftwareType_vm
{
Id = 2,
Name = "Laptops",
DescriptionNotes = "All laptop devices",
EndOfLifeMo = 36,
CategoryCode = 1
}
};
return SoftwareTypeValues_Result;
}
private AssetManager_SoftwareType_vm PostSoftwareType()
{
return new AssetManager_SoftwareType_vm
{
Id = 3,
Name = "Phones",
DescriptionNotes = "All phones",
EndOfLifeMo = 36,
CategoryCode = 1
};
}
private int PostSoftwareType_ResultFromPostReturnInt()
{
return 1;
}
private AssetManager_SoftwareType_vm PutSoftwareType()
{
return new AssetManager_SoftwareType_vm
{
Id = 2,
Name = "Laptops and Notebooks",
DescriptionNotes = "All laptop devices",
EndOfLifeMo = 24,
CategoryCode = 1
};
}
private int PutSoftwareType_ResultFromPutReturnInt()
{
return 1;
}
}
}
|
using System;
namespace FamilyAccounting.BL.DTO
{
public class TransactionDTO
{
public int Id { get; set; }
public decimal Amount { get; set; }
public int SourceWalletId { get; set; }
public string SourceWallet { get; set; }
public int TargetWalletId { get; set; }
public string TargetWallet { get; set; }
public string Description { get; set; }
public DateTime TimeStamp { get; set; }
public int CategoryId { get; set; }
public string Category { get; set; }
public bool State { get; set; }
public TransactionTypeDTO TransactionType { get; set; }
public decimal BalanceBefore { get; set; }
public decimal BalanceAfter { get; set; }
}
}
|
using AutoMapper;
using MovieDbInf.Application.IServices;
using MovieDbInf.Application.Movie;
using MovieDbInf.Application.Movie.Dto;
using MovieDbInf.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using MovieDbInf.Application.Dto.Movie;
namespace MovieDbInf.Application.Services
{
public class MovieService : IMovieService
{
private readonly IMovieRepository _movieRepository;
private readonly IMapper _mapper;
public MovieService(IMovieRepository movieRepository, IMapper mapper)
{
_movieRepository = movieRepository;
_mapper = mapper;
}
public Task Add(MovieDto movieDto)
{
return _movieRepository.Add(_mapper.Map<MovieDbInf.Domain.Entities.Movie>(movieDto));
}
public Task Delete(Guid id)
{
throw new NotImplementedException();
}
public Task Update(Guid id, UpdateMovieDto movie)
{
throw new NotImplementedException();
}
public async Task<MovieDto> Get(Guid id)
{
var result = await _movieRepository.Get(id);
return _mapper.Map<MovieDto>(result);
}
public async Task<List<MovieDto>> GetAll()
{
var result = await _movieRepository.GetAll();
return _mapper.Map<List<MovieDto>>(result);
}
public Task Update(int id, UpdateMovieDto movie)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using IrsMonkeyApi.Models.DB;
using IrsMonkeyApi.Models.Dto;
using Microsoft.EntityFrameworkCore;
namespace IrsMonkeyApi.Models.DAL
{
public class FormSubmittedDal: IFormSubmittedDal
{
private readonly IRSMonkeyContext _context;
private readonly IMapper _mapper;
public FormSubmittedDal(IRSMonkeyContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public FormSubmittedDto SaveForm(FormSubmittedDto formSubmittedDto)
{
using (var transaction = _context.Database.BeginTransaction())
{
try
{
var formSubmitted = new FormSubmitted()
{
FormId = formSubmittedDto.FormId,
MemberId = formSubmittedDto.MemberId,
WizarStepId = formSubmittedDto.WizarStepId,
DateCreated = DateTime.Now
};
_context.FormSubmitted.Add(formSubmitted);
_context.SaveChanges();
foreach (var answer in formSubmittedDto.SubmittedAnswers)
{
answer.FormSubmittedId = formSubmitted.FormSubmittedId;
_context.FormSubmittedAnswer.Add(answer);
_context.SaveChanges();
}
transaction.Commit();
var formSaved = _mapper.Map<FormSubmittedDto>(formSubmitted);
return formSaved ?? null;
}
catch (Exception)
{
throw;
}
}
}
public List<FormSubmitted> GetForm(Guid memberId)
{
try
{
var memberForms = _context.FormSubmitted
.Where(mf => mf.MemberId == memberId)
.Include(sa => sa.FormSubmittedAnswer)
.ToList();
return memberForms.Any() ? memberForms : null;
}
catch (Exception)
{
throw;
}
}
public int GetFormPercentage(int WizardStep, int Wizard)
{
throw new NotImplementedException();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using FISCA.DSAUtil;
using DevComponents.DotNetBar;
using System.Xml;
using Aspose.Cells;
using System.IO;
using System.Diagnostics;
using SmartSchool.Common;
using Framework.Feature;
using K12.Data;
using SHSchool.Behavior.StudentExtendControls;
namespace SHSchool.Behavior.ClassExtendControls
{
public partial class AttendanceStatistic : UserControl, IDeXingExport
{
private string[] _classidList;
public AttendanceStatistic(string[] classidList)
{
InitializeComponent();
_classidList = classidList;
}
#region IDeXingExport 成員
public void LoadData()
{
DSResponse dsrsp = Config.GetAbsenceList();
DSXmlHelper helper = dsrsp.GetContent();
foreach (XmlElement e in helper.GetElements("Absence"))
{
string name = e.GetAttribute("Name");
int rowIndex = dataGridView.Rows.Add();
DataGridViewRow row = dataGridView.Rows[rowIndex];
row.Cells[1].Value = name;
}
}
public void Export()
{
dataGridView.EndEdit();
if (!IsValid())
{
MsgBox.Show("輸入資料有誤,請修正後再進行匯出!", "驗證錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
DSXmlHelper helper = new DSXmlHelper("Request");
helper.AddElement(".", "SchoolYear", School.DefaultSchoolYear);
helper.AddElement(".", "Semester", School.DefaultSemester);
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (!IsCheckedRow(row)) continue;
XmlElement e = helper.AddElement("Absence");
e.SetAttribute("Name", row.Cells[1].Value.ToString());
e.SetAttribute("PeriodCount", row.Cells[2].Value.ToString());
}
foreach (string id in _classidList)
{
helper.AddElement(".", "ClassID", id);
}
DSResponse dsrsp = QueryAttendance.GetAttendanceStatistic(new DSRequest(helper));
if (!dsrsp.HasContent)
{
MsgBox.Show("取得回覆資料失敗:" + dsrsp.GetFault().Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DSXmlHelper rsp = dsrsp.GetContent();
Workbook book = new Workbook();
string A1Name = string.Empty;
book.Worksheets.Clear();
foreach (XmlElement e in rsp.GetElements("Absence"))
{
int sheetIndex = book.Worksheets.Add();
Worksheet sheet = book.Worksheets[sheetIndex];
sheet.Name = e.GetAttribute("Type");
string schoolName = School.ChineseName;
Cell A1 = sheet.Cells["A1"];
A1.Style.Borders.SetColor(Color.Black);
A1Name = "扣分累計學生清單(" + e.GetAttribute("Type") + ")";
A1.PutValue(A1Name);
A1.Style.HorizontalAlignment = TextAlignmentType.Center;
sheet.Cells.Merge(0, 0, 1, 5);
FormatCell(sheet.Cells["A2"], "班級");
FormatCell(sheet.Cells["B2"], "座號");
FormatCell(sheet.Cells["C2"], "姓名");
FormatCell(sheet.Cells["D2"], "學號");
FormatCell(sheet.Cells["E2"], "累積節次");
//FormatCell(sheet.Cells["F2"], "累積扣分");
int index = 3;
foreach (XmlElement s in e.SelectNodes("Student"))
{
FormatCell(sheet.Cells["A" + index], s.GetAttribute("ClassName"));
FormatCell(sheet.Cells["B" + index], s.GetAttribute("SeatNo"));
FormatCell(sheet.Cells["C" + index], s.GetAttribute("Name"));
FormatCell(sheet.Cells["D" + index], s.GetAttribute("StudentNumber"));
FormatCell(sheet.Cells["E" + index], s.GetAttribute("PeriodCount"));
//FormatCell(sheet.Cells["F" + index], s.GetAttribute("Subtract"));
index++;
}
}
string path = Path.Combine(Application.StartupPath, "Reports");
//如果目錄不存在則建立。
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
path = Path.Combine(path, "缺曠累計名單" + ".xls");
int i = 1;
while (true)
{
string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
if (!File.Exists(newPath))
{
path = newPath;
break;
}
}
try
{
book.Save(path);
}
catch (IOException)
{
try
{
FileInfo file = new FileInfo(path);
string nameTempalte = file.FullName.Replace(file.Extension, "") + "{0}.xls";
int count = 1;
string fileName = string.Format(nameTempalte, count);
while (File.Exists(fileName))
fileName = string.Format(nameTempalte, count++);
book.Save(fileName);
path = fileName;
}
catch (Exception ex)
{
MsgBox.Show("檔案儲存失敗:" + ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (Exception ex)
{
MsgBox.Show("檔案儲存失敗:" + ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
Process.Start(path);
}
catch (Exception ex)
{
MsgBox.Show("檔案開啟失敗:" + ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
public Control MainControl
{
get { return this.groupPanel1; }
}
private string ConvertToValidName(string A1Name)
{
char[] invalids = Path.GetInvalidFileNameChars();
string result = A1Name;
foreach (char each in invalids)
result = result.Replace(each, '_');
return result;
}
private void FormatCell(Cell cell, string value)
{
cell.PutValue(value);
cell.Style.Borders.SetStyle(CellBorderType.Hair);
cell.Style.Borders.SetColor(Color.Black);
cell.Style.Borders.DiagonalStyle = CellBorderType.None;
cell.Style.HorizontalAlignment = TextAlignmentType.Center;
}
private bool IsCheckedRow(DataGridViewRow row)
{
if (row.Cells[0].Value == null)
return false;
string value = row.Cells[0].Value.ToString();
bool check = false;
if (!bool.TryParse(value, out check))
return false;
return check;
}
#endregion
//private void dataGridView_RowValidated(object sender, DataGridViewCellEventArgs e)
//{
//}
private bool IsValid()
{
errorProvider1.Clear();
bool valid = true;
int count = 0;
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (IsCheckedRow(row))
{
if (row.Cells[2].ErrorText == string.Empty)
count++;
else
valid = false;
}
}
if (count == 0)
{
errorProvider1.SetError(dataGridView, "至少必須選擇一個缺曠類別");
return false;
}
return valid;
}
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow row = dataGridView.Rows[e.RowIndex];
//DataGridViewCheckBoxCell cell = row.Cells[0] as DataGridViewCheckBoxCell;
//if (cell.Value == null)
// return;
DataGridViewCell c = row.Cells[2];
c.ErrorText = string.Empty;
string value = c.Value == null ? "0" : c.Value.ToString();
decimal subtract = 0;
if (!decimal.TryParse(value, out subtract))
{
row.Cells[2].ErrorText = "必須為數字";
return;
}
c.Value = subtract;
row.Cells[2].ErrorText = string.Empty;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
StatisticWeightConfig config = new StatisticWeightConfig();
config.ShowDialog();
}
}
}
|
using MusicMatchMVC.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Mvc;
using System.Threading.Tasks;
namespace MusicMatchMVC.Controllers
{
public class ArtistAPIController : ApiController
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Configuration;
using System.Timers;
namespace TaskService
{
public partial class TaskService : ServiceBase
{
Logger log = Logger.GetLogger(typeof(TaskService));
public TaskService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
log.Warn("开始任务" + DateTime.Now.ToString());
UpdataTask();
}
protected override void OnStop()
{
log.Warn("结束任务" + DateTime.Now.ToString());
}
public void UpdataTask()
{
log.Warn("开始工作" + DateTime.Now.ToString());
using (TaskDataContext db = new TaskDataContext(ConfigurationSettings.AppSettings["DBCon"]))
{
List<WFTask> items = db.WFTasks.Where(p => p.Status == "审批中" && p.ApproveType == "初步评审" && DateTime.Compare( DateTime.Now,Convert.ToDateTime(p.LastModifirfDate)) > 0).ToList();
foreach (WFTask item in items)
{
item.Status = "完成";
item.CompletedDate = DateTime.Now.ToString();
db.SubmitChanges();
bool istrue = true;
List<WFTask> tasklist = GetWFTasksByStep(item.WorkflowId, item.Step);
foreach (WFTask task in tasklist)
{
if (task.Status == "审批中")
{
istrue = false;
}
}
if (istrue)
{
WFInst inst = db.WFInsts.Where(p => p.Id == Convert.ToInt32(item.WFinstId)).FirstOrDefault();
int step = int.Parse(item.Step);
WorkflowScenario node = GetWFNode(item.WorkflowId, step.ToString());
inst.Name = node.Name;
inst.Status = "审批中";
inst.Step = step.ToString();
db.SubmitChanges();
WFTask newtask = new WFTask();
newtask.FileId = item.FileId;
newtask.WorkflowId = inst.WorkflowId;
newtask.WorkflowName = inst.WorkflowName;
newtask.Step = step.ToString();
newtask.AssigedDate = DateTime.Now.ToString();
newtask.Name = node.Name;
newtask.Status = "审批中";
newtask.WFinstId = item.WFinstId;
newtask.ApproveType = "编辑人";
newtask.ApplicantAD = inst.ApplicantAD;
newtask.ApproverAD = inst.ApplicantAD;
db.WFTasks.InsertOnSubmit(newtask);
db.SubmitChanges();
}
}
}
}
/// <summary>
///获取流程某步的所有任务
/// </summary>
/// <param name="workflowid"></param>
/// <param name="step"></param>
/// <param name="fileid"></param>
/// <param name="borrowid"></param>
/// <returns></returns>
public List<WFTask> GetWFTasksByStep(string workflowid, string step)
{
using (TaskDataContext db = new TaskDataContext(ConfigurationSettings.AppSettings["DBCon"]))
{
List<WFTask> items = db.WFTasks.Where(p => p.WorkflowId == workflowid && p.Step == step).ToList();
return items;
}
}
/// <summary>
/// 获取流程节点
/// </summary>
/// <param name="workflowid"></param>
/// <param name="step"></param>
/// <returns></returns>
public WorkflowScenario GetWFNode(string workflowid, string step)
{
using (TaskDataContext db = new TaskDataContext(ConfigurationSettings.AppSettings["DBCon"]))
{
WorkflowScenario item = db.WorkflowScenarios.Where(p => p.WorkflowId == workflowid && p.Step == step).FirstOrDefault();
return item;
}
}
/// <summary>
/// 根据流程编号获取流程节点数
/// </summary>
/// <param name="workflowid">流程编号</param>
/// <returns></returns>
public int GetWFNodeCount(string workflowid)
{
using (TaskDataContext db = new TaskDataContext(ConfigurationSettings.AppSettings["DBCon"]))
{
List<WorkflowScenario> items = db.WorkflowScenarios.Where(p => p.WorkflowId == workflowid).ToList();
return items.Count;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class TeacherSkillsEnum : MonoBehaviour
{
GameManager gamemanager;
PlayerLog eventLog;
//Modified to be able to compare test..
//public string randomSkil0, randomSkil1, randomSkil2;
public teacherSkills randomSkill0;
public teacherSkills randomSkill1;
public teacherSkills randomSkill2;
[SerializeField] private int cEfficiency;
[SerializeField] private int gEfficiency;
[SerializeField] private int rEfficiency;
[SerializeField] private int lEfficiency;
public int CEfficiency
{
get { return cEfficiency; }
set { cEfficiency = Mathf.Clamp(value, 10, 30); }
}
public int GEfficiency
{
get { return gEfficiency; }
set { gEfficiency = Mathf.Clamp(value, 30, 55); }
}
public int REfficiency
{
get { return rEfficiency; }
set { rEfficiency = Mathf.Clamp(value, 55, 80); }
}
public int LEfficiency
{
get { return lEfficiency; }
set { lEfficiency = Mathf.Clamp(value, 70, 100); }
}
public void randomSkillGen()
{
randomSkill0 = (teacherSkills)Random.Range(0, 4);
randomSkill1 = (teacherSkills)Random.Range(0, 4);
randomSkill2 = (teacherSkills)Random.Range(0, 4);
}
public void commonTeacher()
{
if (gameObject.tag == "Common")
{
eventLog.AddEvent("You hired a Common teacher!");
randomSkill0 = (teacherSkills)Random.Range(1, 4);
CEfficiency = Random.Range(0, 50);
switch (randomSkill0)
{
case teacherSkills.AxeTrowing:
Debug.Log("Axe Thrower, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Axe Thrower, efficiency of " + CEfficiency + "%");
break;
case teacherSkills.Surfing:
Debug.Log("Surfer, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + CEfficiency + "%");
break;
case teacherSkills.Magic:
Debug.Log("Magic, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Magic, efficiency of " + CEfficiency + "%");
break;
case teacherSkills.Haking:
Debug.Log("Surfer, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + CEfficiency + "%");
break;
default:
Debug.Log("None");
eventLog.AddEvent("None");
break;
}
}
}
public void GreatTeacher()
{
if (gameObject.tag == "Great")
{
eventLog.AddEvent("You hired a Great teacher!");
randomSkill0 = (teacherSkills)Random.Range(1, 4);
GEfficiency = Random.Range(30, 70);
switch (randomSkill0)
{
case teacherSkills.AxeTrowing:
Debug.Log("Axe Thrower, efficiency of " + GEfficiency + "%");
eventLog.AddEvent("Axe Thrower, efficiency of " + GEfficiency + "%");
break;
case teacherSkills.Surfing:
Debug.Log("Surfer, efficiency of " + GEfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + GEfficiency + "%");
break;
case teacherSkills.Magic:
Debug.Log("Magic, efficiency of " + GEfficiency + "%");
eventLog.AddEvent("Magic, efficiency of " + GEfficiency + "%");
break;
case teacherSkills.Haking:
Debug.Log("Haking, efficiency of " + GEfficiency + "%");
eventLog.AddEvent("Haking, efficiency of " + GEfficiency + "%");
break;
default:
Debug.Log("None");
eventLog.AddEvent("None");
break;
}
}
}
public void rareTeacher()
{
if (gameObject.tag == "Rare")
{
eventLog.AddEvent("You hired a Rare teacher!");
randomSkill0 = (teacherSkills)Random.Range(1, 2);
randomSkill1 = (teacherSkills)Random.Range(3, 4);
CEfficiency = Random.Range(0, 50);
REfficiency = Random.Range(0, 90);
switch (randomSkill0)
{
case teacherSkills.AxeTrowing:
Debug.Log("Axe Thrower, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Axe Thrower, efficiency of " + CEfficiency + "%");
break;
case teacherSkills.Surfing:
Debug.Log("Surfer, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + CEfficiency + "%");
break;
case teacherSkills.Magic:
Debug.Log("Magic, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Magic, efficiency of " + CEfficiency + "%");
break;
case teacherSkills.Haking:
Debug.Log("Surfer, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + CEfficiency + "%");
break;
default:
Debug.Log("None");
eventLog.AddEvent("None");
break;
}
switch (randomSkill1)
{
case teacherSkills.AxeTrowing:
Debug.Log("Axe Thrower, efficiency of " + REfficiency + "%");
eventLog.AddEvent("Axe Thrower, efficiency of " + REfficiency + "%");
break;
case teacherSkills.Surfing:
Debug.Log("Surfer, efficiency of " + REfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + REfficiency + "%");
break;
case teacherSkills.Magic:
Debug.Log("Magic, efficiency of " + REfficiency + "%");
eventLog.AddEvent("Magic, efficiency of " + REfficiency + "%");
break;
case teacherSkills.Haking:
Debug.Log("Surfer, efficiency of " + REfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + REfficiency + "%");
break;
default:
Debug.Log("None");
eventLog.AddEvent("None");
break;
}
}
}
public void legendaryTeacher()
{
if (gameObject.tag == "Legendary")
{
eventLog.AddEvent("You hired a Legandary teacher!");
randomSkill0 = (teacherSkills)Random.Range(1, 1);
randomSkill1 = (teacherSkills)Random.Range(2, 2);
randomSkill2 = (teacherSkills)Random.Range(3, 4);
CEfficiency = Random.Range(0, 50);
REfficiency = Random.Range(0, 90);
LEfficiency = Random.Range(0, 100);
switch (randomSkill0)
{
case teacherSkills.AxeTrowing:
Debug.Log("Axe Thrower, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Axe Thrower, efficiency of " + CEfficiency + "%");
break;
case teacherSkills.Surfing:
Debug.Log("Surfer, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + CEfficiency + "%");
break;
case teacherSkills.Magic:
Debug.Log("Magic, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Magic, efficiency of " + CEfficiency + "%");
break;
case teacherSkills.Haking:
Debug.Log("Surfer, efficiency of " + CEfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + CEfficiency + "%");
break;
default:
Debug.Log("None");
eventLog.AddEvent("None");
break;
}
switch (randomSkill1)
{
case teacherSkills.AxeTrowing:
Debug.Log("Axe Thrower, efficiency of " + REfficiency + "%");
eventLog.AddEvent("Axe Thrower, efficiency of " + REfficiency + "%");
break;
case teacherSkills.Surfing:
Debug.Log("Surfer, efficiency of " + REfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + REfficiency + "%");
break;
case teacherSkills.Magic:
Debug.Log("Magic, efficiency of " + REfficiency + "%");
eventLog.AddEvent("Magic, efficiency of " + REfficiency + "%");
break;
case teacherSkills.Haking:
Debug.Log("Surfer, efficiency of " + REfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + REfficiency + "%");
break;
default:
Debug.Log("None");
eventLog.AddEvent("None");
break;
}
switch (randomSkill2)
{
case teacherSkills.AxeTrowing:
Debug.Log("Axe Thrower, efficiency of " + LEfficiency + "%");
eventLog.AddEvent("Axe Thrower, efficiency of " + LEfficiency + "%");
break;
case teacherSkills.Surfing:
Debug.Log("Surfer, efficiency of " + LEfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + LEfficiency + "%");
break;
case teacherSkills.Magic:
Debug.Log("Magic, efficiency of " + LEfficiency + "%");
eventLog.AddEvent("Magic, efficiency of " + LEfficiency + "%");
break;
case teacherSkills.Haking:
Debug.Log("Surfer, efficiency of " + LEfficiency + "%");
eventLog.AddEvent("Surfer, efficiency of " + LEfficiency + "%");
break;
default:
Debug.Log("None");
eventLog.AddEvent("None");
break;
}
}
}
// Start is called before the first frame update
void Start()
{
gamemanager = GameManager.instance;
eventLog = PlayerLog.instance;
commonTeacher();
GreatTeacher();
rareTeacher();
legendaryTeacher();
}
// Update is called once per frame
void Update()
{
}
}
public enum teacherSkills
{
none,
AxeTrowing,
Surfing,
Magic,
Haking
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System;
using UnityEngine.UI;
public class MainMenuSys : MonoBehaviour
{
public GameObject Btns;
public static MainMenuSys instance;
public GameObject Image_newestLevelNoteObj;
private void Awake()
{
instance = this;
}
// Start is called before the first frame update
void Start()
{
var t = GameRoot.instance.playerModel.equipmentList.ToList();
//foreach (var item in GameRoot.instance.playerModel.LevelStartDic)
//{
// Debug.Log(item.Key+" "+item.Value+"最大关卡");
//}
try
{
GameObject.Find("Image_Adventy").GetComponent<Animator>().Play("Selected");
GameObject.Find("Image_illustrated").GetComponent<Animator>().Play("Normal");
GameObject.Find("Image_Eqp").GetComponent<Animator>().Play("Normal");
GameObject.Find("Image_Chara").GetComponent<Animator>().Play("Normal");
}
catch
{
Debug.Log("bottomBtnsError");
}
SetBGM();
//1
//ShowBtnImages();
//SetNewestLevelNote();
//1
}
private void SetNewestLevelNote()
{
var btnNewestLevel = GameObject.Find(GameRoot.instance.playerModel.UnlockLevelList[GameRoot.instance.playerModel.UnlockLevelList.Count - 1].ToString());
Image_newestLevelNoteObj.transform.position = btnNewestLevel.transform.position+(new Vector3(0,130,0) * (576f / Screen.width));
btnNewestLevel.transform.localScale = new Vector3(1, 1, 1) * (576f / Screen.width);
Debug.Log("最新关卡:" + GameRoot.instance.playerModel.UnlockLevelList[GameRoot.instance.playerModel.UnlockLevelList.Count - 1]);
//throw new NotImplementedException();
}
private void SetBGM()
{
MusicMgr.GetInstance().PlayBkMusic("mainMenu");
MusicMgr.GetInstance().ChangeBKValue(0.6f);
//throw new NotImplementedException();
}
private void ShowBtnImages()
{
for (int i = 0; i < Btns.transform.childCount; i++)
{
StartCoroutine(IEShowBtnImages(i*0.1f,i));
}
}
IEnumerator IEShowBtnImages(float t,int index)
{
yield return new WaitForSeconds(t);//运行到这,暂停t秒
//t秒后,继续运行下面代码
var tempObj = ResMgr.GetInstance().Load<GameObject>("UI/UIAnimator/MainMenu/BtnStar");
tempObj.transform.SetParent(Btns.transform.GetChild(index));
tempObj.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0);
tempObj.transform.localScale = new Vector3(1, 1, 1) * (576f / Screen.width);
int star = PlayerModelController.GetInstance().GetLevelStarDic(Btns.transform.GetChild(index).name);
tempObj.GetComponent<BtnStar>().Init(star);
//print("Time over.");
}
// Update is called once per frame
void Update()
{
}
}
|
using System.Threading.Tasks;
using Lussatite.FeatureManagement.SessionManagers.SqlClient;
using RimDev.AspNetCore.FeatureFlags.Tests.Testing;
using RimDev.AspNetCore.FeatureFlags.Tests.Testing.Database;
using Xunit;
namespace RimDev.AspNetCore.FeatureFlags.Tests
{
[Collection(nameof(EmptyDatabaseCollection))]
public class FeatureFlagsSessionManagerTests
{
private readonly EmptyDatabaseFixture databaseFixture;
public FeatureFlagsSessionManagerTests(
EmptyDatabaseFixture databaseFixture
)
{
this.databaseFixture = databaseFixture;
}
private async Task<FeatureFlagsSessionManager> CreateSut()
{
var sqlSessionManagerSettings = new SQLServerSessionManagerSettings
{
ConnectionString = databaseFixture.ConnectionString
};
var featureFlagsSettings = new FeatureFlagsSettings(
featureFlagAssemblies: new[] { typeof(FeatureFlagsSessionManagerTests).Assembly }
)
{
ConnectionString = databaseFixture.ConnectionString,
InitializationConnectionString = databaseFixture.ConnectionString,
SqlSessionManagerSettings = sqlSessionManagerSettings,
};
var sut = new FeatureFlagsSessionManager(
featureFlagsSettings: featureFlagsSettings
);
await sqlSessionManagerSettings.CreateDatabaseTableAsync(
featureFlagsSettings.InitializationConnectionString
);
return sut;
}
[Fact]
public async Task Can_create_sut()
{
var sut = await CreateSut();
Assert.NotNull(sut);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SetAsync_returns_expected(bool expected)
{
var sut = await CreateSut();
const string baseFeatureName = "RDANCFF_SetAsync_";
var featureName = $"{baseFeatureName}{expected}";
await sut.SetAsync(featureName, expected);
var result = await sut.GetAsync(featureName);
Assert.Equal(expected, result);
}
[Theory]
[InlineData(null)]
[InlineData(false)]
[InlineData(true)]
public async Task SetNullableAsync_returns_expected(bool? expected)
{
var sut = await CreateSut();
const string baseFeatureName = "RDANCFF_SetNullableAsync_";
var expectedName = expected.HasValue ? expected.ToString() : "Null";
var featureName = $"{baseFeatureName}{expectedName}";
await sut.SetNullableAsync(featureName, expected);
var result = await sut.GetAsync(featureName);
Assert.Equal(expected, result);
}
/// <summary>Exercise the SetAsync method a bunch of times to ensure there are no latent
/// bugs with race conditions, values not being set properly, etc.</summary>
[Fact]
public async Task Exercise_SetAsync()
{
var sut = await CreateSut();
const int iterations = 8000;
const string baseFeatureName = "RDANCFF_SetAsync_Exercise_";
for (var i = 0; i < iterations; i++)
{
var doUpdate = Rng.GetInt(0, 25) == 0; // only call SetAsync() some of the time
var featureName = $"{baseFeatureName}{Rng.GetInt(0, 10)}";
var enabled = Rng.GetBool();
if (doUpdate) await sut.SetAsync(featureName, enabled);
var result = await sut.GetAsync(featureName);
if (doUpdate) Assert.Equal(enabled, result);
}
}
/// <summary>Exercise the SetNullableAsync method a bunch of times to ensure there are no latent
/// bugs with race conditions, values not being set properly, etc.</summary>
[Fact]
public async Task Exercise_SetNullableAsync()
{
var sut = await CreateSut();
const int iterations = 8000;
const string baseFeatureName = "RDANCFF_SetNullableAsync_Exercise_";
for (var i = 0; i < iterations; i++)
{
var doUpdate = Rng.GetInt(0, 25) == 0; // only call SetNullableAsync() some of the time
var featureName = $"{baseFeatureName}{Rng.GetInt(0, 10)}";
var enabled = Rng.GetNullableBool();
if (doUpdate) await sut.SetNullableAsync(featureName, enabled);
var result = await sut.GetAsync(featureName);
if (doUpdate) Assert.Equal(enabled, result);
}
}
}
}
|
using Nailhang.Display.Tools.TextSearch.Base;
using Nailhang.Display.Tools.TextSearch.Processing;
using Ninject.Modules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Nailhang.Display.Tools.TextSearch
{
public class Module : NinjectModule
{
public override void Load()
{
Kernel.Bind<IWSBuilder>().To<StatBuilder>();
}
}
}
|
using Contracts.Conforming;
using Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Clients.Conforming
{
public class ConformingProxy : ClientBase<IConformingService>, IConformingService
{
#region Constructors
public ConformingProxy(ServiceEndpoint endpoint)
: base(endpoint)
{ }
#endregion
#region Public Methods
public bool AddAirMasterRecord(TrackB data)
{
return Channel.AddAirMasterRecord(data);
}
public bool AddAMHistory(TrackBHistory data)
{
return Channel.AddAMHistory(data);
}
public bool AddConformingHistory(MovieConformHistory data)
{
return Channel.AddConformingHistory(data);
}
public bool AddConformingStructureHistory(ConformingStructureHistoryQC data)
{
return Channel.AddConformingStructureHistory(data);
}
public bool AddConformingStructureNotesHistory(ConformingStructureHistoryNotes data)
{
return Channel.AddConformingStructureNotesHistory(data);
}
public bool AddConformingStructureRuntimeHistory(ConformingStructureHistoryRuntimes data)
{
return Channel.AddConformingStructureRuntimeHistory(data);
}
public bool AddFCPHistory(TrackSHistory data)
{
return Channel.AddFCPHistory(data);
}
public bool AddProjectCompleteHistory(ConformingProjectCompleteHistory data)
{
return Channel.AddProjectCompleteHistory(data);
}
public bool AddProjectCompleteNotesHistory(ConformingProjectCompleteHistoryNotes data)
{
return Channel.AddProjectCompleteNotesHistory(data);
}
public bool AddUpdateConformFeatures(MovieConformFeatures data, bool isNew)
{
return Channel.AddUpdateConformFeatures(data, isNew);
}
public bool AddUpdateConformingNotes(int id, string userName, string notes)
{
return Channel.AddUpdateConformingNotes(id, userName, notes);
}
public bool AddUpdateConformingOrderNum(ConformingLoadOrderNum data, bool isNew)
{
return Channel.AddUpdateConformingOrderNum(data, isNew);
}
public bool AddUpdateConformingRecord(MovieConform data, bool isNew)
{
return Channel.AddUpdateConformingRecord(data, isNew);
}
public bool AddUpdateConformingStructure(ConformingStructure data, bool isNew)
{
return Channel.AddUpdateConformingStructure(data, isNew);
}
public bool AddUpdateFCPRecord(TrackS data, bool isNew)
{
return Channel.AddUpdateFCPRecord(data, isNew);
}
public bool AddUpdateMSRecord(TrafficInternet data, bool isNew)
{
return Channel.AddUpdateMSRecord(data, isNew);
}
public bool AddUpdateMSRecordById(int id, string userName)
{
return Channel.AddUpdateMSRecordById(id, userName);
}
public bool AddUpdateProjectComplete(ConformingProjectComplete data, bool isNew)
{
return Channel.AddUpdateProjectComplete(data, isNew);
}
public bool AddUpdateReportRecord(ConformingEmployeeStatsRport data, bool isNew)
{
return Channel.AddUpdateReportRecord(data, isNew);
}
public bool CanFrameSizeBeSelected(string format)
{
return Channel.CanFrameSizeBeSelected(format);
}
public bool CheckProjectComplete(int id)
{
return Channel.CheckProjectComplete(id);
}
public void CreateConformingMethods(string connectionString, string userName)
{
Channel.CreateConformingMethods(connectionString, userName);
}
public bool DeleteReportRecord(int id)
{
return Channel.DeleteReportRecord(id);
}
public TrackB GetAirMaster(int id)
{
return Channel.GetAirMaster(id);
}
public string GetAirMasterLocation(int id)
{
return Channel.GetAirMasterLocation(id);
}
public Tuple<string, DateTime?> GetAirMasterQCInfo(int id)
{
return Channel.GetAirMasterQCInfo(id);
}
public Tuple<string, string, int> GetAirMasterStatus(int id)
{
return Channel.GetAirMasterStatus(id);
}
public int GetAltHDId(int id)
{
return Channel.GetAltHDId(id);
}
public int GetAltSDId(int id)
{
return Channel.GetAltSDId(id);
}
public List<string> GetAspectRatios()
{
return Channel.GetAspectRatios();
}
public string GetAssetType(int id)
{
return Channel.GetAssetType(id);
}
public string GetClipboardUserName(int id)
{
return Channel.GetClipboardUserName(id);
}
public List<Tuple<int, string, int>> GetClipInfo(int id)
{
return Channel.GetClipInfo(id);
}
public DataTable GetConformedMasterRecord(int masterId)
{
return Channel.GetConformedMasterRecord(masterId);
}
public ConformingLoadOrderNum GetConformingLoadOrderNum(int id, string userName)
{
return Channel.GetConformingLoadOrderNum(id, userName);
}
public Tuple<string, string, int?, int> GetConformingMovie(int id)
{
return Channel.GetConformingMovie(id);
}
public MovieConform GetConformingRecord(int id)
{
return Channel.GetConformingRecord(id);
}
public ConformingStructure GetConformingStructure(int id)
{
return Channel.GetConformingStructure(id);
}
public int GetCountByRatingAndType(int id, int rating, string type)
{
return Channel.GetCountByRatingAndType(id, rating, type);
}
public Tuple<string, DateTime> GetDAMStatus(int id)
{
return Channel.GetDAMStatus(id);
}
public DateTime GetDelNOCDate(int id, string type)
{
return Channel.GetDelNOCDate(id, type);
}
public bool GetDelCOA(int id)
{
return Channel.GetDelCOA(id);
}
public int? GetDerivativeId(int id)
{
return Channel.GetDerivativeId(id);
}
public DataTable GetDerivativeNonBTS(int id, string types)
{
return Channel.GetDerivativeNonBTS(id, types);
}
public List<Tuple<int, string>> GetDerivativesForUpdate(int masterId)
{
return Channel.GetDerivativesForUpdate(masterId);
}
public Tuple<DateTime, string> GetEarliestNAD(int id, int xxx)
{
return Channel.GetEarliestNAD(id, xxx);
}
public string GetEditBay(int id)
{
return Channel.GetEditBay(id);
}
public List<string> GetEditBays()
{
return Channel.GetEditBays();
}
public string GetEditor(int id)
{
return Channel.GetEditor(id);
}
public string GetEditors()
{
return Channel.GetEditors();
}
public string GetESLocation(int id)
{
return Channel.GetESLocation(id);
}
public int GetFCPFailHistoryCount(int id)
{
return Channel.GetFCPFailHistoryCount(id);
}
public List<TrackSQCHistory> GetFCPHistory(int id)
{
return Channel.GetFCPHistory(id);
}
public TrackSQCHistory GetFCPHistoryRecord(int historyId)
{
return Channel.GetFCPHistoryRecord(historyId);
}
public bool GetFCPPassed(int id)
{
return Channel.GetFCPPassed(id);
}
public TrackS GetFCPRecord(int id)
{
return Channel.GetFCPRecord(id);
}
public string GetFCPRuntime(int id)
{
return Channel.GetFCPRuntime(id);
}
public string GetFCPStatus(int id, bool useAltId = true)
{
return Channel.GetFCPStatus(id, useAltId);
}
public List<string> GetFileFormats()
{
return Channel.GetFileFormats();
}
public List<string> GetFrameRates()
{
return Channel.GetFrameRates();
}
public DataTable GetGraphicsPackage(int id)
{
return Channel.GetGraphicsPackage(id);
}
public List<string> GetHardDrive()
{
return Channel.GetHardDrive();
}
public Tuple<int, int> GetHDAndSDHDId(int id)
{
return Channel.GetHDAndSDHDId(id);
}
public DataTable GetHiddenMovies()
{
return Channel.GetHiddenMovies();
}
public List<MovieConformHistory> GetHistoryByType(int id, string dataType)
{
return Channel.GetHistoryByType(id, dataType);
}
public string GetHustler(int id)
{
return Channel.GetHustler(id);
}
public int? GetIdByRating(int id, string rating, bool hd)
{
return Channel.GetIdByRating(id, rating, hd);
}
public List<string> GetInterlace()
{
return Channel.GetInterlace();
}
public List<string> GetLanguages()
{
return Channel.GetLanguages();
}
public string GetLanguageAbbreviation(string language)
{
return Channel.GetLanguageAbbreviation(language);
}
public Tuple<int, string> GetMaster(int masterId, int xxx)
{
return Channel.GetMaster(masterId, xxx);
}
public int GetMasterId(int id)
{
return Channel.GetMasterId(id);
}
public List<int> GetMasterIds(int id, bool hasGraphicsPackage)
{
return Channel.GetMasterIds(id, hasGraphicsPackage);
}
public MovieConformFeatures GetMovieConformFeatures(int id)
{
return Channel.GetMovieConformFeatures(id);
}
public DataTable GetMovieConformingStatus(int id, int rating, string assetType, string types, bool graphicsPackage,
bool sceneComp, bool getMasters)
{
return Channel.GetMovieConformingStatus(id, rating, assetType, types, graphicsPackage, sceneComp, getMasters);
}
public DataTable GetMovieConformingStatusGraphicsPackageOnly(int id)
{
return Channel.GetMovieConformingStatusGraphicsPackageOnly(id);
}
public MovieConformNotes GetMovieConformNotes(int id)
{
return Channel.GetMovieConformNotes(id);
}
public Tuple<int, string, int> GetMovieInfo(int id)
{
return Channel.GetMovieInfo(id);
}
public Tuple<int, string, string, int> GetMovieInfoAlt(int id)
{
return Channel.GetMovieInfoAlt(id);
}
public Tuple<string, string, DateTime> GetMovieLanguage(int id)
{
return Channel.GetMovieLanguage(id);
}
public Tuple<int, string> GetMovieRatingType(int id)
{
return Channel.GetMovieRatingType(id);
}
public TrafficInternet GetMSRecord(int id)
{
return Channel.GetMSRecord(id);
}
public string GetNAD(int id, string type)
{
return Channel.GetNAD(id, type);
}
public bool GetNADAssignedTo(int id)
{
return Channel.GetNADAssignedTo(id);
}
public string GetNotes(int id, string track)
{
return Channel.GetNotes(id, track);
}
public List<Tuple<string, DateTime, string>> GetNotesHistory(int id, string type)
{
return Channel.GetNotesHistory(id, type);
}
public ConformingProjectComplete GetProjectComplete(int id)
{
return Channel.GetProjectComplete(id);
}
public int GetRating(int id)
{
return Channel.GetRating(id);
}
public ConformingEmployeeStatsRport GetReportRecord(int id)
{
return Channel.GetReportRecord(id);
}
public List<string> GetResolutions()
{
return Channel.GetResolutions();
}
public DataTable GetSAFQC(int id)
{
return Channel.GetSAFQC(id);
}
public DataTable GetSceneComp(int id, string types, bool graphicsPackage, bool sceneComp, Tuple<string, string> titles)
{
return Channel.GetSceneComp(id, types, graphicsPackage, sceneComp, titles);
}
public string GetSMBLocation(int id)
{
return Channel.GetSMBLocation(id);
}
public DataTable GetSpanishDerivatives(int derivativeId, int masterId, int hd)
{
return Channel.GetSpanishDerivatives(derivativeId, masterId, hd);
}
public bool GetSpanishQC(int id)
{
return Channel.GetSpanishQC(id);
}
public string GetStatus(int id, string type)
{
return Channel.GetStatus(id, type);
}
public string GetStatusMaster(int id)
{
return Channel.GetStatusMaster(id);
}
public Tuple<string, string> GetStructure(int id)
{
return Channel.GetStructure(id);
}
public Tuple<int?, int?> GetStructureQC(int id)
{
return Channel.GetStructureQC(id);
}
public int GetStructureQCPassed(int id)
{
return Channel.GetStructureQCPassed(id);
}
public int GetStudioId(int masterId)
{
return Channel.GetStudioId(masterId);
}
public List<string> GetSubratings(int id)
{
return Channel.GetSubratings(id);
}
public int GetTENCount(int id)
{
return Channel.GetTENCount(id);
}
public int? GetTimelineComplete(int id)
{
return Channel.GetTimelineComplete(id);
}
public string GetTitle(int id)
{
return Channel.GetTitle(id);
}
public Tuple<string, string, int> GetTitleTypeRating(int id, string titleType)
{
return Channel.GetTitleTypeRating(id, titleType);
}
public Tuple<string, string> GetTitles(int id)
{
return Channel.GetTitles(id);
}
public Tuple<string, int, int> GetTypeStudioHD(int id)
{
return Channel.GetTypeStudioHD(id);
}
public List<string> GetUpcomingVODPitches(int id)
{
return Channel.GetUpcomingVODPitches(id);
}
public List<int> GetWebSliceIds(int id)
{
return Channel.GetWebSliceIds(id);
}
public List<string> GetXmlSources(int id)
{
return Channel.GetXmlSources(id);
}
public List<int> GetXXEXXIds(int masterId)
{
return Channel.GetXXEXXIds(masterId);
}
public string GetXXX(int rating)
{
return Channel.GetXXX(rating);
}
public bool HasContentFailure(int id, int itemId)
{
return Channel.HasContentFailure(id, itemId);
}
public bool HasTechnicalFailure(int id, int itemId)
{
return Channel.HasTechnicalFailure(id, itemId);
}
public bool HideId(int id)
{
return Channel.HideId(id);
}
public bool IsClipLoggingComplete(int id)
{
return Channel.IsClipLoggingComplete(id);
}
public bool IsFCPPassed(int id)
{
return Channel.IsFCPPassed(id);
}
public bool IsFCPRuntimeEntered(int id)
{
return Channel.IsFCPRuntimeEntered(id);
}
public int? IsFormatDigital(string format)
{
return Channel.IsFormatDigital(format);
}
public bool IsHD(int id)
{
return Channel.IsHD(id);
}
public bool IsReadyForTimelineQC(int id)
{
return Channel.IsReadyForTimelineQC(id);
}
public bool IsStructureQCComplete(int id)
{
return Channel.IsStructureQCComplete(id);
}
public bool SaveLanguage(int id, string language, string userName)
{
return Channel.SaveLanguage(id, language, userName);
}
public bool UnhideId(int id)
{
return Channel.UnhideId(id);
}
public bool Update3DStatus(int id)
{
return Channel.Update3DStatus(id);
}
public bool UpdateClipboardUserName(string userName, int id)
{
return Channel.UpdateClipboardUserName(userName, id);
}
public bool UpdatePal(int id)
{
return Channel.UpdatePal(id);
}
public bool UpdateSpanishQC(int id, int qc)
{
return Channel.UpdateSpanishQC(id, qc);
}
public bool UpdateTrackYRecord(int id)
{
return Channel.UpdateTrackYRecord(id);
}
public bool UpdateYLocation(int id)
{
return Channel.UpdateYLocation(id);
}
public bool UseTitleOnAsset()
{
return Channel.UseTitleOnAsset();
}
#endregion
}
} |
using UnityEngine;
using System.Collections;
using Malee.Geomix.Geom;
/**
* @author Chris Foulston
*/
namespace Malee.Hive.Util {
public enum InputType {
Auto, Touch, Keyboard, Mouse
}
public static class InputUtil {
public static Vector2 topLeftMousePosition {
get { return ScreenUtil.TopLeft(Input.mousePosition); }
}
public static Vector2 topLeftMousePositionRounded {
get { return ScreenUtil.TopLeftRounded(Input.mousePosition); }
}
public static Vector3 GetGroundMousePosition() {
return GetGroundMousePosition(Camera.main, Input.mousePosition);
}
public static Vector3 GetGroundMousePosition(Camera camera) {
return GetGroundMousePosition(camera, Input.mousePosition);
}
public static Vector3 GetEditorGroundMousePosition(Event guiEvent) {
Vector2 emp = guiEvent.mousePosition;
Vector3 smp = new Vector3(emp.x, Screen.height - (emp.y + 25), 0);
return GetGroundMousePosition(Camera.main, smp);
}
public static bool GetGroundInputPosition(Camera camera, out Vector3 position) {
if (Input.touchCount > 0) {
position = GetGroundMousePosition(camera, Input.GetTouch(0).position);
return true;
}
else if (Input.GetMouseButton(0)) {
position = GetGroundMousePosition(camera, Input.mousePosition);
return true;
}
position = Vector3.zero;
return false;
}
public static Vector3 GetGroundMousePosition(Camera camera, Vector3 mousePosition) {
if (camera) {
Ray ray = camera.ScreenPointToRay(mousePosition);
Plane plane = new Plane(Vector3.up, 0);
float dist = 1.0f;
if (plane.Raycast(ray, out dist)) {
return ray.GetPoint(dist);
}
}
return Vector3.zero;
}
public static RaycastHit GetHitFromInput() {
return GetHitFromInput(Camera.main);
}
public static RaycastHit GetHitFromInput(Camera camera) {
return GetHitFromInput(camera, -1);
}
public static RaycastHit GetHitFromInput(Camera camera, int layerMask) {
if (Input.touchCount > 0) {
return GetMouseHit(camera, Input.GetTouch(0).position, layerMask);
}
else if (Input.GetMouseButton(0)) {
return GetMouseHit(camera, layerMask);
}
else {
return new RaycastHit();
}
}
public static RaycastHit GetMouseHit() {
return GetMouseHit(Camera.main);
}
public static RaycastHit GetMouseHit(Camera camera) {
return GetMouseHit(camera, -1);
}
public static RaycastHit GetMouseHit(Camera camera, int layerMask) {
return GetMouseHit(camera, Input.mousePosition, layerMask);
}
public static RaycastHit GetMouseHit(Camera camera, Vector2 screenPosition, int layerMask) {
Ray ray = camera.ScreenPointToRay(screenPosition);
RaycastHit hit;
Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask);
return hit;
}
public static Ray GetMouseRay() {
return GetMouseRay(Camera.main);
}
public static Ray GetMouseRay(Camera camera) {
return camera.ScreenPointToRay(Input.mousePosition);
}
public static Vector3 GetWorldMouse(float distance) {
return GetWorldMouse(Camera.main, distance);
}
public static Vector3 GetWorldMouse(Camera camera, float distance) {
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
return ray.origin + ray.direction * distance;
}
public static Touch GetTouchById(int touchId) {
return System.Array.Find<Touch>(Input.touches, (Touch touch) => {
return touch.fingerId == touchId;
});
}
public static Touch GetTouchById(int touchId, TouchPhase phase) {
return System.Array.Find<Touch>(Input.touches, (Touch touch) => {
return touch.fingerId == touchId && touch.phase == phase;
});
}
public static Touch GetTouchByPhase(TouchPhase phase) {
return System.Array.Find<Touch>(Input.touches, (Touch touch) => {
return touch.phase == phase;
});
}
public static Vector3 GetInputPosition() {
if (Input.touchCount > 0) {
return Input.GetTouch(0).position;
}
else {
return Input.mousePosition;
}
}
}
//
// -- VIRTUAL AXIS --
//
public static class VirtualAxis {
private static Vector2 axis;
public static Vector2 GetAxis(InputType type, bool raw = false) {
switch (type) {
case InputType.Auto : return GetAuto(raw);
case InputType.Touch: return GetTouch(raw);
case InputType.Mouse: return GetMouse(raw);
case InputType.Keyboard: return GetKey(raw);
}
return axis;
}
public static Vector2 GetAuto(bool raw = false) {
if (Input.touchCount > 0) {
return GetTouch(raw);
}
else if (Input.GetMouseButton(0)) {
return GetMouse(raw);
}
else {
return GetKey(raw);
}
}
public static Vector2 GetTouch(bool raw = false) {
if (Input.touchCount > 0) {
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved) {
float dt = touch.deltaTime > 0 ? Time.deltaTime / touch.deltaTime : 0;
Vector3 delta = touch.deltaPosition * dt;
axis.x = !raw ? delta.x : Mathf.Round(delta.x);
axis.y = !raw ? delta.y : Mathf.Round(delta.y);
}
else {
axis.x = axis.y = 0;
}
}
else {
axis.x = axis.y = 0;
}
return axis;
}
public static Vector2 GetKey(bool raw = false) {
axis.x = !raw ? Input.GetAxis("Horizontal") : Input.GetAxisRaw("Horizontal");
axis.y = !raw ? -Input.GetAxis("Vertical") : -Input.GetAxisRaw("Vertical");
return axis;
}
public static Vector2 GetMouse(bool raw = false) {
axis.x = !raw ? Input.GetAxis("MouseX") : Input.GetAxisRaw("MouseX");
axis.y = !raw ? Input.GetAxis("MouseY") : Input.GetAxisRaw("MouseY");
return axis;
}
}
//
// -- VIRTUAL PAD --
//
public class VirtualPad {
public Vector2 axis;
public float radius;
public float deadZone;
public Vector2 origin;
public bool isFixed;
public int mouseButton;
private int touchId;
public VirtualPad(float radius, bool isFixed = false, float deadZone = 0) {
this.radius = radius;
this.isFixed = isFixed;
this.deadZone = deadZone;
this.mouseButton = 0;
touchId = -1;
origin = Vector2.zero;
}
public float magnitude {
get { return axis.magnitude; }
}
public float sqrMagnitude {
get { return axis.sqrMagnitude; }
}
public void ResetAxis() {
axis.x = axis.y = 0;
}
public void DampAxis(float damping) {
axis.x *= damping;
axis.y *= damping;
}
public Vector2 GetAxis(InputType type, bool raw = false) {
switch (type) {
case InputType.Auto: return GetAuto(raw);
case InputType.Touch: return GetTouch(raw);
case InputType.Mouse: return GetMouse(raw);
case InputType.Keyboard: return GetKey(raw);
}
return axis;
}
private Vector2 GetAuto(bool raw = false) {
if (Input.touchCount > 0) {
return GetTouch(raw);
}
else if (Input.GetMouseButton(0)) {
return GetMouse(raw);
}
else {
return GetKey(raw);
}
}
private Vector2 GetTouch(bool raw = false) {
if (Input.touchCount > 0) {
Touch touch = touchId > 0 ? InputUtil.GetTouchById(touchId) : Input.GetTouch(0);
Vector2 pos = ScreenUtil.TopLeft(touch.position);
touchId = touch.fingerId;
if (touch.phase == TouchPhase.Began) {
if (!isFixed) {
axis.x = axis.y = 0;
origin = pos;
}
else {
axis = GetAxisFromPosition(pos, origin, raw);
}
}
else if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) {
axis = GetAxisFromPosition(pos, origin, raw);
}
else if (touch.phase == TouchPhase.Ended) {
touchId = -1;
}
}
else {
touchId = -1;
}
return axis;
}
private Vector2 GetMouse(bool raw = false) {
if (Input.GetMouseButtonDown(mouseButton)) {
Vector2 pos = ScreenUtil.TopLeft(Input.mousePosition);
if (!isFixed) {
axis.x = axis.y = 0;
origin = pos;
}
else {
axis = GetAxisFromPosition(pos, origin, raw);
}
}
else if (Input.GetMouseButton(mouseButton)) {
axis = GetAxisFromPosition(ScreenUtil.TopLeft(Input.mousePosition), origin, raw);
}
return axis;
}
private Vector2 GetKey(bool raw = false) {
if (Input.GetButton("Horizontal") || Input.GetButton("Vertical")) {
axis.x = origin.x + Input.GetAxis("Horizontal") * radius;
axis.y = origin.y - Input.GetAxis("Vertical") * radius;
axis = GetAxisFromPosition(axis, origin, raw);
}
return axis;
}
private Vector2 GetAxisFromPosition(Vector2 position, Vector2 origin, bool raw) {
Vector2 delta = position - origin;
float distance = delta.magnitude;
if (distance > deadZone) {
float d1 = distance - deadZone;
float d2 = radius - deadZone;
float ratio = Mathf.Clamp01(d1 / d2);
float angle = MathUtil.AngleBetweenTopLeft(origin, position);
float dx = Mathf.Sin(angle) * ratio;
float dy = -Mathf.Cos(angle) * ratio;
axis.x = !raw ? dx : Mathf.Round(dx);
axis.y = !raw ? dy : Mathf.Round(dy);
}
else {
axis.x = axis.y = 0;
}
return axis;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Looxid.Link
{
public class BrainEffect : MonoBehaviour
{
public ParticleSystem brainEffectLight;
public float alphaValue;
public ParticleLines brainEffectLine;
public Color StartColor
{
set
{
var main = brainEffectLight.main;
main.startColor = value;
}
}
void Start()
{
brainEffectLight = GetComponent<ParticleSystem>();
}
void Update()
{
Color whiteCol = new Color(255 / 255f, 255 / 255f, 255 / 255f, alphaValue / 255f);
Color blueCol = new Color(0 / 255f, 107 / 255f, 255 / 255f, alphaValue / 255f);
if (brainEffectLight.gameObject.name.Equals("LeftBrain"))
{
StartColor = whiteCol;
}
else if (brainEffectLight.gameObject.name.Equals("Left Effect A"))
{
StartColor = blueCol;
brainEffectLine.startColor = new Color(255 / 255f, 255 / 255f, 255 / 255f, alphaValue * 5 / 255f);
}
else if (brainEffectLight.gameObject.name.Equals("Left Effect B"))
{
StartColor = blueCol;
brainEffectLine.startColor = new Color(255 / 255f, 255 / 255f, 255 / 255f, alphaValue * 5 / 255f);
}
else if (brainEffectLight.gameObject.name.Equals("RightBrain"))
{
StartColor = whiteCol;
}
else if (brainEffectLight.gameObject.name.Equals("Right Effect A"))
{
StartColor = blueCol;
brainEffectLine.startColor = new Color(255 / 255f, 255 / 255f, 255 / 255f, alphaValue * 5 / 255f);
}
else if (brainEffectLight.gameObject.name.Equals("Right Effect B"))
{
StartColor = blueCol;
brainEffectLine.startColor = new Color(255 / 255f, 255 / 255f, 255 / 255f, alphaValue * 5 / 255f);
}
}
}
} |
using System.Collections.Generic;
using Tomelt.Tags.Models;
namespace Tomelt.Tags.ViewModels {
public class TagsIndexViewModel {
public IList<TagRecord> Tags { get; set; }
}
}
|
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
public partial class Cookie2Source : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=naresh;Integrated Security=True");
string uname = txtUserName.Text;
string pwd = txtPassword.Text;
string query = "select * from Login where Username='" + uname + "' and Password='" + pwd + "'";
SqlDataAdapter da = new SqlDataAdapter(query, cn);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count>0)
{
HttpCookie ObjUname = new HttpCookie("Uname");
ObjUname.Value = uname;
if (chkRemember.Checked==true)
{
ObjUname.Expires = DateTime.Now.AddDays(1);
}
Response.Cookies.Add(ObjUname);
Response.Redirect("Cookie2Destination.aspx");
}
else
{
Response.Write("Login failed");
}
}
} |
using System.Collections.Generic;
using Xunit;
using DinoDiner.Menu;
namespace MenuTest.Entrees
{
public class PrehistoricPBJUnitTest
{
/// <summary>
/// has correct default price
/// </summary>
[Fact]
public void ShouldHaveCorrectDefaultPrice()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
Assert.Equal(6.52, pbj.Price, 2);
}
/// <summary>
/// has correct default calories
/// </summary>
[Fact]
public void ShouldHaveCorrectDefaultCalories()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
Assert.Equal<uint>(483, pbj.Calories);
}
/// <summary>
/// has correct default ingredients
/// </summary>
[Fact]
public void ShouldListDefaultIngredients()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
List<string> ingredients = pbj.Ingredients;
Assert.Contains<string>("Bread", ingredients);
Assert.Contains<string>("Peanut Butter", ingredients);
Assert.Contains<string>("Jelly", ingredients);
Assert.Equal<int>(3, ingredients.Count);
}
/// <summary>
/// removes peanut butter from ingredients
/// </summary>
[Fact]
public void HoldPeanutButterShouldRemovePeanutButter()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
pbj.HoldPeanutButter();
Assert.DoesNotContain<string>("Peanut Butter", pbj.Ingredients);
}
/// <summary>
/// removes jelly from ingredients
/// </summary>
[Fact]
public void HoldJellyShouldRemoveJelly()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
pbj.HoldJelly();
Assert.DoesNotContain<string>("Jelly", pbj.Ingredients);
}
/// <summary>
/// tests to make sure the description for the item is correct
/// </summary>
[Fact]
public void DescriptionShouldBeCorrect()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
Assert.Equal("Prehistoric PB&J", pbj.Description);
}
/// <summary>
/// checks to make sure that the special string array is empty by default
/// </summary>
[Fact]
public void SpecialShouldBeEmptyByDefault()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
Assert.Empty(pbj.Special);
}
/// <summary>
/// checks to make sure that if there are any special instructions for food prep, it adds to the special[]
/// </summary>
[Fact]
public void HoldPeanutButterShouldAddToSpecial()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
pbj.HoldPeanutButter();
Assert.Collection<string>(pbj.Special, item =>
{
Assert.Equal("Hold Peanut Butter", item);
}
);
}
/// <summary>
/// checks to make sure that if there are any special instructions for food prep, it adds to the special[]
/// </summary>
[Fact]
public void HoldJellyShouldAddToSpecial()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
pbj.HoldJelly();
Assert.Collection<string>(pbj.Special, item =>
{
Assert.Equal("Hold Jelly", item);
}
);
}
/// <summary>
/// tests to see if there are multiple special instructions, to add to the special[]
/// </summary>
[Fact]
public void HoldPeanutButterAndJellyShouldAddToSpecial()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
pbj.HoldPeanutButter();
pbj.HoldJelly();
Assert.Collection<string>(pbj.Special, item =>
{
Assert.Equal("Hold Peanut Butter", item);
}, item =>
{
Assert.Equal("Hold Jelly", item);
}
);
}
/// <summary>
/// tests to see that special is notified whenever a property changes
/// </summary>
[Fact]
public void HoldingPeanutButterShouldNotifySpecialChange()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
Assert.PropertyChanged(pbj, "Special", () =>
{
pbj.HoldPeanutButter();
});
}
/// <summary>
/// tests to see that special is notified whenever a property changes
/// </summary>
[Fact]
public void HoldingJellyShouldNotifySpecialChange()
{
PrehistoricPBJ pbj = new PrehistoricPBJ();
Assert.PropertyChanged(pbj, "Special", () =>
{
pbj.HoldJelly();
});
}
}
}
|
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Threading;
//using System.Threading.Tasks;
//using DFC.ServiceTaxonomy.Neo4j.Configuration;
//using DFC.ServiceTaxonomy.Neo4j.Queries.Interfaces;
//using DFC.ServiceTaxonomy.Neo4j.Services;
//using DFC.ServiceTaxonomy.Neo4j.Services.Internal;
//using Divergic.Logging.Xunit;
//using FakeItEasy;
//using Microsoft.Extensions.Logging;
//using Xunit;
//using Xunit.Abstractions;
//namespace DFC.ServiceTaxonomy.IntegrationTests.Helpers
//{
// //todo: if use logger rather than helper, we can do checks like 'after disable no jobs started on disabled replica'
// // 'after disable, all in flight jobs on disabled replica finish' etc. by checking the cache of logs
// public class GraphClusterIntegrationTest
// {
// internal const int NumberOfReplicasConfiguredForPublishedSet = 2;
// internal GraphClusterLowLevel GraphClusterLowLevel { get; }
// internal IEnumerable<INeoEndpoint> Endpoints { get; }
// internal ICacheLogger<GraphClusterBuilder> Logger { get; }
// internal IQuery<int> Query { get; }
// internal GraphClusterIntegrationTest(
// GraphClusterCollectionFixture graphClusterCollectionFixture,
// ITestOutputHelper testOutputHelper)
// {
// Query = A.Fake<IQuery<int>>();
// Endpoints = graphClusterCollectionFixture.Neo4jOptions.Endpoints
// .Where(epc => epc.Enabled)
// .Select(epc => CreateFakeNeoEndpoint(epc.Name!));
// Logger = testOutputHelper.BuildLoggerFor<GraphClusterBuilder>();
// var graphReplicaSets = graphClusterCollectionFixture.Neo4jOptions.ReplicaSets
// .Select(rsc => new GraphReplicaSetLowLevel(
// rsc.ReplicaSetName!,
// ConstructGraphs(rsc, Endpoints, Logger),
// Logger));
// GraphClusterLowLevel = new GraphClusterLowLevel(graphReplicaSets, Logger);
// }
// //todo: can we trust TestOutputHelper.WriteLine to output in order?
// private INeoEndpoint CreateFakeNeoEndpoint(string name)
// {
// var neoEndpoint = A.Fake<INeoEndpoint>();
// A.CallTo(() => neoEndpoint.Name)
// .Returns(name);
// A.CallTo(() => neoEndpoint.Run(A<IQuery<int>[]>._, A<string>._, A<bool>._))
// .Invokes((IQuery<int>[] queries, string databaseName, bool defaultDatabase) =>
// {
// Logger.LogTrace("<{LogId}> Run started on {DatabaseName}, thread #{ThreadId}.",
// IntegrationTestLogId.RunQueryStarted, databaseName, Thread.CurrentThread.ManagedThreadId);
// Thread.Sleep(100);
// Logger.LogTrace("<{LogId}> Run finished on {DatabaseName}, thread #{ThreadId}.",
// IntegrationTestLogId.RunQueryFinished, databaseName, Thread.CurrentThread.ManagedThreadId);
// })
// .Returns(new List<int> { 69 });
// return neoEndpoint;
// }
// private IEnumerable<Graph> ConstructGraphs(
// ReplicaSetConfiguration replicaSetConfiguration,
// IEnumerable<INeoEndpoint> neoEndpoints,
// ILogger logger)
// {
// return replicaSetConfiguration.GraphInstances
// .Where(gic => gic.Enabled)
// .Select((gic, index) =>
// new Graph(
// neoEndpoints.First(ep => ep.Name == gic.Endpoint),
// gic.GraphName!,
// gic.DefaultGraph,
// index,
// logger));
// }
// // protected (int?, LogEntry?) GetLogEntry(List<LogEntry> log, DFC.ServiceTaxonomy.Neo4j.Log.LogId id)
// // {
// // return GetLogEntry(log, (int)id);
// // }
// protected (int?, LogEntry?) GetLogEntry(List<LogEntry> log, IntegrationTestLogId id)
// {
// return GetLogEntry(log, (int)id);
// }
// protected (int?, LogEntry?) GetLogEntry(List<LogEntry> log, int logId)
// {
// int index = log.FindIndex(l => IsLog(l, logId));
// if (index == -1)
// return (null, null);
// return (index, log[index]);
// }
// // protected bool IsLog(LogEntry logEntry, LogId logId, Func<KeyValuePair<string, object>, bool>? stateCheck = null)
// // {
// // return IsLog(logEntry, (int)logId, stateCheck);
// // }
// protected bool IsLog(LogEntry logEntry, IntegrationTestLogId logId, Func<KeyValuePair<string, object>, bool>? stateCheck = null)
// {
// return IsLog(logEntry, (int)logId, stateCheck);
// }
// protected bool IsLog(LogEntry logEntry, int logId, Func<KeyValuePair<string, object>, bool>? stateCheck = null)
// {
// if (!(logEntry.State is IReadOnlyList<KeyValuePair<string, object>> state))
// return false;
// if (!state.Any(kv => kv.Key == "LogId" && (int)kv.Value == logId))
// return false;
// return stateCheck == null || state.Any(stateCheck);
// }
//#if REPLICA_DISABLING_NET5_ONLY
// protected T? Get<T>(LogEntry logEntry, string key)
// {
//#pragma warning disable S1905
// return (T?)((KeyValuePair<string, object>?)(logEntry.State as IReadOnlyList<KeyValuePair<string, object>>)?
// .FirstOrDefault(kv => kv.Key == key))?
// .Value;
//#pragma warning restore S1905
// }
//#endif
// protected void ReferenceCountTest(int parallelLoops)
// {
// const int replicaInstance = 0;
// var replicaSet = GraphClusterLowLevel.GetGraphReplicaSetLowLevel("published");
// Parallel.For(0, parallelLoops, (i, state) =>
// {
// Logger.LogTrace($"Thread id: {Thread.CurrentThread.ManagedThreadId}");
// replicaSet.Disable(replicaInstance);
// replicaSet.Enable(replicaInstance);
// });
// int enabledInstanceCount = replicaSet.EnabledInstanceCount();
// Assert.Equal(NumberOfReplicasConfiguredForPublishedSet, enabledInstanceCount);
// Assert.True(replicaSet.IsEnabled(replicaInstance));
// }
// }
//}
|
using Cs_Gerencial.Dominio.Entities;
using Cs_Gerencial.Dominio.Interfaces.Repositorios;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Infra.Data.Repositorios
{
public class RepositorioSeries: RepositorioBase<Series>, IRepositorioSeries
{
public IEnumerable<Series> ConsultarPorIdCompraSelo(int idCompraSelo)
{
return Db.Series.Where(p => p.IdCompra == idCompraSelo);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.Sconit.Entity.ORD;
using com.Sconit.Entity.WMS;
namespace com.Sconit.Service
{
public interface IShipPlanMgr
{
void CreateShipPlan(string orderNo);
void CancelShipPlan(string orderNo);
void AssignShipPlan(IList<ShipPlan> shipPlanList, string assignUser);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HnC.Web.Api.Models
{
public class OrderItemResponse
{
public int ItemId { get; set; }
public int Quantity { get; set; }
public int OrderId { get; set; }
}
}
|
// Copyright © 2020 Void-Intelligence All Rights Reserved.
using System;
using Vortex.Decay.Utility;
namespace Vortex.Decay.Kernels
{
public class Exponential : BaseDecay
{
public Exponential(double decay) : base(decay)
{
}
public override double CalculateAlpha(double alpha)
{
return alpha * Math.Exp(-Decay * Epoch);
}
public override EDecayType Type()
{
return EDecayType.Exponential;
}
}
} |
namespace BuhtigIssueTracker.Constants
{
public class Messages
{
public const string AlreadyLoggedInUser =
"There is already a logged in user";
public const string ProvidedPasswordDoesntMatch =
"The provided passwords do not match";
public const string SuccessfulRegisteredUser =
"User {0} registered successfully";
public const string AlreadyRegistredUser =
"A user with username {0} already exists";
public const string UserIsNotRegistredAtTheSystem =
"A user with username {0} does not exist";
public const string InvalidPassword =
"The password is invalid for user {0}";
public const string SuccessfullyLoggedIn =
"User {0} logged in successfully";
public const string CurrentlyNoUserLoggedInAtSystem =
"There is no currently logged in user";
public const string SuccessfullyLogOut =
"User {0} logged out successfully";
public const string SuccessfullyIssueCreated =
"Issue {0} created successfully";
public const string InvalidIssueId =
"There is no issue with ID {0}";
public const string NoIssueWithGivenId =
"There is no issue with ID {0}";
public const string SuccefullyAddedCommentToIssue =
"Comment added successfully to issue {0}";
public const string NoIssues = "No issues";
public const string NoComments = "No comments";
public const string NoProvidedTags = "There are no tags provided";
public const string NoIssuesMatchingProvidedTags =
"There are no issues matching the tags provided";
public const string IssueRemoved =
"Issue {0} removed";
public const string ThisIssueDoesntBelongToUser = "The issue with ID {0} does not belong to user {1}";
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Core.Common;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
namespace Tests.Pages.Oberon.CustomForm.CustomFormBuild
{
public class BuildPageContributionInformationDialog : CustomFormBuildPage
{
public BuildPageContributionInformationDialog(Driver driver) : base(driver) { }
public IWebElement DisplayRecurringOptions { get { return _driver.FindElement(By.Name("IsRecurringEnabled")); } }
public void ClickDisplayRecurringOptions()
{
_driver.Click(DisplayRecurringOptions);
_driver.SetImplicitWaitTimeout(3);
}
public IWebElement SectionTitle { get { return _driver.FindElement(By.Name("SectionTitle")); } }
public IWebElement Update { get { return _driver.FindElement(By.CssSelector("div.action.formButtons span.buttonGroup input[value='Update']")); } }
public void ClickUpdate()
{
_driver.JavascriptClick(Update);
}
public IWebElement MinimumAmount { get { return _driver.FindElement(By.Name("MinimumAmount")); } }
public IWebElement MaximumAmount { get { return _driver.FindElement(By.Name("MaximumAmount")); } }
public IWebElement ValueTable { get { return _driver.FindElement(By.ClassName("formField")); } }
public IWebElement AmountDefault(int index)
{
string elementId = String.Format("AmountOptions[{0}].Id", index);
return
_driver.FindElement(
By.XPath("//input[@name='" + elementId + "']/following-sibling::input[@name='DefaultOptionId']"));
}
public void ClickAmountDefault(int index)
{
AmountDefault(index).Click();
}
public IWebElement Amount(int index)
{
return ValueTable.FindElement(By.Name(String.Format("AmountOptions[{0}].Amount", index)));
}
public IWebElement Label(int index)
{
return ValueTable.FindElement(By.Name(String.Format("AmountOptions[{0}].Label", index)));
}
public IWebElement ProvideAmountOptionsYes { get { return _driver.FindElement(By.Id("ProvideAmountOptions_Yes")); } }
public IWebElement ProvideAmountOptionsNo { get { return _driver.FindElement(By.Id("ProvideAmountOptions_No")); } }
public IWebElement ShowOtherOptionYes { get { return _driver.FindElement(By.Id("ShowOtherOption_Yes")); } }
public IWebElement ShowOtherOptionNo { get { return _driver.FindElement(By.Id("ShowOtherOption_No")); } }
public IWebElement OtherAmountDefault()
{
if (ShowOtherOptionYes.Selected)
{
return _driver.FindElement(By.Id("DefaultOptionId"));
}
else
{
return null;
}
}
public void ClickOtherAmountDefault()
{
_driver.Click(OtherAmountDefault());
}
public IWebElement OtherAmount { get { return _driver.FindElement(By.Name("OtherAmountTextBox")); } }
public IWebElement MakeRecurringOnly { get { return _driver.FindElement(By.Name("IsRecurringOnlyContributionEnabled")); } }
public IWebElement RecurringCheckboxLabel { get { return _driver.FindElement(By.Name("RecurringCheckboxLabel")); } }
public IWebElement FrequencyOptionLabel(int index)
{
return _driver.FindElement(By.Name(String.Format("FrequencyOptions[{0}].Label", index)));
}
public IWebElement DisplayFrequencyOption(int index)
{
return _driver.FindElement(By.Name(String.Format("FrequencyOptions[{0}].IsDisplayed", index)));
}
public void ClickDisplayFrequencyOption(int index)
{
_driver.Click(DisplayFrequencyOption(index));
}
//Return the next element to FrequencyOptionLabel
public IWebElement MakeFrequencyOptionDefault(int index)
{
string elementId = String.Format("FrequencyOptions_{0}__IsDefault", index);
return
_driver.FindElement(
By.XPath("//input[@id='" + elementId + "']/following-sibling::input[@name='FrequencyIsDefault']"));
}
public IWebElement ShowDurationOptions { get { return _driver.FindElement(By.Name("IsDurationEnabled")); } }
public void ClickShowDurationOptions()
{
_driver.Click(ShowDurationOptions);
_driver.SetImplicitWaitTimeout(3);
}
public IWebElement RecurringDurationLabel { get { return _driver.FindElement(By.Name("RecurringDurationLabel")); } }
public IWebElement DurationOptionLabel(int index)
{
return _driver.FindElement(By.Name(String.Format("DurationOptions[{0}].Label", index)));
}
public IWebElement DisplayDurationOption(int index)
{
return _driver.FindElement(By.Name(String.Format("DurationOptions[{0}].IsDisplayed", index)));
}
public void ClickDisplayDurationOption(int index)
{
_driver.Click(DisplayDurationOption(index));
}
public IWebElement MakeDurationOptionDefault(int index)
{
string elementId = String.Format("DurationOptions_{0}__IsDefault", index);
return
_driver.FindElement(
By.XPath("//*[@id='" + elementId + "']/following-sibling::input[@name='DurationIsDefault']"));
}
public void ClickMakeDurationOptionDefault(int index)
{
_driver.Click(MakeDurationOptionDefault(index));
}
public IWebElement DurationOptionEndDate(int index)
{
return _driver.FindElement(By.Name(String.Format("DurationOptions[{0}].EndDate", index)));
}
public void SetRecurringDurationLabel(string value)
{
_driver.SendKeys(RecurringDurationLabel, value);
}
public void SetDurationOptionLabel(int index, string value)
{
_driver.SendKeys(DurationOptionEndDate(index),value);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nac.Wpf.Fuzzy {
class NacWpfFuzzyRuleEditorViewModel : ObservableCollection<NacWpfFuzzyRule> {
private NacWpfFuzzyRule _current = new NacWpfFuzzyRule();
public NacWpfFuzzyRule Current { get { return _current; } set { if (value != null) { _current = value; OnPropertyChanged(new PropertyChangedEventArgs("Current")); } } }
public NacWpfFuzzyRuleEditorViewModel() { }
public NacWpfFuzzyRuleEditorViewModel(HashSet<string> rules) : base(rules.Select(rule => new NacWpfFuzzyRule(rule))) { }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace test.ViewComponents
{
[ViewComponent]
public class ArchivedPostsViewComponent : ViewComponent
{
private readonly test.Models.BlogDataContext _dbContext;
public ArchivedPostsViewComponent(test.Models.BlogDataContext db)
{
_dbContext = db;
}
public IViewComponentResult invoke()
{
var archivedPosts = _dbContext.GetArchivedPosts().ToArray();
return View(archivedPosts);
}
}
}
|
/* Author: Mitchell Spryn (mitchell.spryn@gmail.com)
* There is no warranty with this code. I provide it with the intention of being interesting/helpful, but make no
* guarantees about its correctness or robustness.
* This code is free to use as you please, as long as this header comment is left in all of the files and credit is attributed
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace NNGen
{
/// <summary>
/// An abstraction of a neural network entity.
/// </summary>
public class AsyncNeuralNetwork : Entity
{
/// <summary>
/// The entity name
/// </summary>
private string name = "AsyncNeuralNetwork";
/// <summary>
/// The list of input ports to the network
/// </summary>
public Port[] nnInputPorts { get; private set; }
/// <summary>
/// The list of output ports to the network
/// </summary>
public Port[] nnOutputPorts { get; private set; }
/// <summary>
/// This signal will go high when the network has been initialized after a reset.
/// It will go low when the device is in reset
/// </summary>
public Port ready { get; private set; }
/// <summary>
/// A clock used for synchronous loading of the neuron weights from memory
/// </summary>
public Port clk { get; private set; }
/// <summary>
/// An active high reset for the network
/// </summary>
public Port reset { get; private set; }
/// <summary>
/// The activation types for each layer of the network.
/// The i-th member corresponds to the activations of the i-th layer of the network
/// </summary>
public AsyncNeuron.NeuronActivationType[] activationTypes { get; private set; }
/// <summary>
/// The number of neurons in each layer of the network.
/// The i-th member corresponds to the i-th layer of the network
/// </summary>
public int[] neuronCounts { get; private set; }
/// <summary>
/// The bias values for each layer.
/// The i-th member corresponds to the bias value fed into the i+1-th layer of the network
/// </summary>
public double[] biasValues { get; private set; }
/// <summary>
/// A signal used to enable a single neuron to accept weights from memory
/// </summary>
public Signal load_sig { get; private set; }
/// <summary>
/// A signal to hold the values of data coming from memory
/// </summary>
public Signal loadVal { get; private set; }
/// <summary>
/// A signal used to index into an individual neuron's weight signals
/// Used during the load process
/// </summary>
public Signal loadOffset { get; private set; }
/// <summary>
/// A signal used to index into memory to obtain the weights during the load process
/// </summary>
public Signal addrCounter { get; private set; }
/// <summary>
/// The signals that will hold the outputs to each individual neuron
/// </summary>
public Signal[] neuron_outputs { get; private set; }
/// <summary>
/// A signal used in determining whether the device has completed the loading process
/// </summary>
public Signal ready_signal { get; private set; }
/// <summary>
/// A collection of signals to hold the final_load outputs from the individual neurons in the network
/// </summary>
public Signal[] finalLoadSignals { get; private set; }
/// <summary>
/// A signal used to convert the output of memory (STD_LOGIC_VECTOR) into the appropriate type
/// to be used in the neuron (SIGNED_FIXED_POINT)
/// </summary>
public Signal loadValConv { get; private set; }
/// <summary>
/// The values to be used for thresholding the output neurons.
/// The i-th member of this array corresponds to the theshold value for the i-th output neuron.
/// If the network is not a classification network (i.e. isClassifier = false), then this member is unused.
/// </summary>
public double[] classifierThresholds { get; private set; }
/// <summary>
/// If the neural network is to be used for classification, then this variable should be set to true.
/// This will instantiate comparitors on the output neurons.
/// </summary>
public bool isClassifier { get; private set; }
/// <summary>
/// The number of integer bits to be used for the neural network inputs
/// </summary>
public int numIntBits { get; private set; }
/// <summary>
/// The number of fractional bits to be used for the neural network inputs and for the neural network weights
/// </summary>
public int numFracBits { get; private set; }
/// <summary>
/// The number of integer bits to be used for the neural network weights.
/// </summary>
public int numWeightUpperBits { get; private set; }
/// <summary>
/// A memory entity used to store and load the neural network weights on startup
/// </summary>
public WeightMemory wm { get; private set; }
/// <summary>
/// An array of the neurons in the network. It is sequentually loaded, first by layer, then by order within the layer.
/// So, for a net of N layers, each with M neurons in the layer, the array will be
/// [Neuron_0_0, Neuron_0_1, ..., Neuron_0_M, Neuron_1_0, Neuron_1_1, ..., Neuron_N_M]
/// </summary>
public AsyncNeuron[] neuronEntities { get; private set; }
/// <summary>
/// A list of the unique neuron entities for which separate VHDL files will need to be generated.
/// </summary>
public List<AsyncNeuron> uniqueNeuronEntities { get; private set; }
/// <summary>
/// The bus widths for each neuron
/// </summary>
public int[] intBusWidths { get; private set; }
/// <summary>
/// The constructor for a neural network object. Calling this method's write() function will write the entire network.
/// </summary>
/// <param name="_neuronCounts">The number of neurons in each layer, excluding the bias node.</param>
/// <param name="_biasValues">The bias value feeding forward into the next layer. </param>
/// <param name="_activationTypes">The activation types for the neurons in each layer</param>
/// <param name="_numIntBits">The number of integer bits to use for the inputs for each neuron (Sigmoid activated neurons automatically get this set to zero)</param>
/// <param name="_numFracBits">The number of fractional bits to use for the inputs for each neuron</param>
/// <param name="_numWeightUpperBits">The number of integer bits used for the weights for each neuron.</param>
/// <param name="_isClassifier">If true, a comparitor will be instantiatated at the output to each node, comparing the output layer nodes to the threshold value.</param>
/// <param name="_classifierThresholds">The threshold values for the output comparitors</param>
/// <param name="_weights">The list of weights read in for the neurons from WeightReader.readWeightsFromFile()</param>
/// <remark> For example, to intialize a classification neural network with three inputs, two hidden sigmoid-activated nodes, and one linear output node, use the following line:</remark>
/// <remarks> NeuralNetwork nn = new NeuralNetwork([3, 2, 1], [-1, -1], [..SIGMOID_POLY_APPROX, ..LINEAR], 4, 4, 4, true, [0.5], _weights);</remarks>
public AsyncNeuralNetwork(int[] _neuronCounts, double[] _biasValues, AsyncNeuron.NeuronActivationType[] _activationTypes, int _numIntBits, int _numFracBits, int _numWeightUpperBits, bool _isClassifier, double[] _classifierThresholds, List<double> _weights)
{
/*Copy member variables*/
this.neuronCounts = _neuronCounts;
this.biasValues = _biasValues;
this.activationTypes = _activationTypes;
this.numIntBits = _numIntBits;
this.numFracBits = _numFracBits;
this.numWeightUpperBits = _numWeightUpperBits;
this.classifierThresholds = _classifierThresholds;
this.isClassifier = _isClassifier;
/*Some useful variables for computing the signals*/
int numNeurons = 0;
int maxWeights = neuronCounts[0];
for (int i = 1; i < neuronCounts.Length; i++)
{
numNeurons += neuronCounts[i];
if (maxWeights < neuronCounts[i])
{
maxWeights = neuronCounts[i];
}
}
int offsetWidth = Utilities.getNumUnsignedBits(maxWeights);
int addrCounterWidth = Utilities.getNumUnsignedBits(_weights.Count);
/*Initialize memory signals and entities*/
this.wm = new WeightMemory(_numWeightUpperBits, _numFracBits, _weights);
this.load_sig = new Signal("load_sig", Utilities.VHDLDataType.STD_LOGIC_VECTOR, new String('0', numNeurons), numNeurons - 1, 0);
this.loadVal = new Signal("loadVal", Utilities.VHDLDataType.SIGNED_FIXED_POINT, null, numWeightUpperBits, -1 * numFracBits); //NOT -1 => signed
this.loadOffset = new Signal("loadOff", Utilities.VHDLDataType.UNSIGNED, new String('0', offsetWidth), offsetWidth - 1, 0);
this.addrCounter = new Signal("addrCounter", Utilities.VHDLDataType.UNSIGNED, new String('0', addrCounterWidth), addrCounterWidth - 1, 0);
this.ready_signal = new Signal("ready_sig", Utilities.VHDLDataType.STD_LOGIC, null, 0, 0);
this.finalLoadSignals = new Signal[numNeurons];
int arrCounter = 0;
for (int i = 1; i < neuronCounts.Length; i++)
{
for (int j = 0; j < neuronCounts[i]; j++)
{
this.finalLoadSignals[arrCounter] = new Signal(String.Format("finalLoad_{0}_{1}", i - 1, j), Utilities.VHDLDataType.STD_LOGIC, null, 0, 0);
arrCounter++;
}
}
this.loadValConv = new Signal("loadValConv", Utilities.VHDLDataType.STD_LOGIC_VECTOR, null, _numWeightUpperBits + _numFracBits, 0);
/*Compute the bus widths between neurons*/
int maxNeuronInput = Convert.ToInt32(Math.Pow(2, this.numIntBits)) - 1;
int currentNeuronInput = Convert.ToInt32(Math.Pow(2, this.numIntBits)) - 1;
this.intBusWidths = new int[numNeurons + this.neuronCounts[0]];
double[] maxValues = new double[numNeurons + this.neuronCounts[0]];
int neuronStart = 0;
int weightCounter = 0;
for (neuronStart = 0; neuronStart < this.neuronCounts[0]; neuronStart++)
{
maxValues[neuronStart] = (double)maxNeuronInput;
this.intBusWidths[neuronStart] = Utilities.getNumUnsignedBits(Convert.ToInt32(Math.Ceiling((double)maxNeuronInput)));
}
neuronStart = 0;
for (int i = 1; i < this.neuronCounts.Length; i++)
{
int[] currentNeuronMaxIntWidths = new int[this.neuronCounts[i]];
if (this.activationTypes[i - 1] == AsyncNeuron.NeuronActivationType.SIGMOID_POLY_APPROX)
{
for (int j = 0; j < this.neuronCounts[i]; j++)
{
maxValues[neuronStart + this.neuronCounts[i-1]] = 0.9999;
this.intBusWidths[neuronStart + this.neuronCounts[i-1]] = 0;
neuronStart++;
}
}
else if (this.activationTypes[i - 1] == AsyncNeuron.NeuronActivationType.NONE)
{
throw new Exception("YOU DUN FUCKED UP HERE TOO"); //debugging
}
else if (this.activationTypes[i - 1] == AsyncNeuron.NeuronActivationType.LINEAR)
{
for (int j = 0; j < this.neuronCounts[i]; j++)
{
double currentMax = 0;
int neuronIndex = neuronStart;
for (int k = 0; k < this.neuronCounts[i - 1]; k++)
{
currentMax += _weights[weightCounter] * maxValues[neuronIndex];
weightCounter++;
neuronIndex++;
}
maxValues[j + neuronStart + this.neuronCounts[i - 1]] = currentMax;
this.intBusWidths[j + neuronStart + this.neuronCounts[i - 1]] = Utilities.getNumUnsignedBits(Convert.ToInt32(Math.Ceiling(currentMax)));
}
neuronStart += this.neuronCounts[i - 1];
}
}
if (this.isClassifier)
{
for (int i = this.intBusWidths.Length - 1; (this.intBusWidths.Length - i) <= this.neuronCounts[this.neuronCounts.Length - 1]; i--)
this.intBusWidths[i] = 1;
}
/*Initialize neurons and their connectivities*/
this.neuronEntities = new AsyncNeuron[numNeurons];
this.neuron_outputs = new Signal[numNeurons];
this.uniqueNeuronEntities = new List<AsyncNeuron>();
var currentPorts = new List<Port>();
this.nnInputPorts = new Port[this.neuronCounts[0]];
neuronStart = 0;
for (int i = 0; i < this.neuronCounts[0]; i++)
{
this.nnInputPorts[i] = new Port(Port.portDirection.IN, String.Format("nnIn_{0}", i), Utilities.VHDLDataType.SIGNED_FIXED_POINT, this.intBusWidths[neuronStart], this.numFracBits * -1);
neuronStart++;
}
for (int i = 0; i < this.nnInputPorts.Length; i++)
{
Port P = this.nnInputPorts[i].copy();
P.rename(String.Format("in_{0}", i));
currentPorts.Add(P);
}
arrCounter = 0;
for (int i = 1; i < this.neuronCounts.Length; i++)
{
var lastPorts = currentPorts.ToArray();
currentPorts = new List<Port>();
if (this.activationTypes[i - 1] == AsyncNeuron.NeuronActivationType.SIGMOID_POLY_APPROX)
{
for (int j = 0; j < this.neuronCounts[i]; j++)
{
AsyncNeuron n = new AsyncNeuron(lastPorts, this.intBusWidths[neuronStart], this.numFracBits, this.numWeightUpperBits, AsyncNeuron.NeuronActivationType.SIGMOID_POLY_APPROX, String.Format("sig_poly_approx_neuron_{0}_{1}", i, 0));
neuronStart++;
if (j == 0)
{
/*Check for uniqueness*/
if (!this.uniqueNeuronEntities.Contains(n))
{
this.uniqueNeuronEntities.Add(n);
}
}
this.neuronEntities[arrCounter] = n;
Signal currentNeuronOutput = n.neuronOutput.toSignal(String.Format("out_{0}_{1}", i, j));
this.neuron_outputs[arrCounter] = currentNeuronOutput;
Port tempOut = n.neuronOutput.copy();
tempOut.rename(String.Format("in_{0}", j));
tempOut.setDirection(Port.portDirection.IN);
currentPorts.Add(tempOut);
arrCounter++;
}
}
else if (this.activationTypes[i - 1] == AsyncNeuron.NeuronActivationType.LINEAR)
{
for (int j = 0; j < this.neuronCounts[i]; j++)
{
AsyncNeuron n = new AsyncNeuron(lastPorts, this.intBusWidths[neuronStart], this.numFracBits, this.numWeightUpperBits, AsyncNeuron.NeuronActivationType.LINEAR, String.Format("linear_neuron_{0}_{1}", i, 0));
neuronStart++;
if (j == 0)
{
if (!this.uniqueNeuronEntities.Contains(n))
{
this.uniqueNeuronEntities.Add(n);
}
}
this.neuronEntities[arrCounter] = n;
Signal currentNeuronOutput = n.neuronOutput.toSignal(String.Format("out_{0}_{1}", i, j));
this.neuron_outputs[arrCounter] = currentNeuronOutput;
Port tempOut = n.neuronOutput.copy();
tempOut.rename(String.Format("in_{0}", j));
tempOut.setDirection(Port.portDirection.IN);
currentPorts.Add(tempOut);
arrCounter++;
}
}
}
/*Initialize outputs*/
this.nnOutputPorts = new Port[this.neuronCounts[this.neuronCounts.Length - 1]];
if (this.isClassifier)
{
for (int i = 0; i < this.neuronCounts[this.neuronCounts.Length - 1]; i++)
{
this.nnOutputPorts[i] = new Port(Port.portDirection.OUT, String.Format("out_{0}", i), Utilities.VHDLDataType.STD_LOGIC, 0, 0);
}
}
else
{
neuronStart -= this.neuronCounts[this.neuronCounts.Length - 1];
for (int i = 0; i < this.neuronCounts[this.neuronCounts.Length - 1]; i++)
{
this.nnOutputPorts[i] = new Port(Port.portDirection.OUT, String.Format("out{0}", i), Utilities.VHDLDataType.SIGNED_FIXED_POINT, this.intBusWidths[neuronStart], this.numFracBits);
neuronStart++;
}
}
/*Initialize other signals*/
this.ready = new Port(Port.portDirection.OUT, "ready", Utilities.VHDLDataType.STD_LOGIC, 0, 0);
this.reset = new Port(Port.portDirection.IN, "reset", Utilities.VHDLDataType.STD_LOGIC, 0, 0);
this.clk = new Port(Port.portDirection.IN, "clk", Utilities.VHDLDataType.STD_LOGIC, 0, 0);
return;
}
/// <summary>
/// Returns the name of the entity.
/// </summary>
/// <returns>The name of the entity</returns>
public override string getName()
{
return this.name;
}
/// <summary>
/// Returns the input ports of the entity.
/// </summary>
/// <returns>The input ports of the entity</returns>
public override Port[] getInputPorts()
{
Port[] inputs = new Port[this.nnInputPorts.Length + 2];
this.nnInputPorts.CopyTo(inputs, 0);
inputs[inputs.Length - 2] = this.clk;
inputs[inputs.Length - 1] = this.reset;
return inputs;
}
/// <summary>
/// Returns the output ports of the entity.
/// </summary>
/// <returns>The output ports of the entity</returns>
public override Port[] getOutputPorts()
{
Port[] outputs = new Port[this.nnOutputPorts.Length + 1];
this.nnOutputPorts.CopyTo(outputs, 0);
outputs[outputs.Length - 1] = this.ready;
return outputs;
}
/// <summary>
/// Returns the internal signals of the entity.
/// </summary>
/// <returns>The internal signals of the entity</returns>
public override Signal[] getInternalSignals()
{
var s = new Signal[6 + this.neuron_outputs.Length + this.finalLoadSignals.Length];
this.neuron_outputs.CopyTo(s, 0);
this.finalLoadSignals.CopyTo(s, this.neuron_outputs.Length);
int offset = this.neuron_outputs.Length + this.finalLoadSignals.Length;
s[offset] = this.ready_signal;
s[offset + 1] = this.load_sig;
s[offset + 2] = this.loadOffset;
s[offset + 3] = this.loadVal;
s[offset + 4] = this.loadValConv;
s[offset + 5] = this.addrCounter;
return s;
}
/// <summary>
/// Writes the .vhd files necessary to compile this entity.
/// All other necessary entities (i.e. neurons, thresholding functions, etc.) will also be written
/// when this function returns
/// </summary>
/// <param name="file">The file path in which to write the files (do NOT include "...name.vhd"</param>
/// <returns>true if the files were written successfully, false otherwise</returns>
public override bool writeVHDL(string file)
{
bool successfulWrite = false;
string entityFile = file + this.name + ".vhd";
using (StreamWriter sw = new StreamWriter(entityFile))
{
/*Compile all of the entities into one list*/
List<Entity> uniqueEntities = new List<Entity>();
uniqueEntities.Add(this.wm);
for (int i = 0; i < this.uniqueNeuronEntities.Count; i++)
{
uniqueEntities.Add(this.uniqueNeuronEntities[i]);
}
/*Write header*/
if (!((this.writeVHDLIncludes(sw)) && (this.writeVHDLEntity(sw)) && (this.writeArchitectureStatement(sw)) && (this.writeVHDLDependencies(sw, uniqueEntities)) && (this.writeVHDLSignals(sw))))
{
return false;
}
sw.WriteLine(String.Format("\t{0} <= {1};", this.ready.portName, this.ready_signal.name));
/*Write the memory signals*/
sw.WriteLine(String.Format("\twm: {0} port map", this.wm.name));
sw.WriteLine(String.Format("\t("));
sw.WriteLine(String.Format("\t\t{0} => std_logic_vector({1}),", this.wm.addr.portName, this.addrCounter.name));
sw.WriteLine(String.Format("\t\t{0} => {1},", this.wm.clk.portName, this.clk.portName));
sw.WriteLine(String.Format("\t\t{0} => {1}", this.wm.data.portName, this.loadValConv.name));
sw.WriteLine(String.Format("\t);"));
sw.WriteLine(String.Format(""));
sw.WriteLine(String.Format("\t{0} <= to_sfixed({1}, {0}'high, {0}'low);", this.loadVal.name, this.loadValConv.name));
sw.WriteLine("");
/*Write the neural network connections*/
int currentNeuron = 0;
int previousLayerStartingPoint = 0;
for (int i = 1; i < this.neuronCounts.Length; i++)
{
for (int j = 0; j < this.neuronCounts[i]; j++)
{
AsyncNeuron n = this.neuronEntities[currentNeuron];
sw.WriteLine(String.Format("\tNeuron_{0}_{1} : {2} port map", i, j, n.name));
sw.WriteLine(String.Format("\t("));
/*INPUT STATEMENTS*/
/*First row - use inputs*/
if (i == 1)
{
for (int k = 0; k < this.nnInputPorts.Length; k++)
{
sw.WriteLine(String.Format("\t\t{0} => {1},", n.neuronInputs[k].portName, this.nnInputPorts[k].portName));
}
}
/*Later row - use previous rows outputs*/
else
{
for (int k = 0; k < this.neuronEntities[currentNeuron].neuronInputs.Length; k++)
{
sw.WriteLine(String.Format("\t\t{0} => {1},", n.neuronInputs[k].portName, this.neuron_outputs[previousLayerStartingPoint + k].name));
}
}
sw.WriteLine(String.Format("\t\t{0} => {1}({2}),", n.loadEnablePort.portName, this.load_sig.name, currentNeuron)); //Load signal
sw.WriteLine(String.Format("\t\t{0} => {1},", n.loadValuePort.portName, this.loadVal.name)); //LoadVal signal
sw.WriteLine(String.Format("\t\t{0} => {1}({2} downto 0),", n.loadOffsetPort.portName, this.loadOffset.name, n.loadOffsetPort.top)); //LoadOff signal
sw.WriteLine(String.Format("\t\t{0} => {1},", n.finalLoadPort.portName, this.finalLoadSignals[currentNeuron].name)); //FinalLoad signal
sw.WriteLine(String.Format("\t\t{0} => {1},", n.loadClkPort.portName, this.clk.portName)); //Clk signal
sw.WriteLine(String.Format("\t\t{0} => {1}", n.neuronOutput.portName, this.neuron_outputs[currentNeuron].name)); //Output signal
sw.WriteLine("\t);");
sw.WriteLine("");
currentNeuron++;
}
if (i != 1)
{
previousLayerStartingPoint += this.neuronCounts[i - 1];
}
}
/*Load process*/
sw.WriteLine(String.Format("\tprocess ({0})", this.clk.portName));
sw.WriteLine(String.Format("\tbegin"));
sw.WriteLine(String.Format("\t\tif (rising_edge({0}) and ( ({1} = '1') or ({2} = '0') ) ) then", this.clk.portName, this.reset.portName, this.ready_signal.name));
sw.WriteLine(String.Format("\t\t\tif ({0} = '1') then", this.reset.portName));
sw.WriteLine(String.Format("\t\t\t\t{0} <= '0';", this.ready_signal.name));
sw.WriteLine(String.Format("\t\t\t\t{0} <= (others => '0');", this.loadOffset.name));
sw.WriteLine(String.Format("\t\t\t\t{0} <= (others => '0');", this.addrCounter.name));
sw.WriteLine(String.Format("\t\t\t\t{0} <= (0 => '1', others => '0');", this.load_sig.name));
for (int i = 0; i < this.finalLoadSignals.Length; i++)
{
sw.WriteLine(String.Format("\t\t\telsif ({0} = '1') then", this.finalLoadSignals[i].name));
if (i != this.finalLoadSignals.Length - 1)
sw.WriteLine(String.Format("\t\t\t\t{0} <= ({1} => '1', others => '0');", this.load_sig.name, i + 1));
else
sw.WriteLine(String.Format("\t\t\t\t{0} <= (others => '0');", this.load_sig.name));
sw.WriteLine(String.Format("\t\t\t\t{0} <= (others => '0');", this.loadOffset.name));
}
sw.WriteLine(String.Format("\t\t\telse"));
sw.WriteLine(String.Format("\t\t\t\t{0} <= {0} + 1;", this.loadOffset.name));
sw.WriteLine(String.Format("\t\t\t\t{0} <= {0} + 1;", this.addrCounter.name));
sw.WriteLine(String.Format("\t\t\tend if;"));
sw.WriteLine(String.Format(""));
sw.WriteLine(String.Format("\t\t\tif ({0} = {1}) then", this.addrCounter.name, wm.weights_str.Count));
sw.WriteLine(String.Format("\t\t\t\t{0} <= '1';", this.ready_signal.name));
sw.WriteLine(String.Format("\t\t\tend if;"));
sw.WriteLine(String.Format("\t\tend if;"));
sw.WriteLine(String.Format("\tend process;"));
sw.WriteLine("");
/*Write the comparitors for classification problems*/
if (this.isClassifier)
{
int currentOutputNeuronIndex = this.neuronEntities.Length - this.neuronCounts[this.neuronCounts.Length - 1];
int outputIndex = 0;
while (currentOutputNeuronIndex < this.neuronEntities.Length)
{
Signal current_out = this.neuron_outputs[currentOutputNeuronIndex];
sw.WriteLine(String.Format("\tprocess ({0})", current_out.name));
sw.WriteLine(String.Format("\tbegin"));
sw.WriteLine(String.Format("\t\tif ({0} > to_sfixed({1}, {0})) then", current_out.name, this.classifierThresholds[outputIndex]));
sw.WriteLine(String.Format("\t\t\t{0} <= '1';", this.nnOutputPorts[outputIndex].portName));
sw.WriteLine(String.Format("\t\telse"));
sw.WriteLine(String.Format("\t\t\t{0} <= '0';", this.nnOutputPorts[outputIndex].portName));
sw.WriteLine(String.Format("\t\tend if;"));
sw.WriteLine(String.Format("\tend process;"));
currentOutputNeuronIndex++;
outputIndex++;
}
}
/*Write the raw signal outputs for regression problems*/
else
{
int currentOutputNeuronIndex = this.neuronEntities.Length - this.neuronCounts[this.neuronCounts.Length - 1];
int outputIndex = 0;
while (currentOutputNeuronIndex < this.neuronEntities.Length)
{
Signal current_out = this.neuron_outputs[currentOutputNeuronIndex];
sw.WriteLine(String.Format("\t{0} <= {1}", this.nnOutputPorts[outputIndex].portName, current_out.name));
sw.WriteLine("");
currentOutputNeuronIndex++;
outputIndex++;
}
}
/*Write dependent entities*/
foreach (Entity e in uniqueEntities)
{
if (!e.writeVHDL(file))
{
return false;
}
}
successfulWrite = this.writeVHDLFooter(sw);
}
return successfulWrite;
}
}
}
|
using BLL;
using Entidades;
using Entidades.Vistas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ApiMovil.Controllers
{
[RoutePrefix("api/DatosBasicos")]
public class DatosBasicosController : ApiController
{
[Route("Vigencias")]
public List<vVIGENCIAS> GetS()
{
VigenciasBLL o = new VigenciasBLL();
return o.Gets();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace News.Web.Controllers
{
public class RestaurantController : Controller
{
List<News.Web.Models.restaurant> RESTS = new List<Models.restaurant>();
// GET: Restaurant
public ActionResult Index()
{
RESTS.Add
(
new Models.restaurant
{
addr = "ההסתדרות 4, פתח תקווה. ",
l = Models.restaurant.type.falafel,
menu = new List<Models.meal>
{ new Models.meal
{
name = "מנת פלאפל",
price = 17
},
new Models.meal
{
name = "קולה חצי ליטר",
price = 7
}
}
}
);
RESTS.Add
(
new Models.restaurant
{
l = Models.restaurant.type.sushi,
name = "frangelico",
addr = "העצמאות 65, פתח תקווה",
menu = new List<Models.meal>
{ new Models.meal
{
name = "מאקי דג בהרכבה",
price = 26
},
new Models.meal
{
name = "I/O בהרכבה",
price = 30
},
new Models.meal
{
name = "קולה חצי ליטר",
price = 9
}
}
}
);
return View(RESTS);
}
public ActionResult add()
{
RESTS.Add(
new Models.restaurant
{
name = Request["name"]
}
);
return View("Index", RESTS);
}
}
} |
using IClips.Domain.Context.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace IClips.Infrastructure.ViewModel
{
public class FuncionarioViewModel
{
public int? Id { get; set; }
public int? UsuarioId { get; set; }
[Required(ErrorMessage = "Insira um nome")]
[StringLength(30, ErrorMessage = "O nome deve ter entre 2 e 30 caracteres", MinimumLength = 2)]
public string Nome { get; set; }
[Required(ErrorMessage = "Insira o login")]
[StringLength(50, ErrorMessage = "O login deve ter entre 6 e 30 caracteres", MinimumLength = 6)]
public string Login { get; set; }
[Required(ErrorMessage = "Insira uma senha")]
[System.ComponentModel.DataAnnotations.Compare("ConfirmaSenha", ErrorMessage = "As senhas não conferem")]
[StringLength(50, ErrorMessage = "A senha deve ter entre 6 e 50 caracteres")]
[DataType(DataType.Password)]
public string Senha { get; set; }
[Required(ErrorMessage = "Insira a confirmação de senha")]
[StringLength(50, ErrorMessage = "A senha deve ter entre 6 e 50 caracteres")]
[DataType(DataType.Password)]
[Display(Name = "Confirmar senha")]
public string ConfirmaSenha { get; set; }
[Required(ErrorMessage = "Insira o departamento")]
[Display(Name = "Departamento")]
public int DepartamentoId { get; set; }
public string DepartamentoString { get; set; }
[Required(ErrorMessage = "Insira o email")]
[DataType(DataType.EmailAddress)]
[MaxLength(50, ErrorMessage = ("O email deve ter no máximo 50 caracteres"))]
[Display(Name = "E-mail")]
public string Email { get; set; }
[Required(ErrorMessage = "Insira a data de nascimento")]
[DataType(DataType.Date, ErrorMessage = "Data de nascimento em formato inválido! utilize dd/mm/aaaa")]
[Display(Name = "Data de nascimento")]
public DateTime DataNascimento { get; set; }
//[Required(ErrorMessage = "Insira o telefone primário")]
[MaxLength(15, ErrorMessage = "O telefone primário deve ter no máximo 11 caracteres")]
[Display(Name = "Telefone primário")]
public string TelPrimario { get; set; }
[MaxLength(11, ErrorMessage = "O telefone secundário deve ter no máximo 11 caracteres")]
[Display(Name = "Telefone secundário")]
public string TelSecundario { get; set; }
public bool AcessoIclips { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ProyectoWebBlog.Models.ViewModels
{
public class UsuarioModel
{
[Required]
[Display(Name = "Número de identificación")]
public int Id { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Correo electrónico")]
public String Correo { get; set; }
[Required]
[Display(Name = "Nombre")]
public String Nombre { get; set; }
[Required]
[Display(Name = "Primer Apellido")]
public String PrimerApellido { get; set; }
[Required]
[Display(Name = "Segundo Apellido")]
public String SegundoApellido { get; set; }
[Required]
[DataType(DataType.Password)]
public string Contrasena { get; set; }
public String Rol { get; set; }
}
} |
namespace Entoarox.Framework
{
public delegate T AssetLoader<T>(string assetName);
public delegate void AssetInjector<T>(string assetName, ref T asset);
public delegate void ReceiveMessage(string modID, string channel, string message, bool broadcast);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Vapoteur.Models
{
public class Box
{
public int Id { get; set; }
public string Marque{ get; set; }
public int PuissanceMax{ get; set; }
public List<Accumulateur> Accumulateurs { get; set; }
}
} |
using System;
using System.Runtime.Serialization.Formatters;
class MatrixOfPalindromes
{
static void Main()
{
Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!");
while (true)
{
Console.Write("How many rows : ");
uint uiRow = uint.Parse(Console.ReadLine());
Console.Write("How many columns : ");
uint uiCol = uint.Parse(Console.ReadLine());
char cFirstCh = '\u0061';
for (int i = 0; i < uiRow; i++)
{
for (int j = 0; j < uiCol; j++)
{
if (j == 0)
{
Console.Write("{0}{1}{2} ",(char)(cFirstCh + i),(char)(cFirstCh + i),(char)(cFirstCh + i));
}
else
{
Console.Write("{0}{1}{2} ", (char)(cFirstCh + i), (char)(cFirstCh + i + j), (char)(cFirstCh + i));
}
}
Console.WriteLine();
}
}
}
} |
using Acr.UserDialogs;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Explayer.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AppPlayerPage : ContentPage
{
public AppPlayerPage ()
{
NavigationPage.SetHasNavigationBar(this, false);
InitializeComponent ();
}
public AppPlayerPage(string appName, string preferredVersion)
{
NavigationPage.SetHasNavigationBar(this, false);
InitializeComponent();
Webview.Source = $"http://127.0.0.1:8787/{appName}/{preferredVersion}/index.html";
// Show toast
var toastConfig = new ToastConfig($"Loading {appName} v{preferredVersion}...")
.SetDuration(4000);
UserDialogs.Instance.Toast(toastConfig);
}
//private void OnGoButtonClicked(object sender, EventArgs e)
//{
// webview.Source = addressEntry.Text;
//}
protected override bool OnBackButtonPressed()
{
Device.BeginInvokeOnMainThread(async () => {
var result = await this.DisplayAlert("Leave Session?",
"You will lose all unsaved data from this session. " +
"Click anywhere to dismiss this message and remain here.",
"Yes, exit and lose all data", "No, stay here");
if (result) await this.Navigation.PopAsync(); // or anything else
});
return true;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using TemplateFramework;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var fileContents = Program.GetFileContent(args);
var configs = Program.ParseConfig(fileContents);
// check config file exist
if (!configs.Any())
{
Console.WriteLine("No config readed. Execute without result.");
return;
}
// init template framework
TemplateFramework.Global.Init(configs);
TemplateFramework.Global.Execute();
Console.WriteLine("Execute completed. Please press ENTER.");
}
private static IEnumerable<string> GetFileContent(IEnumerable<string> args)
{
// get config-file paths
IEnumerable<string> paths = PathHelper.GetConfigPaths(args);
foreach (string path in paths)
{
string configText = File.ReadAllText(path);
yield return configText;
}
}
private static IEnumerable<FileSettingText> ParseConfig(IEnumerable<string> configContents)
{
foreach(string configTxt in configContents)
{
FileSettingText result = null;
try
{
result = JsonConvert.DeserializeObject<FileSettingText>(configTxt);
}
catch (Exception ex)
{
Console.WriteLine("Parse config file error: ");
Console.WriteLine(ex.ToString());
}
if(result != null)
yield return result;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Spool.Harlowe
{
class Array : DataCollection, IList<Data>
{
public static DataType Type { get; } = new DataType(typeof(Array));
public Array(IEnumerable<Data> values) : base(values) {}
public Data this[int index]
{
get => GetIndex(index);
set => throw new NotSupportedException();
}
protected override bool SupportsIndexing => true;
public override bool Equals(Data other) => other is Array a && base.Equals(other);
class Index : Mutator
{
private readonly Array parent;
private readonly int idx;
public Index(Array parent, int idx)
{
this.parent = parent;
this.idx = idx;
}
public Data Delete() => new Array(parent.Where((_, i) => i != idx));
public Data Set(Data value) => new Array(parent.Select((o, i) => i == idx ? value : o));
}
public override Mutator MutableMember(Data member)
{
return member switch {
Number idx => idx.Value > Count ? throw new IndexOutOfRangeException() : new Index(this, (int)idx.Value - 1),
_ => base.MutableMember(member)
};
}
protected override Data Create(IEnumerable<Data> values) => new Array(values);
new public int IndexOf(Data item) => base.IndexOf(item);
void IList<Data>.Insert(int index, Data item) => throw new NotSupportedException();
void IList<Data>.RemoveAt(int index) => throw new NotSupportedException();
}
} |
using Android.App;
using Android.Content;
using Android.Views;
using Android.Widget;
using Barebone.Common.Enum;
using Barebone.Common.Services.Interfaces;
using Plugin.CurrentActivity;
using System;
namespace Barebone.Droid.Services
{
public class UserInteractionService : IUserInteractionService
{
Toast _toast;
protected Context Context => CrossCurrentActivity.Current.Activity;
public UserInteractionService() { }
public void ShowAlert(string title, string message, Action onOkAction = null)
{
Application.SynchronizationContext.Post(
ignored =>
{
var dialog = BuildNewDialog(title, message);
dialog.SetPositiveButton("Ok", delegate { onOkAction?.Invoke(); })
.SetCancelable(false)
.Show();
},
null);
}
public void ShowAlert(Exception exception, Action onOkAction = null)
{
ShowAlert("Error", exception.Message, onOkAction);
}
public void ShowConfirmationDialog(string message, Action onYesAction, Action onNoAction = null)
{
Application.SynchronizationContext.Post(
ignored =>
{
var dialog = BuildNewDialog("Confirm", message);
dialog
.SetPositiveButton("Yes", delegate { onYesAction?.Invoke(); })
.SetNegativeButton("No", delegate { onNoAction?.Invoke(); })
.SetCancelable(false)
.Show();
},
null);
}
public void ShowConfirmationDialog(string title, string message, string yesMessage, Action onYesAction, string noMessage = null, Action onNoAction = null)
{
Application.SynchronizationContext.Post(
ignored =>
{
var dialog = BuildNewDialog(title, message);
dialog
.SetPositiveButton(yesMessage.ToUpper(), delegate { onYesAction?.Invoke(); })
.SetNegativeButton(string.IsNullOrWhiteSpace(noMessage) ? "No" : noMessage.ToUpper(), delegate { onNoAction?.Invoke(); })
.SetCancelable(false)
.Show();
},
null);
}
public void ShowToast(string message, bool bigToast = false,ToastDuration duration = ToastDuration.Short)
=> Application.SynchronizationContext.Post(ignored => PostToast(message, duration, bigToast), null);
AlertDialog.Builder BuildNewDialog(string title, string message)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(Context);
if (!string.IsNullOrEmpty(title)) { dialog.SetTitle(title); }
if (!string.IsNullOrEmpty(message)) { dialog.SetMessage(message); }
return dialog;
}
void PostToast(string message, ToastDuration duration, bool bigToast = false)
{
_toast?.Cancel();
_toast = Toast.MakeText(Context, message, duration == ToastDuration.Long ? ToastLength.Long : ToastLength.Short);
if (bigToast)
{
View toastView = _toast.View;
TextView toastMessage = (TextView)toastView.FindViewById(Android.Resource.Id.Message);
toastMessage.TextSize = 20;
toastMessage.SetTextColor(Android.Graphics.Color.White);
toastMessage.Gravity = GravityFlags.Center;
toastMessage.CompoundDrawablePadding = 16;
}
_toast.Show();
}
}
} |
using Abp.Authorization;
namespace MyProject.Schools {
public class MyAuthorizationProvider : AuthorizationProvider {
//权限认证
public override void SetPermissions (IPermissionDefinitionContext context) {
var administration = context.CreatePermission ("Administration");
var userManagement = administration.CreateChildPermission ("Administration.UserManagement");
userManagement.CreateChildPermission ("Administration.UserManagement.CreateUser");
var roleManagement = administration.CreateChildPermission ("Administration.RoleManagement");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestPlayerPick : MonoBehaviour
{
public RigidBodyMovement rbm;
private Rigidbody body;
public GameObject conch, cup, can, initialAnchor, tailOut, tailIn, pickParticles;
public Transform newCapsulePos;
private AudioSource playerAudioSource;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody>();
playerAudioSource = rbm.gameObject.GetComponent<AudioSource>();
initialAnchor = transform.parent.Find("InitialAnchor").gameObject;
}
// Update is called once per frame
void Update()
{
if (rbm.GetConchCount() == 0 && !tailOut.activeInHierarchy) {
tailOut.SetActive(true);
tailIn.SetActive(false);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "PickUpPoint")
{
GameObject target = other.gameObject;
PickUpScript pus = target.GetComponent<PickUpScript>();
if (pus != null) {
playerAudioSource.Play();
Instantiate(pickParticles, target.transform.position,Quaternion.identity);
if (tailOut.activeInHierarchy) {
tailOut.SetActive(false);
tailIn.SetActive(true);
gameObject.transform.position = newCapsulePos.position;
}
GameObject toSpawn = null;
switch (pus.GetRoot().tag) {
case "Conch": {
toSpawn = conch;
break;
}
case "Cup":
{
toSpawn = cup;
break;
}
case "Can":
{
toSpawn = can;
break;
}
}
Destroy(pus.GetRoot());
GameObject lastShell = rbm.GetLastConch();
Transform conchAnchor;
if (lastShell != null) conchAnchor = lastShell.GetComponent<ConchScript>().GetAnchor().transform;
else
{
conchAnchor = initialAnchor.transform;
}
GameObject addedConch = Instantiate(toSpawn, conchAnchor.position, conchAnchor.rotation);
addedConch.transform.parent = conchAnchor;
rbm.AddConch(addedConch);
}
}
}
public void DoPickUp()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace MageTwinstick
{
/// <summary>
/// used to find the mouse position
/// </summary>
static class Mouse
{
////fields to contain the mouse position
public static float X { get; set; }
public static float Y { get; set; }
}
}
|
using System;
using System.Linq;
using DelftTools.Shell.Core;
using DelftTools.Shell.Core.Workflow;
using DelftTools.Utils.Collections.Generic;
using NUnit.Framework;
using Rhino.Mocks;
namespace DelftTools.Tests.Core
{
[TestFixture]
public class ModelDataItemTest
{
readonly MockRepository mocks = new MockRepository();
[Test]
public void LinkToModel()
{
var linkedCounter = 0;
var unlinkedCounter = 0;
var model1 = mocks.Stub<IModel>();
var model2 = mocks.Stub<IModel>();
var modelDataItem = new ModelDataItem();
model1.DataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
model2.DataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
modelDataItem.RequiredDataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
modelDataItem.Linked += delegate { linkedCounter++; };
modelDataItem.Unlinked += delegate { unlinkedCounter++; };
Assert.IsFalse(modelDataItem.IsLinked);
modelDataItem.LinkToModel(model1);
Assert.AreEqual(1, linkedCounter);
Assert.AreEqual(0, unlinkedCounter);
Assert.IsTrue(modelDataItem.IsLinked);
modelDataItem.LinkToModel(model1);
// The link already exists => nothing should happen
Assert.AreEqual(1, linkedCounter);
Assert.AreEqual(0, unlinkedCounter);
Assert.IsTrue(modelDataItem.IsLinked);
modelDataItem.LinkToModel(model2);
// The previous model should be unlinked before linking again
Assert.AreEqual(2, linkedCounter);
Assert.AreEqual(1, unlinkedCounter);
Assert.IsTrue(modelDataItem.IsLinked);
}
[Test]
public void UnlinkFromModel()
{
var counter = 0;
var model = mocks.Stub<IModel>();
var modelDataItem = new ModelDataItem();
model.DataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
modelDataItem.RequiredDataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
modelDataItem.Unlinked += delegate { counter++; };
Assert.IsFalse(modelDataItem.IsLinked);
modelDataItem.LinkToModel(model);
Assert.IsTrue(modelDataItem.IsLinked);
modelDataItem.UnlinkFromModel();
Assert.AreEqual(1, counter);
Assert.IsFalse(modelDataItem.IsLinked);
}
[Test]
public void ModelCannotBeLinkedIfRequiredDataItemIsMissing()
{
var model = mocks.Stub<IModel>();
var modelDataItem = new ModelDataItem();
model.DataItems = new EventedList<IDataItem>();
modelDataItem.RequiredDataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
Assert.IsFalse(modelDataItem.IsLinked);
var exceptionThrown = false;
try
{
modelDataItem.LinkToModel(model);
}
catch (Exception e)
{
exceptionThrown = true;
Assert.AreEqual("Can't create link: no matching data is found in the source model for the target item with name \"Name\"", e.Message);
}
Assert.IsTrue(exceptionThrown);
Assert.IsFalse(modelDataItem.IsLinked);
}
[Test]
public void ModelIsUnlinkedIfRequiredDataItemLinkIsRemoved()
{
var counter = 0;
var model = mocks.Stub<IModel>();
var modelDataItem = new ModelDataItem();
model.DataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
modelDataItem.RequiredDataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
modelDataItem.Unlinked += delegate { counter++; };
Assert.IsFalse(modelDataItem.IsLinked);
modelDataItem.LinkToModel(model);
Assert.IsTrue(modelDataItem.IsLinked);
model.DataItems.First().LinkedBy.First().Unlink();
Assert.AreEqual(1, counter);
Assert.IsFalse(modelDataItem.IsLinked);
}
[Test]
public void ModelDataItemNameDoesNotChangeWhileLinkingAndUnlinking()
{
var model = mocks.Stub<IModel>();
var modelDataItem = new ModelDataItem { Name = "Expected name" };
model.DataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
modelDataItem.RequiredDataItems = new EventedList<IDataItem> { new DataItem(new object(), "Name", typeof(object), DataItemRole.None, "Tag") };
modelDataItem.LinkToModel(model);
Assert.AreEqual("Expected name", modelDataItem.Name);
modelDataItem.UnlinkFromModel();
Assert.AreEqual("Expected name", modelDataItem.Name);
}
}
} |
using System.Collections.Generic;
using Mastermind;
using Mastermind.NET.Models;
using Mastermind.NET.Validation;
using Moq;
using NUnit.Framework;
namespace MastermindTests
{
public class GuessValidatorTests
{
[Test]
public void ExactGuessShouldSetVictoryCondition()
{
var stateMock = GameStateMockBuilder(new int[] { 1, 2, 3, 4 });
var guess = new List<int> { 1, 2, 3, 4 };
var validation = GuessValidator.Validate(stateMock.Object, guess);
Assert.IsTrue(validation.VictoryCondition);
}
[Test]
public void IncorrectGuessShouldNotTriggerVictoryCondition()
{
var stateMock = GameStateMockBuilder(new int[] { 1, 2, 3, 4 });
var guess = new List<int> { 1, 1, 2, 2 };
var validation = GuessValidator.Validate(stateMock.Object, guess);
Assert.IsFalse(validation.VictoryCondition);
}
[Test]
public void MatchingElementsAtMatchingPositionsShouldReturnPlus()
{
var stateMock = GameStateMockBuilder(new int[] { 1, 2, 3, 4 });
var guess = new List<int> { 1, 2, 5, 6 };
var validation = GuessValidator.Validate(stateMock.Object, guess);
Assert.AreEqual(validation.GuessResult, "++");
}
[Test]
public void MatchingElementsAtWrongPositionsShouldReturnMinus()
{
var stateMock = GameStateMockBuilder(new int[] { 1, 2, 3, 4 });
var guess = new List<int> { 4, 3, 2, 1 };
var validation = GuessValidator.Validate(stateMock.Object, guess);
Assert.AreEqual(validation.GuessResult, "----");
}
[Test]
public void MixOfCorrectAndIncorrectPositionsI()
{
var stateMock = GameStateMockBuilder(new int[] { 1, 2, 3, 4 });
var guess = new List<int> { 4, 2, 3, 1 };
var validation = GuessValidator.Validate(stateMock.Object, guess);
Assert.AreEqual("++--", validation.GuessResult);
}
[Test]
public void MixOfCorrectAndIncorrectPositionsII()
{
var stateMock = GameStateMockBuilder(new int[] { 1, 2, 3, 4 });
var guess = new List<int> { 1, 3, 2, 4 };
var validation = GuessValidator.Validate(stateMock.Object, guess);
Assert.AreEqual("++--", validation.GuessResult);
}
[Test]
public void IncorrectPositionTestI()
{
var stateMock = GameStateMockBuilder(new int[] { 6, 5, 4, 3 });
var guess = new List<int> { 1, 2, 3, 5 };
var validation = GuessValidator.Validate(stateMock.Object, guess);
Assert.AreEqual("--", validation.GuessResult);
}
[Test]
public void AdditionalTestCases()
{
var stateMock = GameStateMockBuilder(new int[] { 3, 1, 1, 1 });
var guess = new List<int> { 1, 1, 2, 2 };
Assert.AreEqual("--", GuessValidator.Validate(stateMock.Object, guess).GuessResult);
}
#region mock builder
// Quick helper method since I'm writing the same game state mocks a bunch
private Mock<IGameState> GameStateMockBuilder(int[] generated)
{
var stateMock = new Mock<IGameState>();
stateMock.Setup(m => m.Numbers).Returns(new List<int>(generated));
return stateMock;
}
#endregion
}
}
|
using System;
using System.Linq;
using ICSharpCode.Core;
using MyLoadTest.LoadRunnerSvnAddin.Gui;
namespace MyLoadTest.LoadRunnerSvnAddin.Commands
{
public class CheckoutCommand : AbstractMenuCommand
{
public override void Run()
{
SvnGuiWrapper.ShowCheckoutDialog(null);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestJump : MonoBehaviour
{
float time = 0;
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.left * 1 * Time.deltaTime);
if (time >3)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, 4);
time = 0;
}
time += Time.deltaTime;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Foundation;
using ResidentAppCross.iOS.Views.Attributes;
using ResidentAppCross.ViewModels.Screens;
using UIKit;
namespace ResidentAppCross.iOS.Views
{
[Register("NotificationDetailsFormView")]
[NavbarStyling]
[StatusBarStyling]
public class NotificationDetailsFormView : BaseForm<NotificationDetailsFormViewModel>
{
private UIWebView _webView;
public UIWebView WebView
{
get
{
if (_webView == null)
{
_webView = new UIWebView().WithHeight(600,1000);
_webView.TranslatesAutoresizingMaskIntoConstraints = false;
}
return _webView;
}
set { _webView = value; }
}
public override void BindForm()
{
base.BindForm();
}
public override void GetContent(List<UIView> content)
{
base.GetContent(content);
content.Add(WebView);
}
}
}
|
using Uintra.Features.Links.Models;
namespace Uintra.Features.Links
{
public interface IErrorLinksService
{
UintraLinkModel GetNotFoundPageLink();
UintraLinkModel GetForbiddenPageLink();
}
}
|
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DataAccesLayer.Repositories
{
public class PcRepository : IPcRepository<Podcast>
{
PodcastDataManager podcastDataManager;
List<Podcast> podcastList;
List<Episode> episodeList;
public PcRepository()
{
podcastList = new List<Podcast>();
episodeList = new List<Episode>();
podcastDataManager = new PodcastDataManager();
podcastList = GetAll();
}
//Skapar en ny podcast och sparar ändringarna
public void New(Podcast podcast)
{
podcastList = GetAll();
podcastList.Add(podcast);
SaveAllChanges();
}
//Sparar ändringarna
public void Save(int index, Podcast podcast)
{
if (index >= 0)
{
podcastList[index] = podcast;
}
SaveAllChanges();
}
//Raderar podcast och sparar ändringarna
public void Delete(int index)
{
podcastList.RemoveAt(index);
SaveAllChanges();
}
//Sparar alla ändringar och lägger in dem i ett lokalt xml dokument
public async void SaveAllChanges()
{
await Task.Run(() =>
{
podcastDataManager.Serialize(podcastList);
});
}
//Hämtar alla podcasts från ett lokalt xml dokument
public List<Podcast> GetAll()
{
List<Podcast> podcastListToBeReturned = new List<Podcast>();
try
{
podcastListToBeReturned = podcastDataManager.Deserialize();
}
catch (Exception)
{
}
return podcastListToBeReturned;
}
//Hämtar podcast via ett namn
public Podcast GetByNamn(string namn)
{
return GetAll().First(p => p.Namn.Equals(namn));
}
//Hämtar podcast via ett index
public string GetName(int index)
{
return GetAll()[index].Namn;
}
//Sätter podcastlistan till valfri lista
public void SetPodcastList(List<Podcast> podcasts)
{
podcastList = podcasts;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class StageManager : MonoBehaviour
{
private List<Character> characterList = new List<Character>();
private Character selectedCharacter = null;
[SerializeField]
private Map map;
void Update()
{
if(map.canGetTilePos)
{
//Debug.Log(map.tileWorldPos);
//Debug.Log(character.transform.position);
selectedCharacter.StartMoing(Vector3.Normalize(new Vector3(map.tileWorldPos.x, map.tileWorldPos.y + 0.6f) - selectedCharacter.transform.position),
new Vector3(map.tileWorldPos.x, map.tileWorldPos.y + 0.6f, selectedCharacter.transform.position.z));
map.canGetTilePos = false;
UnSelectCharacter();
}
}
private void UnSelectCharacter()
{
if(selectedCharacter != null)
{
selectedCharacter.pointer.SetActive(false);
selectedCharacter = null;
}
}
public void SelectCharacter(Character _character)
{
UnSelectCharacter();
selectedCharacter = _character;
//Debug.Log(character.spd);
selectedCharacter.pointer.SetActive(true);
}
public bool IsCharSelected()
{
if(selectedCharacter == null)
{
return false;
}
else
{
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using Autofac;
using XH.Infrastructure.Web;
namespace XH.Presentation.Admin.App_Start
{
public class BackofficeModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(context =>
{
return new SiteSetting
{
ApiDomain = ConfigurationManager.AppSettings[AppSettingConstants.ApiDomain],
MediaApiDomain = ConfigurationManager.AppSettings[AppSettingConstants.MediaApiDomain],
UnobtrusiveJavaScriptEnabled = ConfigurationManager.AppSettings[AppSettingConstants.UnobtrusiveJavaScriptEnabled] == "true",
BaiduMapAK = ConfigurationManager.AppSettings[AppSettingConstants.BaiduMapAK]
};
}).SingleInstance();
base.Load(builder);
}
}
} |
using ParrisConnection.DataLayer.Dtos;
using System;
using System.ComponentModel.DataAnnotations;
namespace ParrisConnection.DataLayer.Entities.Profile
{
public class Employer : IEmployer
{
public int Id { get; set; }
public string UserId { get; set; }
[StringLength(255)]
public string Name { get; set; }
[StringLength(255)]
public string JobTitle { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BusinessObjects;
namespace DataAccess
{
class CommentLikeDAO
{
private static CommentLikeDAO instance = null;
private static readonly object instanceLock = new object();
public static CommentLikeDAO Instance
{
get
{
lock (instanceLock)
{
if (instance == null)
{
instance = new CommentLikeDAO();
}
return instance;
}
}
}
//-------------------------
public CommentLike GetCommentLike(string username, int commentId)
{
CommentLike commentLike = null;
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
commentLike =
context.CommentLikes.SingleOrDefault(l => l.Username.Equals(username) && l.CommentId == commentId);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return commentLike;
}
public IEnumerable<CommentLike> GetCommentLikeByCommentId(int commendId)
{
var commentLikeList = new List<CommentLike>();
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
commentLikeList = context.CommentLikes.Where(l => l.CommentId == commendId).ToList();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return commentLikeList;
}
public void AddCommentLike(CommentLike like)
{
try
{
CommentLike _like = GetCommentLike(like.Username, like.CommentId);
if (_like == null)
{
using var context = new PRN211_OnlyFunds_CopyContext();
context.CommentLikes.Add(like);
context.SaveChanges();
}
else
{
throw new Exception("Already liked");
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public void DeleteLike(string username, int postId)
{
try
{
CommentLike like = GetCommentLike(username, postId);
if (like != null)
{
using var context = new PRN211_OnlyFunds_CopyContext();
context.CommentLikes.Remove(like);
context.SaveChanges();
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public CommentLike CheckCommentLike(string username, int commentId)
{
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
CommentLike like =
context.CommentLikes.FirstOrDefault(l => l.Username.Equals(username) && l.CommentId == commentId);
return like;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}
|
namespace Ach.Fulfillment.Scheduler
{
using Ach.Fulfillment.Scheduler.Common;
using Ach.Fulfillment.Scheduler.Configuration;
using Topshelf;
public static class Program
{
public static void Main(string[] args)
{
var host = HostFactory.New(x =>
{
x.Service<QuartzServer>(s =>
{
s.SetServiceName("quartz.server");
s.ConstructUsing(builder =>
{
var server = new QuartzServer();
server.Initialize();
return server;
});
s.WhenStarted(server => server.Start());
s.WhenPaused(server => server.Pause());
s.WhenContinued(server => server.Resume());
s.WhenStopped(server => server.Stop());
});
x.RunAsLocalSystem();
x.SetDescription(Registry.ServiceDescription);
x.SetDisplayName(Registry.ServiceDisplayName);
x.SetServiceName(Registry.ServiceName);
});
host.Run();
}
}
}
|
using TextBox_Validation_MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TextBox_Validation_MVC.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
var appInfo = new AppInformation();
ViewBag.Message = appInfo;
return View();
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
return View(); // Examine with breakpoint
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using WebApplication1.Models;
namespace WebApplication1.DAL
{
public class BookInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<BookService>
{
protected override void Seed(BookService service)
{
var books = new List<Book>
{
new Book{Book_Id=2,Book_Name="Java",Book_Author="Mr.Chen",Book_BoughtDate=DateTime.Parse("2005-09-01"),Book_Publisher="NKUST",Book_Note="Java Class Beginning ",Book_Status="A",Book_Keeper="Tenso",Create_Date=DateTime.Parse("2010-10-09"),Create_User="HowHow",Modify_Date=DateTime.Parse("2013-03-01"),Modify_User="HowHow"},
new Book{Book_Id=3,Book_Name="人類學",Book_Author="Duo",Book_BoughtDate=DateTime.Parse("2013-09-01"),Book_Publisher="NKUST",Book_Note="人類文化 ",Book_Status="B",Book_Keeper="Xuan",Create_Date=DateTime.Parse("2015-01-01"),Create_User="PeiYee",Modify_Date=DateTime.Parse("2019-01-11"),Modify_User="GuoDong"},
new Book{Book_Id=4,Book_Name="微積分",Book_Author="Wei",Book_BoughtDate=DateTime.Parse("2015-09-01"),Book_Publisher="NKUST",Book_Note="微分與積分",Book_Status="U",Book_Keeper="Yee",Create_Date=DateTime.Parse("2016-08-07"),Create_User="GuoDong",Modify_Date=DateTime.Parse("2018-03-02"),Modify_User="PeiYee"},
};
books.ForEach(s => service.Books.Add(s));
service.SaveChanges();
var codes = new List<Code>
{
new Code{Code_Id="1",Code_Name="第一類",Code_TypeDesc="程式語言",Code_Type="Programming",Create_Date=DateTime.Parse("2019-10-10"),Create_User="Yee",Modify_Date=DateTime.Parse("2019-10-10"),Modify_User="Yee"},
new Code{Code_Id="2",Code_Name="第二類",Code_TypeDesc="文化",Code_Type="Cluture",Create_Date=DateTime.Parse("2019-10-10"),Create_User="Yee",Modify_Date=DateTime.Parse("2019-10-10"),Modify_User="Yee"},
new Code{Code_Id="3",Code_Name="第三類",Code_TypeDesc="數學",Code_Type="Math",Create_Date=DateTime.Parse("2019-10-10"),Create_User="Yee",Modify_Date=DateTime.Parse("2019-10-10"),Modify_User="Yee"},
};
codes.ForEach(s => service.Codes.Add(s));
service.SaveChanges();
var members = new List<Member>
{
new Member{User_Id="1",User_CName="陳沂",User_EName="Yee",Create_Date=DateTime.Parse("2009-10-19")},
new Member{User_Id="2",User_CName="阿偉",User_EName="Wei",Create_Date=DateTime.Parse("2008-11-29")},
new Member{User_Id="3",User_CName="小多",User_EName="Duo",Create_Date=DateTime.Parse("2010-12-19")},
};
members.ForEach(s => service.Members.Add(s));
service.SaveChanges();
var borrow = new List<Borrow>
{
new Borrow{User_Id="1",Book_Id=2,Code_Id="1",Status="A"},
new Borrow{User_Id="2",Book_Id=4,Code_Id="2",Status="B"},
new Borrow{User_Id="3",Book_Id=3,Code_Id="3",Status="C"},
};
borrow.ForEach(s => service.Borrows.Add(s));
service.SaveChanges();
}
}
} |
using System;
using System.Threading.Tasks;
namespace WerkWerk.Test.Workers
{
using Model;
using Tasks;
public class TestWorker : Worker<TestWorkerData>
{
private readonly TimeSpan _interval;
public TestWorker(IServiceProvider provider, TimeSpan interval) : base(provider)
{
_interval = interval;
}
protected override WorkBuilder<TestWorkerData> Configure(WorkBuilder<TestWorkerData> builder) => builder
.Setup("TestWork", _interval)
.Use<DoTask1>()
.Use(async ctx =>
{
await Task.Delay(50);
ctx.Data.Task2Complete = true;
return WorkResult.Success();
});
}
} |
using System.Xml.Serialization;
using Witsml.Data.Measures;
namespace Witsml.Data
{
public class WitsmlStnTrajCorUsed
{
[XmlElement("gravAxialAccelCor")] public Measure GravAxialAccelCor { get; set; }
[XmlElement("gravTran1AccelCor")] public Measure GravTran1AccelCor { get; set; }
[XmlElement("gravTran2AccelCor")] public Measure GravTran2AccelCor { get; set; }
[XmlElement("magAxialDrlstrCor")] public Measure MagAxialDrlstrCor { get; set; }
[XmlElement("magTran1DrlstrCor")] public Measure MagTran1DrlstrCor { get; set; }
[XmlElement("magTran2DrlstrCor")] public Measure MagTran2DrlstrCor { get; set; }
[XmlElement("magTran1MSACor")] public Measure MagTran1MsaCor { get; set; }
[XmlElement("magTran2MSACor")] public Measure MagTran2MsaCor { get; set; }
[XmlElement("magAxialMSACor")] public Measure MagAxialMsaCor { get; set; }
[XmlElement("sagIncCor")] public Measure SagIncCor { get; set; }
[XmlElement("sagAziCor")] public Measure SagAziCor { get; set; }
[XmlElement("stnMagDeclUsed")] public Measure StnMagDeclUsed { get; set; }
[XmlElement("stnGridCorUsed")] public Measure StnGridCorUsed { get; set; }
[XmlElement("stnGridConUsed")] public Measure StnGridConUsed { get; set; }
[XmlElement("dirSensorOffset")] public Measure DirSensorOffset { get; set; }
}
}
|
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using RaysTest.Core.Model;
using RayTest.Droid.Fragments;
namespace RayTest.Droid
{
[Activity(Label = "HotDogMenuActivity", MainLauncher = false)]
public class HotDogMenuActivity : BaseCustomActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
base.SetContentView(Resource.Layout.HotDogMenuView);
ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
this.AddTab("Favorites", Resource.Drawable.Icon, new FavoriteHotDogFragment());
this.AddTab("Meat lovers", Resource.Drawable.Icon, new MeatLoversFragment());
this.AddTab("Veggie Lovers", Resource.Drawable.Icon, new VeggieLoversFragment());
}
private void AddTab(string tabText, int iconResourceId , Fragment view)
{
var tab = this.ActionBar.NewTab();
tab.SetText(tabText);
tab.SetIcon(iconResourceId);
tab.TabSelected += delegate (object sender, ActionBar.TabEventArgs e)
{
var fragment = this.FragmentManager.FindFragmentById(Resource.Id.fragmentContainer);
if(fragment != null)
{
e.FragmentTransaction.Remove(fragment);
}
e.FragmentTransaction.Add(Resource.Id.fragmentContainer, view);
};
tab.TabUnselected += delegate (object sender, ActionBar.TabEventArgs e)
{
e.FragmentTransaction.Remove(view);
};
this.ActionBar.AddTab(tab);
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok && requestCode == this.ActivityHelper.RequestCode)
{
int paramId = base.ActivityHelper.GetValueFromExtras<int>(data, "Id");
int amount = base.ActivityHelper.GetValueFromExtras<int>(data, "amount");
HotDog selected = base.ActivityHelper.FindSelectedHotDog(paramId);
var dialog = new AlertDialog.Builder(this);
dialog.SetTitle("Confirmation");
dialog.SetMessage(string.Format("You have added {0} time(s) the {1}", amount, selected.Name));
dialog.Show();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MercadoPago;
namespace starteAlkemy.Services
{
public class MercadoPago
{
}
} |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using Timelogger.Api.BL;
using Timelogger.Api.Entities;
using Timelogger.Entities;
namespace Timelogger.Api.Controllers
{
[Route("api/invoice")]
public class InvoiceController : BaseApiController
{
/// <summary>
/// Instance of the workBC ( Bussiness component)
/// </summary>
private readonly IWorkBC _workBC;
/// <summary>
/// Constructor of invoice controller
/// </summary>
/// <param name="workBC">Injecting the workBC instance using parameter</param>
public InvoiceController(IWorkBC workBC)
{
this._workBC = workBC;
}
/// <summary>
/// Method to get the invoice amount
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
// GET api/Invoice/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
// Get the hours spend on the project
int hoursSpend;
this.ExecuteGatewayCall(this._workBC.GetTimeSpend, id, 1, out hoursSpend);
// Get the invoice amount based on the hours spend
decimal invoiceAmt;
this.ExecuteGatewayCall(this._workBC.GetInvoiceAmount, hoursSpend, 1, out invoiceAmt);
InvoiceData invoiceData = new InvoiceData()
{
TimeSpend = hoursSpend,
InvoiceAmt = invoiceAmt
};
return Ok(invoiceData);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Multiplication_Table
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Multiplication table");
Console.WriteLine("Enter a number and then print the number's multiplication table.");
string userInput = Console.ReadLine();
int parsedInput = int.Parse(userInput);
int[] multiplikationer = new int[10];
for (int i = 0; i < 10; i++)
{
multiplikationer[i] = (i + 1) * parsedInput;
}
Console.WriteLine("that's your number multiplication table, it's right! yeah!:");
foreach (int nummer in multiplikationer)
{
Console.WriteLine(nummer);
}
Console.ReadLine();
}
}
} |
// The players energy meter
using UnityEngine;
using System.Collections;
public class Energy : MonoBehaviour {
public float fullWidth = 256f; // max width of the powerbar
public float theTime; // The time before the player could move again
public GameObject powerMeter; // Finds the powermeter
private Movement barTime; // Gets the players movement script
// Use this for initialization
void Start () {
// Find the powermeter and its script
barTime = powerMeter.GetComponent<Movement>();
}
// Update is called once per frame
void Update () {
// If thrust variable in player is true
if(barTime.thrust) {
theTime += barTime.thrustTime * 3.8f;
Rect pos = guiTexture.pixelInset;
pos.xMax = guiTexture.pixelInset.xMin + fullWidth * theTime / fullWidth;
guiTexture.pixelInset = pos;
}
else {
theTime = 0; // Reset the time
}
}
}
|
using System.Web;
using Microsoft.AspNet.Identity;
using XH.Infrastructure.Bus;
using XH.Queries.Security.Dtos;
using XH.Queries.Security.Queries;
using Autofac;
namespace XH.Core.Context
{
public class WebWorkContextProvider : IWorkContextProvider
{
private readonly HttpContextBase _httpContext;
private readonly IQueryBus _queryBus;
private IWorkContext _cachedWorkContext;
public WebWorkContextProvider(HttpContextBase httpContext, IComponentContext context)
{
_httpContext = httpContext;
_queryBus = new InMemoryQueryBus(context);
}
public IWorkContext GetWorkContext()
{
if (_cachedWorkContext != null)
{
return _cachedWorkContext;
}
// Get user
var currentUser = default(UserProfileDto);
if (_httpContext != null && _httpContext.User != null)
{
var userId = _httpContext.User.Identity.GetUserId();
currentUser = _queryBus.Send<GetUserProfileQuery, UserProfileDto>(new GetUserProfileQuery
{
Id = userId
});
}
_cachedWorkContext = new WorkContext(currentUser);
return _cachedWorkContext;
}
}
}
|
using AccesoDatos;
using ProyectoLP2;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogicaNegocio
{
public class ClienteBL
{
ClienteDA clienteDA;
public ClienteBL()
{
clienteDA = new ClienteDA();
}
public BindingList<Cliente> listarCliente()
{
return clienteDA.listarClientes();
}
public BindingList<Cliente> listarCliente(string ruc)
{
return clienteDA.listarClientes(ruc);
}
public bool registrarCliente(Cliente cliente)
{
return clienteDA.registrarCliente(cliente);
}
public bool eliminarCliente(int id)
{
return clienteDA.eliminarCliente(id);
}
public bool modificarCliente(Cliente cliente)
{
return clienteDA.modificarCliente(cliente);
}
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace ConsoleMWS
{
class Program
{
static NetworkStream stream;
static List<Extension> extensions;
static void Main(string[] args)
{
Console.WriteLine("\nMessageWaitingService has started.");
extensions = new List<Extension>();
Listener();
//OnStart();
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
public static void OnStart()
{
int interval = int.Parse(ConfigurationSettings.AppSettings["monitoringInterval"]);
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = interval * 1000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(Monitoring);
timer.Start();
}
public static void Monitoring(object sender, System.Timers.ElapsedEventArgs args)
{
string path = ConfigurationSettings.AppSettings["mailboxPath"];
string format = ConfigurationSettings.AppSettings["extensionFormat"];
if (Directory.Exists(path) && stream != null)
{
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] files = dir.GetFiles().Where(f => f.Extension == ".ini").OrderBy(p => p.CreationTime).ToArray();
List<string> onExtensions = new List<string>();
foreach (FileInfo file in files)
{
int index = file.Name.IndexOf(" ");
if (index > -1)
{
string number = int.Parse(file.Name.Remove(index)).ToString(format);
if (!onExtensions.Contains(number)) {
string content = File.ReadAllText(file.FullName);
if (!extensions.Where(e => e.number == number).Any())
{
extensions.Add(new Extension(number, false));
}
if (!content.Contains("read=true"))
{
Extension ext = extensions.Where(e => e.number == number).First();
if (!ext.state)
{
byte[] signal = ext.getLampSignal(true);
Console.WriteLine(ext.number + " ON");
stream.Write(signal, 0, signal.Length);
ext.state = true;
}
onExtensions.Add(number);
}
}
}
}
foreach (Extension ext in extensions)
{
if (!onExtensions.Contains(ext.number) && ext.state) {
byte[] signal = ext.getLampSignal(false);
Console.WriteLine(ext.number + " OFF");
stream.Write(signal, 0, signal.Length);
ext.state = false;
}
}
}
}
public static void Listener()
{
TcpListener server = null;
Int32 port = Int32.Parse(ConfigurationSettings.AppSettings["port"]);
try
{
server = new TcpListener(IPAddress.Any, port);
server.Start();
Console.WriteLine("\nWaiting for a connection... ");
// Buffer for reading data
Byte[] bytes = new Byte[256];
// Enter the listening loop.
while (true)
{
if (server.Pending())
{
using (TcpClient client = server.AcceptTcpClient())
{
Console.WriteLine("\nAccept connection from client!");
String data = null;
// Get a stream object for reading and writing
stream = client.GetStream();
OnStart();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
bytes = System.Text.Encoding.ASCII.GetBytes(data);
if (data.Substring(5, 2) == "98")
{
Console.Write("\nDopyt PBX: " + data);
string sApproval = data.Remove(5, 2).Insert(5, "93");
string sResponse = data.Remove(5, 2).Insert(5, "99");
Byte[] bApproval = System.Text.Encoding.ASCII.GetBytes(sApproval);
Byte[] bResponse = System.Text.Encoding.ASCII.GetBytes(sResponse);
stream.Write(bApproval, 0, bApproval.Length);
Console.Write("Potvr MWS: " + sApproval);
stream.Write(bResponse, 0, bResponse.Length);
Console.Write("Odpov MWS: " + sResponse);
}
else if (data.Substring(5, 2) == "93")
{
Console.Write("Potvr PBX: " + data);
}
}
client.Close();
}
}
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
}
}
class Extension
{
public string number;
public bool state; // 0 = OFF, 1 = ON
public Extension(string number, bool state)
{
this.number = number;
this.state = state;
}
public byte[] getLampSignal(bool state)
{
byte[] extension = System.Text.Encoding.ASCII.GetBytes(number);
byte[] signal;
byte[] end = new byte[] { 48, 49, 13, 10 };
if (state)
signal = new byte[] { 1, 48, 48, 48, 2, 48, 54 };
else
signal = new byte[] { 1, 48, 48, 48, 2, 48, 55 };
byte[] result = new byte[signal.Length + extension.Length + end.Length];
Buffer.BlockCopy(signal, 0, result, 0, signal.Length);
Buffer.BlockCopy(extension, 0, result, signal.Length, extension.Length);
Buffer.BlockCopy(end, 0, result, signal.Length + extension.Length, end.Length);
return result;
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Upgrader.MySql;
using Upgrader.Schema;
namespace Upgrader.Test.MySql
{
[TestClass]
public class PrimaryKeyInfoMySqlTest : PrimaryKeyInfoTest
{
public PrimaryKeyInfoMySqlTest() : base(new MySqlDatabase(AssemblyInitialize.MySqlConnectionString))
{
}
[TestMethod]
public override void PrimaryKeyIsNamedAccordingToNamingConvention()
{
Database.Tables.Add("PrimaryKeyName", new Column<int>("PrimaryKeyNameId"));
Database.Tables["PrimaryKeyName"].AddPrimaryKey("PrimaryKeyNameId");
Assert.AreEqual("PRIMARY", Database.Tables["PrimaryKeyName"].GetPrimaryKey().PrimaryKeyName);
}
}
}
|
using System;
namespace Phenix.Test.使用指南._11._2._1
{
/// <summary>
/// User
/// </summary>
[Serializable]
public class User : User<User>
{
private User()
{
//禁止添加代码
}
#region 演示OnInitializeNew()函数被调用的情况
//* 记录OnInitializeNew()函数是否被调用了
public bool OnInitializeNewByExecute { get; private set; }
//* 此处可以写业务对象的初始化代码,但需知道什么情况下才会被调用:NewPure()不会、New()会
protected override void OnInitializeNew()
{
//* 记录下被调用了
OnInitializeNewByExecute = true;
}
#endregion
}
/// <summary>
/// User清单
/// </summary>
[Serializable]
public class UserList : Phenix.Business.BusinessListBase<UserList, User>
{
private UserList()
{
//禁止添加代码
}
}
/// <summary>
/// User
/// </summary>
[Phenix.Core.Mapping.ClassAttribute("PH_USER", FriendlyName = "User"), System.ComponentModel.DisplayNameAttribute("User"), System.SerializableAttribute()]
public abstract class User<T> : Phenix.Business.BusinessBase<T> where T : User<T>
{
/// <summary>
/// US_ID
/// </summary>
public static readonly Phenix.Business.PropertyInfo<long?> US_IDProperty = RegisterProperty<long?>(c => c.US_ID);
[Phenix.Core.Mapping.Field(FriendlyName = "US_ID", TableName = "PH_USER", ColumnName = "US_ID", IsPrimaryKey = true, NeedUpdate = true)]
private long? _US_ID;
/// <summary>
/// US_ID
/// </summary>
[System.ComponentModel.DisplayName("US_ID")]
public long? US_ID
{
get { return GetProperty(US_IDProperty, _US_ID); }
internal set
{
SetProperty(US_IDProperty, ref _US_ID, value);
}
}
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
public override string PrimaryKey
{
get { return US_ID.ToString(); }
}
/// <summary>
/// US_USERNUMBER
/// </summary>
public static readonly Phenix.Business.PropertyInfo<string> UsernumberProperty = RegisterProperty<string>(c => c.Usernumber);
[Phenix.Core.Mapping.Field(FriendlyName = "US_USERNUMBER", Alias = "US_USERNUMBER", TableName = "PH_USER", ColumnName = "US_USERNUMBER", NeedUpdate = true)]
private string _usernumber;
/// <summary>
/// US_USERNUMBER
/// </summary>
[System.ComponentModel.DisplayName("US_USERNUMBER")]
public string Usernumber
{
get { return GetProperty(UsernumberProperty, _usernumber); }
set { SetProperty(UsernumberProperty, ref _usernumber, value); }
}
/// <summary>
/// US_NAME
/// </summary>
public static readonly Phenix.Business.PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name);
[Phenix.Core.Mapping.Field(FriendlyName = "US_NAME", Alias = "US_NAME", TableName = "PH_USER", ColumnName = "US_NAME", NeedUpdate = true, IsNameColumn = true, InLookUpColumn = true, InLookUpColumnDisplay = true)]
private string _name;
/// <summary>
/// US_NAME
/// </summary>
[System.ComponentModel.DisplayName("US_NAME")]
public string Name
{
get { return GetProperty(NameProperty, _name); }
set { SetProperty(NameProperty, ref _name, value); }
}
/// <summary>
/// US_LOCKED
/// </summary>
public static readonly Phenix.Business.PropertyInfo<bool?> LockedProperty = RegisterProperty<bool?>(c => c.Locked);
[Phenix.Core.Mapping.Field(FriendlyName = "US_LOCKED", Alias = "US_LOCKED", TableName = "PH_USER", ColumnName = "US_LOCKED", NeedUpdate = true)]
private int? _locked;
/// <summary>
/// US_LOCKED
/// </summary>
[System.ComponentModel.DisplayName("US_LOCKED")]
public bool? Locked
{
get { return GetPropertyConvert(LockedProperty, _locked); }
set { SetPropertyConvert(LockedProperty, ref _locked, value); }
}
/// <summary>
/// New
/// </summary>
public static T New(string usernumber, string name, int? locked)
{
T result = NewPure();
result._usernumber = usernumber;
result._name = name;
result._locked = locked;
return result;
}
/// <summary>
/// SetFieldValues
/// </summary>
protected void SetFieldValues(string usernumber, string name, int? locked)
{
InitOldFieldValues();
_usernumber = usernumber;
_name = name;
_locked = locked;
MarkDirty();
}
}
}
|
using BHLD.Model.Abstract;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BHLD.Model.Models
{
[Table("hu_protection_title")]
public class hu_protection_title : Auditable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
//tham chiếu phần other_list_type
public int type_id { get; set; }
public int title_id { get; set; }
[ForeignKey("title_id")]
public virtual hu_title Hu_Title { get; set; }
public DateTime effect_date { get; set; }
public DateTime expire_date { get; set; }
[StringLength(1023)]
public string remark { get; set; }
[StringLength(1)]
public string actfg { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using TheMapToScrum.Back.BLL.Mapping;
using TheMapToScrum.Back.DAL.Entities;
using TheMapToScrum.Back.DTO;
namespace TheMapToScrum.Back.BLL
{
internal static class MapProjectDTO
{
internal static ProjectDTO ToDto(Project objet)
{
ProjectDTO retour = new ProjectDTO();
if (null != objet)
{
retour.Id = objet.Id;
retour.Label = objet.Label;
retour.ProductOwnerId = objet.ProductOwnerId;
retour.TeamId = objet.TeamId;
retour.ScrumMasterId = objet.ScrumMasterId;
retour.DepartmentId = objet.DepartmentId;
retour.Department = MapDepartmentDTO.ToDto(objet.Department);
retour.ScrumMaster= MapScrumMasterDTO.ToDto(objet.TechnicalManager);
retour.ProductOwner = MapProductOwnerDTO.ToDto(objet.ProductOwner);
retour.Team = MapTeamDTO.ToDto(objet.Team);
retour.DateCreation = (System.DateTime)objet.DateCreation;
retour.DateModification = (System.DateTime)objet.DateModification;
retour.IsDeleted = objet.IsDeleted;
}
return retour;
}
internal static List<ProjectDTO> ToDto(List<TheMapToScrum.Back.DAL.Entities.Project> liste)
{
List<ProjectDTO> retour = new List<ProjectDTO>();
retour = liste.Select(x => new ProjectDTO()
{
Id = x.Id,
DepartmentId = x.DepartmentId,
ProductOwnerId = x.ProductOwnerId,
TeamId = x.TeamId,
ScrumMasterId = x.ScrumMasterId,
Department = MapDepartmentDTO.ToDto(x.Department),
ProductOwner = MapProductOwnerDTO.ToDto(x.ProductOwner),
ScrumMaster = MapScrumMasterDTO.ToDto(x.TechnicalManager),
Team = MapTeamDTO.ToDto(x.Team),
DateCreation = (System.DateTime)x.DateCreation,
DateModification = (System.DateTime)x.DateModification,
IsDeleted = x.IsDeleted,
Label = x.Label
}).ToList();
return retour;
}
}
}
|
// Author: Eduard Varshavsky
// File Name: Character.cs
// Project Name: Super Mario Bros
// Creation Date: October 8, 2017
// Modified Date: October 15, 2017
// Description: This class is used as a base class for playale and non-playable characters
// code
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Super_Mario_Bros
{
class Characters
{
//Stores the running animation of the character
protected Texture2D runningAnimation;
//Stores the timers for death animations
protected int deathTimer;
protected int dTimerMax = 36;
//Stores the max bounce height
protected int bounceMax = 12;
//Stores the animation frame data dimensions
protected int walkFrames = 4;
protected int walkFrameWidth;
protected int walkFrameHeight;
protected int numRows = 1;
protected int numCols = 4;
protected int currentWalkFrame = 0;
protected int frameCount = 0;
protected float walkFrameRepeat = 5;
//Stores source and destination rectangles
protected Rectangle srcRec;
protected Rectangle destRec;
//Stores current x and y velocities as well as constants for physics
protected float xVelocity;
protected float yVelocity;
protected const int SCALE_CONST = 4;
protected const float NEW_GRAVITY_MID = .6f * SCALE_CONST / 2;
protected const float DEATH_JUMP = -16f;
//Stores true/false data for state bools
protected bool isGoingRight;
protected bool isDead;
protected bool isAlternateDead;
//Made array of rectangles for hitboxes (0 = head, 1 = legs, 2 = left, 3 = right)
protected Rectangle[] hitBoxes = new Rectangle[4];
//Pre: Requires to be called by the MainGame class
//Post: Gives the Rectagle of the asked for rectangele
//Desc: Used to provide the destination rectangle for location and dimension calculations
public Rectangle GetDest()
{
return destRec;
}
//Pre: Requires to be called by the MainGame class
//Post: Gives the Rectagle of the asked for rectangle
//Desc: Used to provide the source rectangle for sprite sheet based animations
public Rectangle GetSrc()
{
return srcRec;
}
public Texture2D GetWalkImg()
{
return runningAnimation;
}
public int GetInterception(Rectangle potentialCollision)
{
if (potentialCollision.Intersects(destRec))
{
for (int i = 0; i < hitBoxes.Length; i++)
{
if (hitBoxes[i].Intersects(potentialCollision))
{
return i;
}
}
}
return -1;
}
public void MoveXConstantly()
{
destRec.X += (int)xVelocity;
SetHitXPos();
}
public void MoveYGravity()
{
yVelocity += NEW_GRAVITY_MID;
destRec.Y += (int)yVelocity;
SetHitYPos();
}
public void SetCharacterX(int xPoint)
{
destRec.X = xPoint;
for (int i = 0; i < hitBoxes.Length; i++)
{
int halfCharacterX = (runningAnimation.Width / numCols) / 2;
int halfCharacterY = (runningAnimation.Height / numRows) / 2;
int headSize = 32;
int halfHead = headSize / 2;
hitBoxes[0] = new Rectangle(GetDest().X + halfHead / 2, GetDest().Y, halfCharacterX + halfHead, halfHead / 2);
hitBoxes[1] = new Rectangle(GetDest().X + halfHead / 2, GetDest().Y + GetDest().Height - halfHead / 2, halfCharacterX + halfHead, halfHead / 2);
hitBoxes[2] = new Rectangle(GetDest().X, GetDest().Y + halfHead / 2, halfCharacterX, GetDest().Height - headSize / 2);
hitBoxes[3] = new Rectangle(GetDest().X + halfCharacterX, GetDest().Y + halfHead / 2, halfCharacterX, GetDest().Height - headSize / 2);
}
}
public void SetCharacterY(int yPoint)
{
destRec.Y = yPoint;
for (int i = 0; i < hitBoxes.Length; i++)
{
int halfCharacterX = (runningAnimation.Width / numCols) / 2;
int halfCharacterY = (runningAnimation.Height / numRows) / 2;
int headSize = 32;
int halfHead = headSize / 2;
hitBoxes[0] = new Rectangle(GetDest().X + halfHead / 2, GetDest().Y, halfCharacterX + halfHead, halfHead / 2);
hitBoxes[1] = new Rectangle(GetDest().X + halfHead / 2, GetDest().Y + GetDest().Height - halfHead / 2, halfCharacterX + halfHead, halfHead / 2);
hitBoxes[2] = new Rectangle(GetDest().X, GetDest().Y + halfHead / 2, halfCharacterX, GetDest().Height - headSize / 2);
hitBoxes[3] = new Rectangle(GetDest().X + halfCharacterX, GetDest().Y + halfHead / 2, halfCharacterX, GetDest().Height - headSize / 2);
}
}
public void ChangeDirection()
{
if (isGoingRight == false)
{
isGoingRight = true;
xVelocity = 2f;
}
else
{
isGoingRight = false;
xVelocity = -2f;
}
}
public float GetXVelocity()
{
return xVelocity;
}
public float GetYVelocity()
{
return yVelocity;
}
public Rectangle GetHitboxRec(int i)
{
return hitBoxes[i];
}
public bool IsGoingRight()
{
return isGoingRight;
}
public void SetHitXPos()
{
for (int i = 0; i < hitBoxes.Length; i++)
{
hitBoxes[i].X += (int)xVelocity;
}
}
public void SetHitYPos()
{
for (int i = 0; i < hitBoxes.Length; i++)
{
hitBoxes[i].Y += (int)yVelocity;
}
}
public void ResetXVelocity()
{
xVelocity = 0f;
}
public void ResetYVelocity()
{
yVelocity = 0f;
}
public void SetIsDead()
{
isDead = true;
}
public bool GetIsDead()
{
return isDead;
}
public void SetIsAlternateDead()
{
isAlternateDead = true;
}
public bool GetIsAlternateDead()
{
return isAlternateDead;
}
public void DeathJump()
{
yVelocity = DEATH_JUMP;
if (isGoingRight == true)
{
xVelocity = DEATH_JUMP / 2;
}
else
{
xVelocity = -DEATH_JUMP / 2;
}
}
public void IncrimentDeathTimer()
{
deathTimer++;
}
public bool IsDeathTimerUp()
{
if (deathTimer >= dTimerMax)
{
return true;
}
return false;
}
public void ResetDeathTimer()
{
deathTimer = 0;
}
//Pre: frameNum is the current frame the animation is on
// frameW is the pixel width of one frame in the source image
// numCols is the number of columns wide the animation grid is
//Post: Return the x cooridinate on the source image of the current animation frame
//Desc: Calculate the X coordinate of the current frame animation on the
// source image
public int GetSrcX(int frameNum, int frameW, int numCols)
{
int result = 0;
//Calculate which column the animation frame is in within the animation grid
int col = (frameNum % numCols);
//Calculate the x by multiplying the column by the width of one frame
result = frameW * col;
return result;
}
//Pre: frameNum is the current frame the animation is on
// frameH is the pixel height of one frame in the source image
// numCols is the number of columns wide the animation grid is
//Post: Return the y cooridinate on the source image of the current animation frame
//Desc: Calculate the y coordinate of the current frame animation on the
// source image
public int GetSrcY(int frameNum, int frameH, int numCols)
{
int result = 0;
//Calculate which row the animation frame is in within the animation grid
int row = (frameNum / numCols);
//Calculate the y by multiplying the row by the height of one frame
result = frameH * row;
return result;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Waypoints : MonoBehaviour
{
private static Waypoint firstWaypoint;
public static GameObject startPoint;
void Start()
{
startPoint = GameObject.Find("StartPoint");
}
public static Waypoint GetFirstWaypoint()
{
if (firstWaypoint != null)
{
return firstWaypoint;
}
var waypoint = GameObject.FindObjectOfType<Waypoint>();
while (waypoint.previousWaypoint!=null)
{
waypoint = waypoint.previousWaypoint;
}
return firstWaypoint = waypoint;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Obstacle : MonoBehaviour
{
float currentSpeed = 4f;
LevelController levelController;
void Start()
{
levelController = FindObjectOfType<LevelController>();
}
void Update()
{
transform.Translate(Vector2.left * currentSpeed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
Destroy(other.gameObject);
levelController.Finish();
}
}
}
|
using System.Collections.Generic;
namespace SingletonDemo
{
//try to add items in cart
public class ManageCart2
{
public static void AddmoreItems()
{
//get cart instance
Cart cart3=Cart.getCart();
cart3.Items.Add(new Item(){Name="Plain Yogurt",Price=3.00M});
}
}
} |
using System;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramFootballBot.Core.Models.CallbackQueries;
namespace TelegramFootballBot.Core.Helpers
{
public static class MarkupHelper
{
public static InlineKeyboardMarkup GetIfReadyToPlayQuestion(DateTime gameDate)
{
var labels = new[] { Constants.YES_ANSWER, Constants.NO_ANSWER, Constants.MAYBE_ANSWER };
return GetKeyBoardMarkup(PlayerSetCallback.BuildCallbackPrefix(gameDate), labels, labels);
}
private static InlineKeyboardMarkup GetKeyBoardMarkup(string callbackPrefix, string[] buttonsLabels, string[] buttonValues)
{
var keyBoard = new[] { new InlineKeyboardButton[buttonsLabels.Length] };
for (var i = 0; i < keyBoard[0].Length; i++)
{
keyBoard[0][i] = new InlineKeyboardButton(buttonsLabels[i])
{
CallbackData = Callback.ToCallbackText(callbackPrefix, buttonValues[i])
};
}
return new InlineKeyboardMarkup(keyBoard);
}
public static string DashedString => new('-', 30);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.