text stringlengths 13 6.01M |
|---|
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace NetFabric.Hyperlinq
{
public static partial class ValueEnumerable
{
[GeneratedCode("NetFabric.Hyperlinq.SourceGenerator", "1.0.0")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Count(this NetFabric.Hyperlinq.ValueEnumerable.RangeEnumerable source)
=> NetFabric.Hyperlinq.ValueEnumerableExtensions.Count<NetFabric.Hyperlinq.ValueEnumerable.RangeEnumerable, NetFabric.Hyperlinq.ValueEnumerable.RangeEnumerable.DisposableEnumerator, int>(source);
}
}
|
using SimpleApiService.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SimpleApiService.Service.Contracts
{
public interface IAccountService
{
/// <summary>
/// Депозит дс
/// </summary>
public Task<decimal> TopUp(int accountId, decimal amount);
/// <summary>
/// Снять дс
/// </summary>
public Task<decimal> Withdraw(int accountId, decimal amount);
/// <summary>
/// Трансфер дс между счетами
/// </summary>
public Task<TransferDTO> Transfer(int sourceAccountId, int destinationAccountId, decimal amount);
}
}
|
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 CapaEntidades;
using CapaNegocio;
namespace CapaPresentacion
{
public partial class FrmPresentacion : Form
{
//variable bool para registrar y objetos de clases entidad y negocio
private bool Editar = false;
readonly E_Presentacion ObjEntidad = new E_Presentacion();
readonly N_Presentacion ObjNegocio = new N_Presentacion();
public FrmPresentacion()
{
InitializeComponent();
}
//Metodo mensaje para confirmacion
private void MensajeConfirmacion(string Mensaje)
{
MessageBox.Show(Mensaje, "Ferreteria Emanuel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//Metodo para mostrar mensaje de error
private void MensajeError(string Mensaje)
{
MessageBox.Show(Mensaje,"Ferreteria Emanuel",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
//Metodo mostrar presentacion
public void MostrarRegistro()
{
DataListado.DataSource = N_Presentacion.MostrarRegistro();
}
//Metodo Buscar presentacion
public void BuscarRegistro()
{
DataListado.DataSource = N_Presentacion.BuscarRegistro(txtBuscar.Text);
}
//Metodo limpiar textos
private void LimpiarTexto()
{
Editar = false;
txtID.Text = "";
txtNombre.Text = "";
txtDescripcion.Text = "";
txtNombre.Focus();
}
private void FrmPresentacion_Load(object sender, EventArgs e)
{
this.MostrarRegistro();
}
private void pbCerrar_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnNuevo_Click(object sender, EventArgs e)
{
this.LimpiarTexto();
}
private void btnEditar_Click(object sender, EventArgs e)
{
if (DataListado.SelectedRows.Count>0)
{
Editar = true;
txtID.Text = DataListado.CurrentRow.Cells[0].Value.ToString();
txtNombre.Text = DataListado.CurrentRow.Cells[1].Value.ToString();
txtDescripcion.Text = DataListado.CurrentRow.Cells[2].Value.ToString();
}
else
{
this.MensajeError("Seleccione un registro de la tabla!!!");
}
}
private void btnEliminar_Click(object sender, EventArgs e)
{
if (DataListado.SelectedRows.Count>0)
{
DialogResult opcion;
opcion = MessageBox.Show("¿Realmente desea eliminar el registro?","Ferreteria Emanuel",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
if (opcion==DialogResult.OK)
{
ObjEntidad.Id_presentacion = Convert.ToInt32(DataListado.CurrentRow.Cells[0].Value.ToString());
ObjNegocio.EliminarRegistro(ObjEntidad);
MensajeConfirmacion("Se eliminó correctamente el registro");
this.MostrarRegistro();
}
}
else
{
MensajeError("Seleccione un registro de la tabla!!!");
}
}
private void btnGuardar_Click(object sender, EventArgs e)
{
if (Editar==false)
{
try
{
if (txtNombre.Text==string.Empty)
{
MensajeError("Debe proporcionar un nombre para agregar nueva presentacion");
}
else
{
ObjEntidad.Nombre = txtNombre.Text.ToUpper();
ObjEntidad.Descripcion = txtDescripcion.Text.ToUpper();
ObjNegocio.InsertarRegistro(ObjEntidad);
MensajeConfirmacion("Se ingresó correctamente el registro");
this.MostrarRegistro();
this.LimpiarTexto();
}
}
catch (Exception)
{
MensajeError("Error al guardar el registro!!!");
}
}
if (Editar==true)
{
try
{
ObjEntidad.Id_presentacion = Convert.ToInt32(txtID.Text);
ObjEntidad.Nombre = txtNombre.Text.ToUpper();
ObjEntidad.Descripcion = txtDescripcion.Text.ToUpper();
ObjNegocio.EditarRegistro(ObjEntidad);
MensajeConfirmacion("Se modificó correctamente el registro");
this.MostrarRegistro();
this.LimpiarTexto();
}
catch (Exception)
{
MensajeError("Error al modificar el registro!!!");
}
}
}
private void txtBuscar_TextChanged(object sender, EventArgs e)
{
this.BuscarRegistro();
}
private void label4_Click(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AzmanSys
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void btnManageCustomers_Click(object sender, EventArgs e)
{
Close(); // close the current form
CustomersForm custForm = new CustomersForm();
custForm.Show();
}
private void btnManageFlights_Click(object sender, EventArgs e)
{
Close(); // close the current form
FlightsForm flightsForm = new FlightsForm();
flightsForm.Show();
}
private void btnManageBookings_Click(object sender, EventArgs e)
{
Close(); // close the current form
BookingsForm bookingsForm = new BookingsForm();
bookingsForm.Show();
}
}
}
|
using System.Web.Optimization;
namespace MyCashFlow.Web
{
public static class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
RegisterScriptBundles(bundles);
RegisterStyleBundles(bundles);
}
private static void RegisterScriptBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle(Bundles.Scripts.Jquery)
.Include("~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle(Bundles.Scripts.Jqueryval)
.Include("~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/jquery.unobtrusive-ajax.js"));
bundles.Add(new ScriptBundle(Bundles.Scripts.JqueryUi)
.Include("~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle(Bundles.Scripts.Modernizr)
.Include("~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle(Bundles.Scripts.Bootstrap)
.Include("~/Scripts/bootstrap.min.js",
"~/Scripts/respond.js"));
bundles.Add(new ScriptBundle(Bundles.Scripts.Knockout)
.Include("~/Scripts/knockout-{version}.js",
"~/Scripts/moment-with-locales.min.js")
.IncludeDirectory("~/Scripts/MyCashFlow/Knockout", "*.js", true));
bundles.Add(new ScriptBundle(Bundles.Scripts.MyCashFlow.Models.Shared)
.Include("~/Scripts/MyCashFlow/Models/Shared/*.js"));
bundles.Add(new ScriptBundle(Bundles.Scripts.MyCashFlow.Models.Transaction)
.Include("~/Scripts/MyCashFlow/Models/Transaction/*.js"));
}
private static void RegisterStyleBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle(Bundles.Styles.Css).Include(
"~/Content/bootstrap.css",
"~/Content/Site.css"));
bundles.Add(new StyleBundle(Bundles.Styles.JqueryUi).Include(
"~/Content/themes/base/jquery-ui.min.css"));
}
}
public static class Bundles
{
public static class Scripts
{
public const string Jquery = "~/bundles/jquery";
public const string Jqueryval = "~/bundles/jqueryval";
public const string JqueryUi = "~/bundles/jqueryui";
public const string Modernizr = "~/bundles/modernizr";
public const string Bootstrap = "~/bundles/bootstrap";
public const string Knockout = "~/bundles/knockout";
public static class MyCashFlow
{
public static class Models
{
public const string Shared = "~/bundles/MyCashFlow/Models/Shared";
public const string Transaction = "~/bundles/MyCashFlow/Models/Transaction";
}
}
}
public static class Styles
{
public const string Css = "~/Content/css";
public const string JqueryUi = "~/Content/jqueryui";
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserStorageServices.Validation;
namespace UserStorageServices
{
public class CompositeValidator : IValidator
{
private readonly IValidator[] _validators;
public CompositeValidator()
{
_validators = new[]
{
new AgeValidator(),
new FirstNameValidator(),
(IValidator)new LastNameValidator()
};
}
public void Validate(User user)
{
if (user == null)
{
throw new ArgumentNullException("User is null." , nameof(user));
}
foreach (var item in _validators)
{
item.Validate(user);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class CameraManager : MonoBehaviour
{
public static CameraManager main;
public float moveSpeed = 5;
public float moveDamping = 10;
public float cameraAngle = 52;
public bool canRotate = false;
public float rotationSpeed = 60;
public float rotationDamping = 10;
public float zoomSpeed = 10;
public float zoomDistance = 10;
public Vector3 focusPos;
public int minAngle = 30;
public int maxAngle = 90;
public int minZoom = 3;
public int maxZoom = 30;
private Transform _transform;
public float x, y;
void Start ()
{
main = this;
_transform = transform;
y = cameraAngle;
_transform.rotation = Quaternion.Euler(y, x, 0);
}
void Update ()
{
if (canRotate && Input.GetKey(KeyCode.Mouse2))
{
x += Input.GetAxis("Mouse X") * rotationSpeed * Time.fixedDeltaTime;
y -= Input.GetAxis("Mouse Y") * rotationSpeed * Time.fixedDeltaTime;
y = Mathf.Clamp(y, minAngle, maxAngle);
_transform.rotation = Quaternion.Euler(y, x, 0);
}
zoomDistance -= Input.GetAxis("Mouse ScrollWheel") * zoomSpeed * Time.fixedDeltaTime;
zoomDistance = Mathf.Clamp(zoomDistance, minZoom, maxZoom);
focusPos += Quaternion.Euler(0, x, 0) * new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")) * moveSpeed * (zoomDistance / maxZoom) * Time.deltaTime;
_transform.position = focusPos + Quaternion.Euler(y, x, 0) * new Vector3(0.0f, 0.0f, -zoomDistance);
}
public void PanTo(Transform target)
{
//float y = transform.position.y;
focusPos = target.position;
//focusPos.y = y;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using OlympicsWebApp.BusinessLayer;
using OlympicsWebApp.Data;
namespace OlympicsWebApp.Pages.Countries
{
public class IndexModel : PageModel
{
private readonly OlympicsWebApp.Data.OlympicsDataContext _context;
public IndexModel(OlympicsWebApp.Data.OlympicsDataContext context)
{
_context = context;
}
public IList<Country> Country { get;set; }
public async Task OnGetAsync()
{
Country = await _context.Countries.ToListAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Emotiv
{
public class ELSClient
{
public enum profileFileType
{
TRAINING,
EMOKEY
};
public struct profileVersionInfo
{
public int version;
public IntPtr last_modified;
};
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_Connect")]
public static extern bool ELS_Connect();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_Login")]
public static extern bool ELS_Login(String email, String password, ref int userID);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_CreateHeadset")]
public static extern bool ELS_CreateHeadset(int userID);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_CreateProtocol")]
public static extern bool ELS_CreateProtocol(String name, ref int protocolID);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_AddSubjectToProtocol")]
public static extern bool ELS_AddSubjectToProtocol(int userID, int protocolID);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_SetProtocol")]
public static extern bool ELS_SetProtocol(int protocolID);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_SetExperiment")]
public static extern bool ELS_SetExperiment(int experimentID);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_CreateExperiment")]
public static extern bool ELS_CreateExperiment(String name, String description, ref int experimentID);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_CreateRecordingSession")]
public static extern IntPtr ELS_CreateRecordingSession();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_StartRecordData")]
public static extern bool ELS_StartRecordData();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_StartRecordDataWithOCEFile")]
public static extern bool ELS_StartRecordDataWithOCEFile(String oceiFilePath, ref bool overtime, int timeLimit = 24);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_StopRecordData")]
public static extern bool ELS_StopRecordData();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_GetReportOnline")]
public static extern void ELS_GetReportOnline(ref int engagementScore, ref int excitementScore, ref int stressScore, ref int relaxScore, ref int interestScore);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_GetOfflineReport")]
public static extern void ELS_GetOfflineReport(ref int engagementScore, ref int excitementScore, ref int affinityScore);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_Marker_EyeOpenStart")]
public static extern bool ELS_Marker_EyeOpenStart();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_Marker_EyeOpenEnd")]
public static extern bool ELS_Marker_EyeOpenEnd();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_Marker_EyeClosedStart")]
public static extern bool ELS_Marker_EyeClosedStart();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_Marker_EyeClosedEnd")]
public static extern bool ELS_Marker_EyeClosedEnd();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_Marker_RecordingStart")]
public static extern bool ELS_Marker_RecordingStart();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_UpdateNote")]
public static extern bool ELS_UpdateNote(String note);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_UpdateTag")]
public static extern bool ELS_UpdateTag(String[] tag);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_UploadPhoto")]
public static extern bool ELS_UploadPhoto(String filePath);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_Disconnect")]
public static extern void ELS_Disconnect();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_UploadEdfFile")]
public static extern String ELS_UploadEdfFile(String emostateFilePath, String edfFilePath);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_UploadProfileFile")]
public static extern bool ELS_UploadProfileFile(String profileName, String filePath, profileFileType ptype);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_UpdateProfileFile")]
public static extern bool ELS_UpdateProfileFile(int profileId, String filePath);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_DeleteProfileFile")]
public static extern bool ELS_DeleteProfileFile(int profileId);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_GetProfileId")]
public static extern int ELS_GetProfileId(String profileName);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_DownloadFileProfile")]
public static extern bool ELS_DownloadFileProfile(int profileId,String destPath,int version); //default = -1 for download lastest version
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_GetAllProfileName")]
public static extern int ELS_GetAllProfileName();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_ProfileIDAtIndex")]
public static extern int ELS_ProfileIDAtIndex(int index);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_ProfileNameAtIndex")]
public static extern String ELS_ProfileNameAtIndex(int index);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_ProfileLastModifiedAtIndex")]
public static extern IntPtr ELS_ProfileLastModifiedAtIndex(int index);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_ProfileTypeAtIndex")]
public static extern profileFileType ELS_ProfileTypeAtIndex(int index);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_SaveOpenCloseEyeInfo")]
public static extern bool ELS_SaveOpenCloseEyeInfo(String fileName);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_ResetPassword")]
public static extern bool ELS_ResetPassword(String userName);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_Logout")]
public static extern bool ELS_Logout();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_SetDefaultUser")]
public static extern bool ELS_SetDefaultUser(int userID);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_GetDefaultUser")]
public static extern int ELS_GetDefaultUser();
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_GetAvailableProfileVersions")]
public static extern bool ELS_GetAvailableProfileVersions(int profileID, out profileVersionInfo pVersionInfo, ref int nVersion);
[DllImport("edk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ELS_SetClientSecret")]
public static extern void ELS_SetClientSecret(String profileID, String clientSecret);
}
}
|
using System;
using Assets.Scripts.Core.ConstantsContainers;
using Assets.Scripts.Models;
using Assets.Scripts.Units;
namespace Assets.Scripts.Configs
{
[Serializable]
public class MobConfig
{
[ChooseFromList(typeof(UnitType))]
public string UnitType;
public UnitController Prefab;
public MobLevel Level;
}
} |
using System.Collections.Generic;
namespace Hybrid.AspNetCore.Mvc.Models
{
/// <summary>
/// 表示包含了分页信息的集合类型。
/// </summary>
/// <typeparam name="T"></typeparam>
public class PageResult<T>
{
#region Ctor
/// <summary>
/// 初始化一个新的<c>PagedResult{T}</c>类型的实例。
/// </summary>
public PageResult()
{
Data = new List<T>();
}
///// <summary>
///// 初始化一个新的<c>PagedResult{T}</c>类型的实例。
///// </summary>
///// <param name="totalRecords">总记录数。</param>
///// <param name="totalPages">页数。</param>
///// <param name="pageNumber">页码。</param>
///// <param name="pageSize">页面大小。</param>
///// <param name="data">当前页面的数据。</param>
//public PageRequest(long totalRecords, int totalPages, int pageNumber, int pageSize, List<T> data)
//{
// TotalRecords = totalRecords;
// TotalPages = totalPages;
// PageNumber = pageNumber;
// PageSize = pageSize;
// Data = data;
//}
#endregion Ctor
#region Public Properties
/// <summary>
/// 获取或设置总记录数。
/// </summary>
public long TotalRecords { get; set; }
///// <summary>
///// 获取或设置页数。
///// </summary>
//public int TotalPages { get; set; }
///// <summary>
///// 获取或设置页面大小。
///// </summary>
//public int PageSize { get; set; }
///// <summary>
///// 获取或设置页码。
///// </summary>
//public int PageNumber { get; set; }
/// <summary>
/// 获取或设置当前页面的数据。
/// </summary>
public List<T> Data { get; set; }
#endregion Public Properties
}
} |
using System;
using System.Collections;
namespace Simplist.Cqrs.Core
{
public interface IRepository<T> where T : IEventSourced
{
// void Save(T eventSourced);
T Get(Guid id);
}
} |
using Microsoft.EntityFrameworkCore.Migrations;
namespace VinarishMvc.Migrations
{
public partial class ParentReportId : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Reports_Reports_AppendixReportId",
table: "Reports");
migrationBuilder.RenameColumn(
name: "AppendixReportId",
table: "Reports",
newName: "ParentReportId");
migrationBuilder.RenameIndex(
name: "IX_Reports_AppendixReportId",
table: "Reports",
newName: "IX_Reports_ParentReportId");
migrationBuilder.AddForeignKey(
name: "FK_Reports_Reports_ParentReportId",
table: "Reports",
column: "ParentReportId",
principalTable: "Reports",
principalColumn: "ReportId",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Reports_Reports_ParentReportId",
table: "Reports");
migrationBuilder.RenameColumn(
name: "ParentReportId",
table: "Reports",
newName: "AppendixReportId");
migrationBuilder.RenameIndex(
name: "IX_Reports_ParentReportId",
table: "Reports",
newName: "IX_Reports_AppendixReportId");
migrationBuilder.AddForeignKey(
name: "FK_Reports_Reports_AppendixReportId",
table: "Reports",
column: "AppendixReportId",
principalTable: "Reports",
principalColumn: "ReportId",
onDelete: ReferentialAction.Restrict);
}
}
}
|
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Shunxi.App.CellMachine.Converters
{
public class DateTimeToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo language)
{
try
{
var time = System.Convert.ToDateTime(value);
return time != DateTime.MinValue && time != default(DateTime) ? Visibility.Visible : Visibility.Collapsed;
}
catch (Exception)
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo language)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _08.ExtractSentence
{
class ExtractSentence
{
static void Main(string[] args)
{
/*Write a program that extracts from a given text all sentences containing given word.
Consider that the sentences are separated by "." and the words – by non-letter symbols.*/
string text = "We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day.We will move out of it in 5 days.";
string[] sentences = text.Split('.');
foreach (string s in sentences)
{
string[] words = s.Split(' ');
if (words.Contains("in"))
{
Console.WriteLine(s);
}
}
}
}
}
|
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UnityEngine_JointSpring : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
JointSpring jointSpring = default(JointSpring);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, jointSpring);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_spring(IntPtr l)
{
int result;
try
{
JointSpring jointSpring;
LuaObject.checkValueType<JointSpring>(l, 1, out jointSpring);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, jointSpring.spring);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_spring(IntPtr l)
{
int result;
try
{
JointSpring jointSpring;
LuaObject.checkValueType<JointSpring>(l, 1, out jointSpring);
float spring;
LuaObject.checkType(l, 2, out spring);
jointSpring.spring = spring;
LuaObject.setBack(l, jointSpring);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_damper(IntPtr l)
{
int result;
try
{
JointSpring jointSpring;
LuaObject.checkValueType<JointSpring>(l, 1, out jointSpring);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, jointSpring.damper);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_damper(IntPtr l)
{
int result;
try
{
JointSpring jointSpring;
LuaObject.checkValueType<JointSpring>(l, 1, out jointSpring);
float damper;
LuaObject.checkType(l, 2, out damper);
jointSpring.damper = damper;
LuaObject.setBack(l, jointSpring);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_targetPosition(IntPtr l)
{
int result;
try
{
JointSpring jointSpring;
LuaObject.checkValueType<JointSpring>(l, 1, out jointSpring);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, jointSpring.targetPosition);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_targetPosition(IntPtr l)
{
int result;
try
{
JointSpring jointSpring;
LuaObject.checkValueType<JointSpring>(l, 1, out jointSpring);
float targetPosition;
LuaObject.checkType(l, 2, out targetPosition);
jointSpring.targetPosition = targetPosition;
LuaObject.setBack(l, jointSpring);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UnityEngine.JointSpring");
LuaObject.addMember(l, "spring", new LuaCSFunction(Lua_UnityEngine_JointSpring.get_spring), new LuaCSFunction(Lua_UnityEngine_JointSpring.set_spring), true);
LuaObject.addMember(l, "damper", new LuaCSFunction(Lua_UnityEngine_JointSpring.get_damper), new LuaCSFunction(Lua_UnityEngine_JointSpring.set_damper), true);
LuaObject.addMember(l, "targetPosition", new LuaCSFunction(Lua_UnityEngine_JointSpring.get_targetPosition), new LuaCSFunction(Lua_UnityEngine_JointSpring.set_targetPosition), true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_JointSpring.constructor), typeof(JointSpring), typeof(ValueType));
}
}
|
using System;
namespace UInput
{
[Serializable]
public class InputByButton : InputComponet
{
InputAxis Horizontal = new InputAxis("Horizontal");
InputButton Jump = new InputButton("Jump");
public override float GetHorizontal()
{
return Horizontal.GetValue();
}
public override bool GetJump()
{
return Jump.GetDown();
}
}
} // namespace Input
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Crt.Model.Dtos.Region
{
public class RegionDto
{
[JsonPropertyName("id")]
public decimal RegionId { get; set; }
public decimal RegionNumber { get; set; }
public string RegionName { get; set; }
public DateTime? EndDate { get; set; }
[JsonPropertyName("name")]
public string Description { get => $"{RegionNumber}-{RegionName}"; }
public virtual ICollection<RegionDistrictDto> CrtRegionDistricts { get; set; }
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Otchi.Ebml.Types;
namespace Otchi.Ebml.Tests.Types
{
[TestClass]
public class EbmlDateTest
{
[TestMethod]
public void TestFromNanoseconds()
{
var date = EbmlDate.FromNanoSeconds(328711520000000000);
Console.WriteLine(date);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xadrez.TabuleiroEntities;
namespace Xadrez.PecasXadrez
{
class Cavalo : Peca
{
public Cavalo(Tabuleiro tabuleiro, Cor cor) : base(tabuleiro, cor)
{
}
public override string ToString()
{
return "C ";
}
public override bool[,] MovimentosPossiveis()
{
bool[,] matriz = new bool[TabuleiroPeca.Linhas, TabuleiroPeca.Colunas];
Posicao posicao = new Posicao(0, 0);
posicao.DefinirValores(PosicaoPeca.Linha - 1, PosicaoPeca.Coluna - 2);
if (TabuleiroPeca.PosicaoValida(posicao) && PodeMover(posicao))
matriz[posicao.Linha, posicao.Coluna] = true;
posicao.DefinirValores(PosicaoPeca.Linha - 2, PosicaoPeca.Coluna - 1);
if (TabuleiroPeca.PosicaoValida(posicao) && PodeMover(posicao))
matriz[posicao.Linha, posicao.Coluna] = true;
posicao.DefinirValores(PosicaoPeca.Linha - 2, PosicaoPeca.Coluna + 1);
if (TabuleiroPeca.PosicaoValida(posicao) && PodeMover(posicao))
matriz[posicao.Linha, posicao.Coluna] = true;
posicao.DefinirValores(PosicaoPeca.Linha - 1, PosicaoPeca.Coluna + 2);
if (TabuleiroPeca.PosicaoValida(posicao) && PodeMover(posicao))
matriz[posicao.Linha, posicao.Coluna] = true;
posicao.DefinirValores(PosicaoPeca.Linha + 1, PosicaoPeca.Coluna + 2);
if (TabuleiroPeca.PosicaoValida(posicao) && PodeMover(posicao))
matriz[posicao.Linha, posicao.Coluna] = true;
posicao.DefinirValores(PosicaoPeca.Linha + 2, PosicaoPeca.Coluna + 1);
if (TabuleiroPeca.PosicaoValida(posicao) && PodeMover(posicao))
matriz[posicao.Linha, posicao.Coluna] = true;
posicao.DefinirValores(PosicaoPeca.Linha + 2, PosicaoPeca.Coluna - 1);
if (TabuleiroPeca.PosicaoValida(posicao) && PodeMover(posicao))
matriz[posicao.Linha, posicao.Coluna] = true;
posicao.DefinirValores(PosicaoPeca.Linha + 1, PosicaoPeca.Coluna - 2);
if (TabuleiroPeca.PosicaoValida(posicao) && PodeMover(posicao))
matriz[posicao.Linha, posicao.Coluna] = true;
return matriz;
}
}
}
|
using System;
using Microsoft.WindowsCE.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace kkmKassa
{
public partial class confAddUsers : Form
{
bool isOpen = true;
private Global g;
public confAddUsers(Global g)
{
this.g = g;
InitializeComponent();
}
private void mainForm_Deactivate(object sender, EventArgs e)
{
if (isOpen)
this.Activate();
}
protected void SetKeyboardVisible(bool isVisible)
{
InputPanel aa = new InputPanel();
aa.Enabled = isVisible;
}
private void textBox1_GotFocus(object sender, EventArgs e)
{
SetKeyboardVisible(true);
}
private void textBox1_LostFocus(object sender, EventArgs e)
{
SetKeyboardVisible(false);
}
private void confEditUsers_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string asses = "";
if (this.checkBox1.Checked) asses += "1;"; else asses += "0;";
if (this.checkBox2.Checked) asses += "1;"; else asses += "0;";
if (this.checkBox3.Checked) asses += "1;"; else asses += "0;";
if (this.checkBox4.Checked) asses += "1;"; else asses += "0;";
if (this.checkBox5.Checked) asses += "1;"; else asses += "0;";
if (this.checkBox6.Checked) asses += "1;"; else asses += "0;";
if (this.checkBox7.Checked) asses += "1;"; else asses += "0;";
if (this.checkBox8.Checked) asses += "1;"; else asses += "0;";
if (this.checkBox9.Checked) asses += "1;"; else asses += "0;";
if (this.checkBox10.Checked) asses += "1;"; else asses += "0;";
g.db.FetchAllSql("INSERT INTO users (login,pass,info,asses) VALUES ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + asses + "')");
this.Close();
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Accounting.Entity
{
public class ReqDetail
{
public ReqDetail() { }
#region Fields
private int numReqDID = 0;
private int numReqMID = 0;
private int numItemID = 0;
private double numReqQty = 0;
private int numUnitID = 0;
private string strBudle_Pack_Qty = "";
private string strSpecifications = "";
private string strBudle_Pack_Size = "";
private int nCountID;
private int nSizeID;
private int nColorID;
#endregion
#region Properties
public int ReqDID
{
get { return numReqDID; }
set { numReqDID = value; }
}
public int ReqMID
{
get { return numReqMID; }
set { numReqMID = value; }
}
public int ItemID
{
get { return numItemID; }
set { numItemID = value; }
}
public double ReqQty
{
get { return numReqQty; }
set { numReqQty = value; }
}
public int UnitID
{
get { return numUnitID; }
set { numUnitID = value; }
}
public string Budle_Pack_Qty
{
get { return strBudle_Pack_Qty; }
set { strBudle_Pack_Qty = value; }
}
public string Specifications
{
get { return strSpecifications; }
set { strSpecifications = value; }
}
public string Budle_Pack_Size
{
get { return strBudle_Pack_Size; }
set { strBudle_Pack_Size = value; }
}
public int CountID
{
get { return nCountID; }
set { nCountID = value; }
}
public int SizeID
{
get { return nSizeID; }
set { nSizeID = value; }
}
public int ColorID
{
get { return nColorID; }
set { nColorID = value; }
}
#endregion
}
}
|
using System;
namespace Soko.Domain
{
/// <summary>
/// Summary description for FinansijskaCelina.
/// </summary>
public class FinansijskaCelina : DomainObject, IComparable
{
public static readonly int NAZIV_MAX_LENGTH = 50;
private string naziv;
public virtual string Naziv
{
get { return naziv; }
set { naziv = value; }
}
public FinansijskaCelina()
{
}
public override string ToString()
{
return Naziv;
}
public override void validate(Notification notification)
{
// validate Naziv
if (String.IsNullOrEmpty(Naziv))
{
notification.RegisterMessage(
"Naziv", "Naziv je obavezan.");
}
else if (Naziv.Length > NAZIV_MAX_LENGTH)
{
notification.RegisterMessage(
"Naziv", "Naziv moze da sadrzi maksimalno "
+ NAZIV_MAX_LENGTH + " znakova.");
}
}
#region IComparable Members
public virtual int CompareTo(object obj)
{
if (!(obj is FinansijskaCelina))
throw new ArgumentException();
FinansijskaCelina other = obj as FinansijskaCelina;
return this.Naziv.CompareTo(other.Naziv);
}
#endregion
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CloneDeploy_Entities
{
[Table("active_imaging_tasks", Schema = "public")]
public class ActiveImagingTaskEntity
{
public ActiveImagingTaskEntity()
{
Status = "0";
QueuePosition = 0;
}
[Column("task_arguments")]
public string Arguments { get; set; }
[Column("task_completed")]
public string Completed { get; set; }
[Column("computer_id")]
public int ComputerId { get; set; }
[NotMapped]
public string Direction { get; set; }
[Column("distribution_point_id")]
public int DpId { get; set; }
[Column("task_elapsed")]
public string Elapsed { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("active_task_id")]
public int Id { get; set; }
[Column("multicast_id")]
public int MulticastId { get; set; }
[Column("task_partition")]
public string Partition { get; set; }
[Column("task_queue_position")]
public int QueuePosition { get; set; }
[Column("task_rate")]
public string Rate { get; set; }
[Column("task_remaining")]
public string Remaining { get; set; }
[Column("task_status")]
public string Status { get; set; }
[Column("task_type")]
public string Type { get; set; }
[Column("user_id")]
public int UserId { get; set; }
[Column("last_update_time")]
public DateTime LastUpdateTime { get; set; }
}
[NotMapped]
public class TaskWithComputer : ActiveImagingTaskEntity
{
public ComputerEntity Computer { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FitChildPanel.Models.Classes
{
public class Oneriler
{
public int ID { get; set; }
public string OneriAdi { get; set; }
public string OneriResim { get; set; }
public string OneriFayda { get; set; }
public string OneriTavsiye { get; set; }
public string OneriCalisanBolge { get; set; }
public Nullable<System.DateTime> OneriEklenmeTarih { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace NapierBank.Models
{
/*
Class for displaying messages to the user
*/
class Info
{
public string Title { get; set; }
public string Body { get; set; }
// Constructor
public Info()
{
Title = "";
Body = "";
}
// Constructor
public Info(string title, string body)
{
Title = title;
Body = body;
}
// Displays message without parameters
public void DisplayMessage()
{
MessageBoxButton buttons = MessageBoxButton.OKCancel;
MessageBoxImage icon = MessageBoxImage.Information;
MessageBoxResult result = MessageBox.Show(Body, Title, buttons, icon);
}
// Displays message with parameters
public void DisplayMessage(string title, string body)
{
MessageBoxButton buttons = MessageBoxButton.OKCancel;
MessageBoxImage icon = MessageBoxImage.Information;
MessageBoxResult result = MessageBox.Show(body, title, buttons, icon);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ApplicationNavigation.Model
{
public class Mage : PlayerCharacter
{
public Mage()
{
}
~Mage()
{
}
}
} |
using System;
using Android.App;
using Android.Hardware;
using Android.Media;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
using Android.Views;
namespace DoggySee
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
public class MainActivity : AppCompatActivity, ISensorEventListener
{
private SensorManager _sensorManager;
private MediaPlayer _mediaPlayer;
private DateTime _lastBeep;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
_sensorManager = (SensorManager)this.GetSystemService(SensorService);
_mediaPlayer = MediaPlayer.Create(global::Android.App.Application.Context, Resource.Raw.beep);
if (_sensorManager.GetSensorList(SensorType.Proximity).Count != 0)
{
var proximitySensor = _sensorManager.GetDefaultSensor(SensorType.Proximity);
_sensorManager.RegisterListener(this, proximitySensor, SensorDelay.Normal);
}
Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
fab.Click += FabOnClick;
}
public void OnAccuracyChanged(Sensor sensor, SensorStatus accuracy)
{
//todo
}
public void OnSensorChanged(SensorEvent e)
{
Beep();
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.menu_main, menu);
return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
int id = item.ItemId;
if (id == Resource.Id.action_settings)
{
return true;
}
return base.OnOptionsItemSelected(item);
}
private void FabOnClick(object sender, EventArgs eventArgs)
{
View view = (View)sender;
Snackbar.Make(view, "Send questions to davepadot@gmail.com", Snackbar.LengthLong)
.SetAction("Action", (Android.Views.View.IOnClickListener)null).Show();
}
public bool Beep()
{
if (DateTime.Now.Subtract(_lastBeep).TotalMilliseconds > 1200)
_mediaPlayer.Start();
_lastBeep = DateTime.Now;
return true;
}
}
}
|
using System;
namespace SGDE.Domain.Entities
{
public class Advance : BaseEntity
{
public DateTime ConcessionDate { get; set; }
public DateTime? PayDate { get; set; }
public double Amount { get; set; }
public string Observations { get; set; }
public bool Paid => PayDate != null;
public int UserId { get; set; }
public virtual User User { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using Renting.Domain.Drafts;
namespace Renting.Persistence.InMemory
{
public class InMemoryDraftRepository : IDraftRepository
{
private static readonly List<Draft> Drafts = new List<Draft>();
public Draft Get(DraftId draftId)
{
return Drafts.SingleOrDefault(d => d.Id.Equals(draftId));
}
public void Save(Draft draft)
{
Drafts.Add(draft);
}
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System.Xml;
using System.Xml.Serialization;
using DotNetNuke.Services.Tokens;
using DotNetNuke.Security.Roles;
using System.Collections;
using DotNetNuke.Security.Roles.Internal;
using System;
#endregion
namespace DotNetNuke.Entities.Groups
{
public class GroupInfo : RoleInfo, IPropertyAccess
{
//private RoleInfo roleInfo;
public GroupInfo() {
}
public GroupInfo(RoleInfo roleInfo) {
RoleID = roleInfo.RoleID;
RoleName = roleInfo.RoleName;
Description = roleInfo.Description;
PortalID = roleInfo.PortalID;
SecurityMode = roleInfo.SecurityMode;
ServiceFee = roleInfo.ServiceFee;
RSVPCode = roleInfo.RSVPCode;
}
//public RoleInfo Role {
// get {
// return roleInfo;
// }
// set {
// roleInfo = value;
// }
//}
//public int GroupId {
// get {
// return RoleID;
// }
//}
//public int ModuleId { get; set; }
public string Street {
get {
return GetString("Street", string.Empty);
}
set {
SetString("Street",value);
}
}
public string City {
get {
return GetString("City", string.Empty);
}
set {
SetString("City", value);
}
}
public string Region {
get {
return GetString("Region", string.Empty);
}
set {
SetString("Region",value);
}
}
public string Country {
get {
return GetString("Country", string.Empty);
}
set {
SetString("Country",value);
}
}
public string PostalCode {
get {
return GetString("PostalCode", string.Empty);
}
set {
SetString("PostalCode",value);
}
}
public string Website {
get {
return GetString("Website", string.Empty);
}
set {
SetString("Website",value);
}
}
public bool Featured {
get {
return Convert.ToBoolean(GetString("Featured","false"));
}
set {
SetString("Featured", value.ToString());
}
}
private string GetString(string keyName, string defaultValue) {
if (Settings == null) {
return defaultValue;
}
if (Settings.ContainsKey(keyName)) {
return Settings[keyName];
} else {
return defaultValue;
}
}
private void SetString(string keyName, string value) {
if (Settings.ContainsKey(keyName)) {
Settings[keyName] = value;
} else {
Settings.Add(keyName, value);
}
}
}
}
|
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using MyMedicine.Models.Chat;
namespace MyMedicine.Middleware
{
public class ChatMiddleware
{
private static ConcurrentDictionary<string, WebSocket> _sockets = new ConcurrentDictionary<string, WebSocket>();
private static ConcurrentQueue<MessageModel> messages = new ConcurrentQueue<MessageModel>();
private static DateTime DateLastUpdate = DateTime.UtcNow;
private readonly RequestDelegate _next;
public ChatMiddleware(RequestDelegate next)
{
_next = next;
Task.Factory.StartNew(CounterUpdater);
}
public async Task Invoke(HttpContext context)
{
if (!context.WebSockets.IsWebSocketRequest || context.Request.Path != "/wschat")
{
await _next.Invoke(context);
return;
}
CancellationToken ct = context.RequestAborted;
WebSocket currentSocket = await context.WebSockets.AcceptWebSocketAsync();
var socketId = Guid.NewGuid().ToString();
_sockets.TryAdd(socketId, currentSocket);
Console.WriteLine($"info: chat socket connected.");
string response;
MessageModel message;
while (true)
{
if (ct.IsCancellationRequested)
break;
try
{
response = await currentSocket.ReceiveStringAsync(ct);
}
catch (Exception exp)
{
Console.WriteLine($"info: socket aborted.\nMore info: {exp.Message}");
break;
}
if (string.IsNullOrEmpty(response))
{
if (currentSocket.State != WebSocketState.Open)
break;
continue;
}
try
{
if (response == "GetMessages")
{
var savedMessages = messages.ToArray();
if (savedMessages.Length > 0)
foreach (var ms in savedMessages)
await _sockets[socketId].SendStringAsync(ms, ct);
await _sockets[socketId].SendStringAsync(_sockets.Count, ct);
continue;
}
else
{
message = JsonConvert.DeserializeObject<MessageModel>(response);
messages.AddNewMessage(message);
}
}
catch
{
continue;
}
foreach (var socket in _sockets)
{
if (socket.Value.State != WebSocketState.Open)
continue;
await socket.Value.SendStringAsync(message, _sockets.Count, ct);
}
}
_sockets.TryRemove(socketId, out _);
if (currentSocket.State != WebSocketState.Aborted)
await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);
currentSocket.Dispose();
Console.WriteLine($"WebSocket disconnect from chat: {socketId}");
}
private async void CounterUpdater()
{
while (true)
{
Thread.Sleep(60000);
if (!_sockets.IsEmpty)
foreach (var socket in _sockets)
if (socket.Value.State == WebSocketState.Open)
await socket.Value.SendStringAsync(_sockets.Count);
}
}
}
}
|
using StockData.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StockData.Repository
{
public static class WarehouseProductsHandler
{
public static void AddToWarehouse(ProductQuantity product, List<ProductQuantity> warehouseValues)
{
var productInfo = warehouseValues.SingleOrDefault(x => x.ProductId == product.ProductId);
if (productInfo != null)
productInfo.Quantity += product.Quantity;
else
{
warehouseValues.Add(new ProductQuantity
{
ProductId = product.ProductId,
Quantity = product.Quantity,
});
}
}
public static int GetAllProductsQuantity(IEnumerable<ProductQuantity> stock)
=> stock.Sum(x => x.Quantity);
public static void FillProductsInfoInWarehouse(Dictionary<string, List<ProductQuantity>> warehousesWithProducts, IEnumerable<string> lines)
{
foreach (var line in lines)
FillProductsInfoInWarehouse(warehousesWithProducts, line);
}
public static void FillProductsInfoInWarehouse(Dictionary<string, List<ProductQuantity>>warehousesWithProducts, string line)
{
if (string.IsNullOrWhiteSpace(line))
return;
var records = line.Split(';');
if (records == null || records.Length < 3)
return;
var product = new Product { ProductId = records[1], ProductName = records[0] };
var warehouses = records.Skip(2).FirstOrDefault()?.Split('|');
foreach (var warehouseData in warehouses)
{
var warehouseRecords = warehouseData.Split(',');
var warehouseId = warehouseRecords[0];
var quantityStr = warehouseRecords[1];
if (!int.TryParse(quantityStr, out var quantity))
continue;
if (!warehousesWithProducts.ContainsKey(warehouseId))
{
var productsQuantities = new List<ProductQuantity>();
var productQuantity = new ProductQuantity
{
ProductId = product.ProductId,
Quantity = quantity,
};
AddToWarehouse(productQuantity, productsQuantities);
warehousesWithProducts.Add(warehouseId, productsQuantities);
}
else
{
var warehouse = warehousesWithProducts[warehouseId];
AddToWarehouse(new ProductQuantity
{
ProductId = product.ProductId,
Quantity = quantity,
}, warehouse);
}
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data.SqlClient;
using YoctoScheduler.Core.Database;
namespace YoctoScheduler.UnitTest.Daatabase
{
[TestClass]
public class Task_Test
{
[TestMethod]
public void Task_Insert_PassthroughTask()
{
YoctoScheduler.Core.ExecutionTasks.Passthrough.PassthroughTask pt = new Core.ExecutionTasks.Passthrough.PassthroughTask();
pt.Configuration = "Some data";
Task t = pt.GenerateDatabaseTask();
t.Name = "Unit test Passthrough";
t.Description = t.Name + " description";
t.ReenqueueOnDead = true;
using (SqlConnection conn = new SqlConnection(Config.CONNECTION_STRING))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
Task.Insert(conn, trans, t);
trans.Commit();
}
}
}
[TestMethod]
public void Task_Insert_WaitTask()
{
YoctoScheduler.Core.ExecutionTasks.WaitTask.WaitTask wt = new Core.ExecutionTasks.WaitTask.WaitTask();
wt.Configuration = new Core.ExecutionTasks.WaitTask.Configuration() { SleepSeconds = 200 };
Task t = wt.GenerateDatabaseTask();
t.Name = "Unit test Mock";
t.Description = t.Name + " description";
t.ReenqueueOnDead = true;
using (SqlConnection conn = new SqlConnection(Config.CONNECTION_STRING))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
Task.Insert(conn, trans, t);
trans.Commit();
}
}
}
}
}
|
using System;
namespace OOP_FinalProject
{
class VerticalLine : Shape, IMathShape
{
#region Data-Memebers
private int secondY;
private int thickness;
#endregion
#region Ctors
public VerticalLine() { }
public VerticalLine(int x, int y, ConsoleColor color, int secondy, int thickness) : base(x, y, color)
{
SecondY = secondy;
Thickness = thickness;
}
#endregion
#region Property
/// <summary>
/// Represent the second Y that the line sould be, the value must be between 0-24!.
/// </summary>
public int SecondY
{
set
{
if (value < 0 || value > 25)
throw new Exception("SecondY value must be between 0-25");
secondY = value;
}
get
{
return secondY;
}
}
/// <summary>
/// Represent the thickness of the line, value must be between 1-3!.
/// </summary>
public int Thickness
{
set
{
if (value < 1 || value > 3)
throw new Exception("Thickness value must be between 1-3");
thickness = value;
}
get
{
return thickness;
}
}
#endregion
#region Methods
public override string ToString()
{
return string.Format(base.ToString() + " {0} {1}", secondY, thickness);
}
/// <summary>
/// Start drawing the vertical line throw the console interface.
/// </summary>
public override void Draw()
{
if (CheckValidate() == false)
InitWithRandomValues();
Console.ForegroundColor = Color;
if (Y > secondY)
Console.SetCursorPosition(X, secondY);
else
Console.SetCursorPosition(X, Y);
for (int i = 1; i <= GetPerimeter(); i++)
{
Console.CursorLeft = X;
for (int j = 1; j <= thickness; j++)
Console.Write("*");
Console.WriteLine();
}
Console.ResetColor();
}
/// <summary>
/// Get the area of the vertical line.
/// </summary>
/// <returns>0</returns>
public double GetArea()
{
return 0;
}
/// <summary>
/// Get the perimeter of the vertical line.
/// </summary>
/// <returns>the length of the line.</returns>
public double GetPerimeter()
{
return (Y > secondY) ? Y - secondY : secondY - Y;
}
/// <summary>
/// Fill all vertical line with random values.
/// </summary>
public override void InitWithRandomValues()
{
base.InitWithRandomValues();
secondY = rand.Next(0, 25); // random number between 0-24
thickness = rand.Next(1, 4); // random number between 1-3
if (CheckValidate() == false)
InitWithRandomValues();
}
/// <summary>
/// Show all details of the vertical line in the console.
/// </summary>
public override void ShowDetails()
{
base.ShowDetails();
Console.WriteLine("Shape Name: Vertical Line");
Console.WriteLine("Second Point Y: " + secondY);
Console.WriteLine("Second Point X: " + X);
Console.WriteLine("Area: 0");
Console.WriteLine("Perimeter: " + GetPerimeter());
Console.WriteLine("Thickness: " + thickness);
}
#endregion
// private function.
private bool CheckValidate()
{
// just to make the line seems like a real line.
if (GetPerimeter() < 4)
return false;
if (Y < secondY)
{
// thats mean its gonna start write from Y, check if its gonna be write overflow-y
if ((Y + GetPerimeter()) >= 25)
return false;
}
else
{
// thats mean its gonna start write from secondY, check if its gonna be write overflow-y
if (secondY + GetPerimeter() >= 25)
return false;
}
// check if thickness is more than 1 becase then need to check if its gonna be write overflow-x
if (thickness > 1)
{
if (X + thickness >= 80)
return false;
}
// get from where its gonna start writing
int num = Y < secondY ? Y : secondY;
// then check if it is between 0-9 (in ShowDetails function message)
if (num >= 0 && num <= 9)
{
// then check if its gonna be override ShowDetails function messages.
if (X < 30)
return false;
}
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleApp
{
public delegate int MyDelegate(int a, int b);
class Program
{
static void Main(string[] args)
{
Service1 s1 = new Service1();
Client c1 = new Client(s1);
c1.Serve();
Service2 s2 = new Service2();
Client c2 = new Client(s2);
c2.Serve();
MyDelegate del = new MyDelegate(MyClass.Add);
Console.WriteLine("The sum of 5 and 6 is: " + del(5, 6));
del = new MyDelegate(MyClass.Multiply);
Console.WriteLine("The sum of 5 and 6 is: " + del(5, 6));
}
}
interface IService
{
void Print();
}
class Service1 : IService
{
public void Print()
{
Console.WriteLine("Printing for Service1");
}
}
class Service2 : IService
{
public void Print()
{
Console.WriteLine("Printing for Service2");
}
}
class Client
{
IService _service;
public Client(IService service)
{
this._service = service;
}
public void Serve()
{
_service.Print();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data;
using MySql.Web;
using MySql.Data.MySqlClient;
namespace ProjectMFS
{
public partial class ParticipantDataView : System.Web.UI.Page
{
string WIN = "";
protected void Page_Load(object sender, EventArgs e)
{
bool add = bool.TryParse(Request.QueryString["Add"], out add) == true ? add : false;
WIN = Request.QueryString["WIN"];
if (((SiteMaster)this.Master).IsLoggedIn)
{
this.LoginPanel.Visible = false;
if (add && !String.IsNullOrEmpty(WIN)) //Adding new participant
{
this.MainDataPanel.Visible = true;
this.WINLabel.Text = WIN;
HowHeardDropDownDataSource();
}
else if (!String.IsNullOrEmpty(WIN)) //Load Existing Participant
{
this.MainDataPanel.Visible = true;
this.WINLabel.Text = WIN;
HowHeardDropDownDataSource();
LoadParticipant();
}
}
}
protected void LoadBanner_Click(object sender, EventArgs e)
{
LoadBanner(Int32.Parse(this.WINLabel.Text));
}
protected void Update_Click(object sender, EventArgs e)
{
}
/// <summary>
/// MAYBE GET RID OF THIS AND USE AN SQLDATASOURCE
/// </summary>
protected void HowHeardDropDownDataSource()
{
try
{
MySqlConnection mycon = new MySql.Data.MySqlClient.MySqlConnection(ConfigurationManager.ConnectionStrings["mfs"].ToString());
mycon.Open();
MySql.Data.MySqlClient.MySqlCommand mycmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT HowHeard FROM projectmfs.contacttypes;", mycon);
using (MySql.Data.MySqlClient.MySqlDataReader reader = mycmd.ExecuteReader())
{
while (reader.Read())
{
this.HowHeardDropDown.Items.Add(reader["HowHeard"].ToString());
}
reader.Close();
}
mycon.Close();
}
catch (Exception e)
{
EventLog logger = new EventLog();
logger.Source = "Load ContactTypes Failed";
logger.WriteEntry("Page: ParticipantDataView", EventLogEntryType.Error);
}
}
protected void LoadBanner(int win)
{
//load new data from banner
}
protected void LoadParticipant()
{
//do query, set things, set dropdown, etc
}
}
} |
using System.Collections.Generic;
using Data.Core;
using LearningEnglishWeb.Areas.Training.Models.Shared;
namespace LearningEnglishWeb.Areas.Training.Models.ChooseTranslate
{
public class ChooseTranslateTraining : TrainingBase<QuestionWithOptions>
{
public ChooseTranslateTraining(IEnumerable<QuestionWithOptions> questions, bool isReverse = false)
: base(questions, TrainingTypeEnum.ChooseTranslate, isReverse)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MisRecetas.Modelo
{
//Hago publica la clase para poder acceder o instanciarla desde otro lado del proyecto
public class Paciente
{
//Declaro las variables con sus tipos de dato.
public int Id_Paciente { get; set; }
public int Id_TipoDocumento { get; set; }
public String Nro_Documento { get; set; }
public String Nombre_Paciente { get; set; }
public String Apellido_Paciente { get; set; }
public String Email { get; set; }
//Metodo constructor para generar nuevos objetos.
public Paciente(int id_Paciente, int id_TipoDocumento, string nro_Documento, string nombre, string apellido, String email)
{
Id_Paciente = id_Paciente;
Id_TipoDocumento = id_TipoDocumento;
Nro_Documento = nro_Documento;
Nombre_Paciente = nombre;
Apellido_Paciente = apellido;
Email = email;
}
//Metodo constructor vacio para manipular y mostrar datos.
public Paciente()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common
{
public class ActionEnum
{
/// <summary>
/// 操作类型
/// </summary>
public enum Type
{
Add = 1,
Edit = 2,
Delete = 3,
LOGIN = 4
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using ChesterDevs.Core.Aspnet.App.Jobs;
using ChesterDevs.Core.Aspnet.Models.ViewModels;
using Microsoft.Extensions.Logging;
namespace ChesterDevs.Core.Aspnet.App.PageHelpers
{
public interface IJobListHelper
{
Task<JobListViewModel> LoadViewModelAsync(int pageNumber, CancellationToken cancellationToken);
}
public class JobListHelper : IJobListHelper
{
private const int PageSize = 10;
private readonly ILogger<JobListHelper> _logger;
private readonly IJobService _jobService;
public JobListHelper(ILogger<JobListHelper> logger, IJobService jobService)
{
_logger = logger;
_jobService = jobService;
}
public async Task<JobListViewModel> LoadViewModelAsync(int pageNumber, CancellationToken cancellationToken)
{
var jobPage = await _jobService.GetJobsAsync(pageNumber, PageSize, cancellationToken);
if (!(jobPage?.Status?.Success ?? true))
{
_logger.LogWarning($"Job load failed for page {pageNumber}");
}
return new JobListViewModel()
{
JobListPage = jobPage,
PageNumber = pageNumber
};
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace homeworkCSharp2020
{
class nal12
{
public static void func(int userInput)
{
if( userInput > 99999 && userInput < 999999)
{
string full = userInput.ToString();
string part1 = full.Substring(0, 3);
string part2 = full.Substring(3);
int part1Converted = Convert.ToInt32(part1);
int part2Converted = Convert.ToInt32(part2);
int result = part1Converted + part2Converted;
Console.WriteLine("Sestevek prvih in zadnjih treh stevil ({0}) = {1}", userInput, result);
}
else
{
Console.WriteLine("Stevilo ne ustreza pogojem");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Coll_Si7 : MonoBehaviour {
public ring_coll co;
public UIHP playerUI;
// Use this for initialization
void Start () {
co = FindObjectOfType<ring_coll> ();
playerUI = FindObjectOfType<UIHP> ();
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision other)
{
if (co.count <= 0) {
SceneManager.LoadScene ("Fail Scene");
Destroy (playerUI.gameObject);
}
else
SceneManager.LoadScene("Final Scene");
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class attendReception : GAction
{
public override bool PrePerform()
{
GWorld.Instance.GetWorld().ModifyState("receptionAttended",1);
return true;
}
public override bool PostPerform()
{
GWorld.Instance.GetWorld().ModifyState("receptionAttended",-1);
return true;
}
}
|
namespace AquaServiceSPA.Models
{
public class Express
{
public double AquaLiters { get; set; }
public double ContainerCapacity { get; set; }
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using LCTP;
using LCTP.Server;
namespace LctpTestServer
{
class Program
{
static int Main(string[] args)
{
Console.WriteLine("LCTP Test Server v0.0");
using (var source = new CancellationTokenSource())
{
Console.CancelKeyPress += (s, e) => source.Cancel();
try
{
var port = args.Length > 0 && int.TryParse(args[0], out var v) ? v : LctpServer.DefaultPort;
Run(port, source.Token).Wait(source.Token);
return 0;
}
catch (OperationCanceledException)
{
Console.WriteLine("Exiting ...");
}
catch (AggregateException e)
{
Console.WriteLine(e.InnerException);
return -1;
}
catch (Exception e)
{
Console.WriteLine(e);
return -1;
}
finally
{
Console.WriteLine("Bye!");
}
}
return 0;
}
private static async Task Run(int port, CancellationToken cancellationToken)
{
using(var server = new LctpServer(port, new EchoController()))
{
await server.Start(cancellationToken);
}
}
}
public class EchoController : IController
{
public void ConnectionClosed()
{
}
public void ConnectionOpened()
{
}
public Task<ResponseMessage> Execute(RequestMessage request)
{
Console.WriteLine(request);
return Task.FromResult(new ResponseMessage
{
Content = request.Content
});
}
}
}
|
using Programa_de_descuentos.Compra1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Programa_de_desucnetos.Descuentos
{
class NClsDescuentos
{
private int dia;
private double compra;
private double descuento;
private double total;
public NClsDescuentos()
{
}
public NClsDescuentos(int dia, double compra)
{
this.dia = dia;
this.compra = compra;
}
public NClsDescuentos(int dia, double compra, double descuento, double total)
{
this.dia = dia;
this.compra = compra;
this.descuento = descuento;
this.total = total;
}
public int Dia { get => dia; set => dia = value; }
public double Compra { get => compra; set => compra = value; }
public double Descuento { get => descuento; set => descuento = value; }
internal bool NClsDescuento(Clscompras clsCompra)
{
throw new NotImplementedException();
}
internal bool NClsDescuento(NClscompras clsCompra)
{
throw new NotImplementedException();
}
public double Total { get => total; set => total = value; }
}
}
|
using LuigiApp.Base.ViewModels;
using LuigiApp.Product.Interactors;
using LuigiApp.Product.Models;
using LuigiApp.Product.Views;
using LuigiApp.Resources;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace LuigiApp.Product.ViewModels
{
public class ProductsViewModel : BaseViewModel
{
public ObservableCollection<Models.Product> Products { get; }
public Command LoadProductsCommand { get; }
public Command AddProductCommand { get; }
public Command<Models.Product> ProductTapped { get; }
public ProductsViewModel()
{
Title = Literals.Products;
Products = new ObservableCollection<Models.Product>();
LoadProductsCommand = new Command(async () => await ExecuteLoadProductsCommand());
ProductTapped = new Command<Models.Product>(OnProductSelected);
AddProductCommand = new Command(OnAddProduct);
}
async Task ExecuteLoadProductsCommand()
{
IsBusy = true;
try
{
this.Products.Clear();
var products = await ProductInteractor.All();//await DataStore.GetProductsAsync(true);
foreach (var product in products)
{
Products.Add(product);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
public void OnAppearing()
{
IsBusy = true;
}
private async void OnAddProduct(object obj)
{
await Navigation.NavigateTo(nameof(NewProductPage), new Models.Product());
}
private async void OnProductSelected(Models.Product product)
{
await Navigation.NavigateTo(nameof(NewProductPage), product);
}
}
}
|
using System;
namespace UserStorageServices.Validation.Attributes
{
internal sealed class ValidateMaxLengthAttribute : ValidationAttribute
{
public ValidateMaxLengthAttribute(int maxLength)
{
MaxLength = maxLength;
ErrorMesage = "Length of property is bigger then max length.";
}
public int MaxLength { get; }
public override bool IsValid(object value)
{
var isValid = false;
if (value is string s)
{
isValid = s.Length <= MaxLength;
}
else if (value is Array array)
{
isValid = array.Length <= MaxLength;
}
return isValid;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bracelet : MonoBehaviour {
public GameObject fireGlowPrefab;
public GameObject waterGlowPrefab;
public GameObject earthGlowPrefab;
public GameObject airGlowPrefab;
private Animator glowAnimator;
public void SetElement(ElementPower element)
{
switch (element)
{
case ElementPower.Air:
ReplaceGlow(airGlowPrefab);
break;
case ElementPower.Earth:
ReplaceGlow(earthGlowPrefab);
break;
case ElementPower.Fire:
ReplaceGlow(fireGlowPrefab);
break;
case ElementPower.Water:
ReplaceGlow(waterGlowPrefab);
break;
}
}
public void Die()
{
glowAnimator.SetTrigger("die");
}
private void ReplaceGlow(GameObject newGlow)
{
if(glowAnimator != null)
{
Destroy(glowAnimator.gameObject);
}
GameObject glow = Instantiate(newGlow, transform);
glow.SetActive(true);
glowAnimator = glow.GetComponent<Animator>();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObstacleGenerator : MonoBehaviour
{
public GameObject[] obstacles;
public int initialSpawnAmount;
public int maximumSpawnAmount;
public int spawnAmountIncreaseDistance;
public float initialSpawnOffsetX;
public float initialSpawnOffsetY;
public float spawnVarianceX;
public float spawnVarianceY;
public float despawnOffsetX;
public float despawnOffsetY;
private Transform player;
private List<GameObject> spawnedObstacles;
private int curSpawnAmount;
private void Start()
{
spawnedObstacles = new List<GameObject>();
player = GameObject.Find("Player").transform;
curSpawnAmount = initialSpawnAmount;
}
private void Update()
{
if (player == null)
return;
if (spawnedObstacles.Count < curSpawnAmount) //Spawn Obstacles
{
Vector2 spawnPosition = player.position + new Vector3(initialSpawnOffsetX, 0);
for (int i = 0; i < curSpawnAmount - spawnedObstacles.Count; i++)
{
Vector2 spawnOffset = new Vector2(0, Random.Range(-spawnVarianceY, spawnVarianceY));
if (spawnOffset.y > initialSpawnOffsetY || spawnOffset.y < -initialSpawnOffsetY)
spawnOffset.x = Random.Range(-(spawnVarianceX + initialSpawnOffsetX), spawnVarianceX);
else
spawnOffset.x = Random.Range(0, spawnVarianceX);
spawnedObstacles.Add(Instantiate(obstacles[Random.Range(0, obstacles.Length)], spawnPosition + spawnOffset, Quaternion.identity, transform));
}
}
else
{
for (int i = 0; i < spawnedObstacles.Count; i++)
{
if (spawnedObstacles[i] == null)
{
spawnedObstacles.RemoveAt(i);
return;
}
if (spawnedObstacles[i].transform.position.x < player.position.x - despawnOffsetX || spawnedObstacles[i].transform.position.y < player.position.y - despawnOffsetY || spawnedObstacles[i].transform.position.y > player.position.y + despawnOffsetY) //Remove Obstacles
{
GameObject go = spawnedObstacles[i];
spawnedObstacles.RemoveAt(i);
Destroy(go);
}
}
}
if (player.position.x > spawnAmountIncreaseDistance * (1 + curSpawnAmount - initialSpawnAmount))
{
if (curSpawnAmount < maximumSpawnAmount)
curSpawnAmount++;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace OnlineShopping
{
public partial class GoodAdd : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if (DBHelper.Select("select * from Goods").Tables[0].Rows.Count != 0)
txtgid.Text = (Convert.ToInt32(DBHelper.Select("select max(gid) from Goods").Tables[0].Rows[0][0]) + 1).ToString();
else
txtgid.Text = "1";
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if(txtGoodName.Text=="")
{
Response.Write("<script>alert('请输入商品名称')</script>");
return;
}
if (txtGoodPrice.Text == "")
{
Response.Write("<script>alert('请输入商品价格')</script>");
return;
}
else
{
try
{
Convert.ToSingle(txtGoodPrice.Text);
}
catch(Exception ex)
{
Response.Write("<script>alert('商品价格格式错误')</script>");
return;
}
}
if (ddlCategory.Text == "请选择商品类别")
{
Response.Write("<script>alert('请选择商品类别')</script>");
return;
}
if (txtGoodNum.Text == "")
{
Response.Write("<script>alert('请输入商品数量')</script>");
return;
}
else
{
try
{
Convert.ToInt32(txtGoodNum.Text);
}
catch (Exception ex)
{
Response.Write("<script>alert('商品数量格式错误')</script>");
return;
}
}
if(!fuploadGoodPic.HasFile)
{
Response.Write("<script>alert('请上传商品图片')</script>");
return;
}
if (txtGoodShow.Text == "")
{
Response.Write("<script>alert('请输入商品介绍')</script>");
return;
}
if(!imgUpdate())
{
Response.Write("<script>alert('上传失败,请检查文件类型和网络')</script>");
return;
}
if (DBHelper.Update("insert into Goods (gid,GoodName,GoodPrice,Category,GoodNum,GoodPic,GoodShow,GoodTime)" +
" values(" + Convert.ToInt32(txtgid.Text) + ",'" + txtGoodName.Text + "'," + Convert.ToSingle(txtGoodPrice.Text) + ",'" + ddlCategory.SelectedIndex.ToString() + "'," + Convert.ToInt32(txtGoodNum.Text) + ",'" + fuploadGoodPic.FileName + "','" + txtGoodShow.Text + "','" + DateTime.Now.ToString() + "')"))
{
Response.Write("<script>alert('添加商品成功');window.location.href='GoodAdd.aspx'</script>");
}
else
{
Response.Write("<script>alert('添加商品失败')</script>");
}
}
protected bool imgUpdate()
{
string name = fuploadGoodPic.FileName; //上传文件名
string size = fuploadGoodPic.PostedFile.ContentLength.ToString(); //文件大小(字节)
string type = fuploadGoodPic.PostedFile.ContentType; //获取上传文件的MIME内容类型
string type1 = name.Substring(name.LastIndexOf(".") + 1); //name.LastIndexOf(".")索引name中"."的位置+1,就是后缀名的index
string ipath = Server.MapPath("Images") + "\\" + name;
if (type1 == "jpg" || type1 == "gif" || type1 == "bmp" || type1 == "png")
{
try
{
fuploadGoodPic.SaveAs(ipath);
return true;//上传成功
}
catch(Exception ex)
{
return false;//上传出现异常
}
}
else
{
return false;//文件类型不正确
}
}
}
} |
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace DuaControl.Web.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Clientes",
columns: table => new
{
BusinessName = table.Column<string>(maxLength: 100, nullable: false),
ClienteId = table.Column<string>(maxLength: 10, nullable: false),
Name = table.Column<string>(maxLength: 100, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Clientes", x => x.ClienteId);
});
migrationBuilder.CreateTable(
name: "Puertos",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Puertos", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Roles",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(type: "varchar(50)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Roles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserName = table.Column<string>(nullable: false),
FirstName = table.Column<string>(nullable: true),
LastName = table.Column<string>(nullable: true),
IsActive = table.Column<bool>(nullable: false),
LastLoginDate = table.Column<DateTime>(nullable: false),
CreatedOn = table.Column<DateTime>(nullable: false),
CreatedBy = table.Column<string>(nullable: true),
ModifiedOn = table.Column<DateTime>(nullable: false),
ModifiedBy = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Facturas",
columns: table => new
{
ClienteId = table.Column<string>(nullable: true),
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
InvoiceDate = table.Column<DateTime>(nullable: false),
InvoiceNumber = table.Column<string>(maxLength: 15, nullable: false),
PortId = table.Column<int>(nullable: true),
Remarks = table.Column<string>(nullable: true),
Details = table.Column<string>(nullable: true),
InvoiceUser = table.Column<string>(maxLength: 15, nullable: true),
InvoiceSystem = table.Column<string>(maxLength: 15, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Facturas", x => x.Id);
table.ForeignKey(
name: "FK_Facturas_Clientes_ClienteId",
column: x => x.ClienteId,
principalTable: "Clientes",
principalColumn: "ClienteId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Facturas_Puertos_PortId",
column: x => x.PortId,
principalTable: "Puertos",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "UserRoles",
columns: table => new
{
UserId = table.Column<int>(nullable: false),
RoleId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_UserRoles_Roles",
column: x => x.RoleId,
principalTable: "Roles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UserRoles_Users",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Adjuntos",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
RegisterDate = table.Column<DateTime>(nullable: false),
User = table.Column<string>(type: "VARCHAR(20)", maxLength: 20, nullable: true),
DocumentName = table.Column<string>(type: "VARCHAR(120)", maxLength: 120, nullable: true),
FacturaId = table.Column<int>(nullable: true),
DocumentUrl = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Adjuntos", x => x.Id);
table.ForeignKey(
name: "FK_Adjuntos_Facturas_FacturaId",
column: x => x.FacturaId,
principalTable: "Facturas",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Adjuntos_FacturaId",
table: "Adjuntos",
column: "FacturaId");
migrationBuilder.CreateIndex(
name: "IX_Facturas_ClienteId",
table: "Facturas",
column: "ClienteId");
migrationBuilder.CreateIndex(
name: "IX_Facturas_PortId",
table: "Facturas",
column: "PortId");
migrationBuilder.CreateIndex(
name: "IX_UserRoles_RoleId",
table: "UserRoles",
column: "RoleId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Adjuntos");
migrationBuilder.DropTable(
name: "UserRoles");
migrationBuilder.DropTable(
name: "Facturas");
migrationBuilder.DropTable(
name: "Roles");
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.DropTable(
name: "Clientes");
migrationBuilder.DropTable(
name: "Puertos");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenCloudPrinciple_OCP_.ModelClasses.FilteringComputerMonitor.ImplementOCP
{
public interface ISpecification<T>
{
bool isSatisfied(T item);
}
}
|
using System;
namespace Ex3
{
class Program
{
static void Main(string[] args)
{
string radiusAsString;
double radius, perimeterOrArea;
Console.WriteLine("Enter radius: ");
radiusAsString = Console.ReadLine();
radius = Radius(radiusAsString);
perimeterOrArea = 2 * Math.PI * radius;
Console.WriteLine($"The perimeter of the circle is: {perimeterOrArea}");
perimeterOrArea = Math.Pow(radius,2) * Math.PI;
Console.WriteLine($"The area of the circle is: {perimeterOrArea}");
}
static double Radius(string radiusAsString)
{
double radius;
double.TryParse(radiusAsString, out radius);
return radius;
}
}
}
|
using System.Collections.ObjectModel;
using System.Linq;
using Athena.Data;
using Athena.Data.Categories;
using Athena.Data.PublishingHouses;
using Athena.Data.Series;
using Athena.Data.StoragePlaces;
using Microsoft.EntityFrameworkCore;
namespace Athena {
public static class DbSetExtensions {
public static ObservableCollection<Author> LoadAsObservableCollection(this DbSet<Author> dbSet) {
return new ObservableCollection<Author>(dbSet
.AsNoTracking()
.OrderBy(a => a != null ? a.LastName : null));
}
public static ObservableCollection<StoragePlace> LoadAsObservableCollection(this DbSet<StoragePlace> dbSet) {
return new ObservableCollection<StoragePlace>(dbSet
.AsNoTracking()
.OrderBy(a => a != null ? a.StoragePlaceName : null));
}
public static ObservableCollection<PublishingHouse> LoadAsObservableCollection(
this DbSet<PublishingHouse> dbSet) {
return new ObservableCollection<PublishingHouse>(dbSet
.AsNoTracking()
.OrderBy(a => a != null ? a.PublisherName : null));
}
public static ObservableCollection<Series> LoadAsObservableCollection(this DbSet<Series> dbSet) {
return new ObservableCollection<Series>(dbSet
.AsNoTracking()
.OrderBy(a => a != null ? a.SeriesName : null));
}
public static ObservableCollection<Category> LoadAsObservableCollection(
this DbSet<Category> dbSet) {
return new ObservableCollection<Category>(dbSet.ToList());
}
}
} |
using CityTemperature.Borders.Adapter;
using CityTemperature.Borders.Interfaces;
using CityTemperature.Borders.UseCase;
using CityTemperature.DTO;
using CityTemperature.DTO.AddCitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CityTemperature.UseCase
{
public class AddCitysUseCase : IAddCitysUseCase
{
private readonly ITemperatureRepositories _repositoriesCity;
private readonly IAddCitysAdapter _addCityAdapter;
public AddCitysUseCase(ITemperatureRepositories temperatureRepositories, IAddCitysAdapter addCitysAdapter )
{
_repositoriesCity = temperatureRepositories;
_addCityAdapter = addCitysAdapter;
}
public AddCitysResponse Execute(AddCitysRequest request)
{
var response = new AddCitysResponse();
try
{
if ( request.City.Length < 3)
{
response.msg = "Erro ao adicionar a cidade";
return response;
}
var addCity = _addCityAdapter.converterRequestCitys(request);
_repositoriesCity.Add(addCity);
response.msg = "Cidade Adicionada com sucesso";
response.id = addCity.Id;
return response;
}
catch (Exception)
{
response.msg = "Erro ao adicionar a cidade";
return response;
}
}
}
}
|
using UnityEngine;
using System.Collections;
using TMPro;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class UpgradeGuiHandler : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
Upgrade upgrade { get; set; }
Player player { get; set; }
UpgradeManager um { get; set; }
TextMeshProUGUI[] texts;
GameObject description;
Button btn;
private const int MAX_LEVEL = 10;
public void Initialize(Upgrade upg, Player player, UpgradeManager upgradeManager)
{
upgrade = upg;
this.player = player;
um = upgradeManager;
texts = GetComponentsInChildren<TextMeshProUGUI>();
description = transform.Find("DescriptionBackground").gameObject;
btn = GetComponentInChildren<Button>();
var icon = transform.Find("Icon").GetComponent<Image>();
icon.color = TypeToColor(upg.Type);
SetTexts();
}
void SetTexts()
{
texts[0].text = upgrade.Title;
texts[1].text = upgrade.Description;
texts[2].text = upgrade.Cost + " HP";
description.SetActive(false);
RefreshAvailability();
btn.onClick.AddListener(() => {
Upgrade(player, upgrade, texts[3]);
});
}
private void Upgrade(Player player, Upgrade upgrade, TextMeshProUGUI currentLevelText)
{
upgrade.Purchase(player);
upgrade.CurrentLevel++;
currentLevelText.text = upgrade.CurrentLevel == MAX_LEVEL ? "MAX" : upgrade.CurrentLevel.ToString();
player.ReduceHp(upgrade.Cost);
// UI
um.RefreshAvailability();
HandleUiStats.Instance.handleStatChange();
HandleUiStats.Instance.handleHpChange();
}
public void RefreshAvailability()
{
btn.interactable = player.Health > upgrade.Cost && upgrade.CurrentLevel < MAX_LEVEL;
}
public void OnPointerEnter(PointerEventData eventData)
{
description.SetActive(true);
}
public void OnPointerExit(PointerEventData eventData)
{
description.SetActive(false);
}
Color c_Offensive = new Color(255, 0, 0);
Color c_Defensive = new Color(0, 0, 255);
Color c_Misc = new Color(100, 100, 50);
private Color TypeToColor(UpgradeType upg)
{
switch (upg)
{
case UpgradeType.Offensive:
return c_Offensive;
case UpgradeType.Defensive:
return c_Defensive;
case UpgradeType.Misc:
return c_Misc;
default:
return Color.black;
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Nitro_Smart_Viewer
{
public static class ResourceHelper
{
public static string[] GetResourse(ResourceType resourceType)
{
string value;
switch (resourceType)
{
case ResourceType.Txt:
{
value = ".txt";
break;
}
case ResourceType.Image:
{
value = ".png";
break;
}
default:
{
throw new ArgumentOutOfRangeException(nameof(resourceType), resourceType, null);
}
}
var assembly = typeof(ResourceHelper).GetTypeInfo().Assembly;
var resources = assembly.GetManifestResourceNames().Where(name => name.Contains(value));
return resources.ToArray();
}
public static Stream GetResourceStream(string resourceName)
{
var assembly = typeof(ResourceHelper).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream(resourceName);
return stream;
}
}
} |
using NuGet.Packaging.Core;
using NuGet.Protocol.Core.Types;
using NuGet.Protocol.VisualStudio;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Client.V3Test
{
public class UIMetadataResourceTests : TestBase
{
[Fact]
public async Task UIMetadataResource_Basic()
{
var resource = await SourceRepository.GetResourceAsync<UIMetadataResource>();
var result = await resource.GetMetadata("newtonsoft.json", false, false, CancellationToken.None);
var package = result.FirstOrDefault(p => p.Identity.Version == new NuGetVersion(6, 0, 4));
Assert.False(package.RequireLicenseAcceptance);
Assert.True(package.Description.Length > 0);
}
[Fact]
public async Task UIMetadataResource_NotFound()
{
var resource = await SourceRepository.GetResourceAsync<UIMetadataResource>();
var result = await resource.GetMetadata("alsfkjadlsfkjasdflkasdfkllllllllk", false, false, CancellationToken.None);
Assert.False(result.Any());
}
}
}
|
using System;
class NumbersInIntervalDividableByGivenNumber
{
static void Main()
{
//Write a program that reads two positive integer numbers and prints how many
//numbers p exist between them such that the reminder of the division by 5 is 0.
Console.Write("Start = ");
int start = int.Parse(Console.ReadLine());
Console.Write("End = ");
int end = int.Parse(Console.ReadLine());
int p = 0;
for (int i = start; i <= end; i++)
{
if (i % 5 == 0)
{
p++;
}
}
Console.WriteLine("P = {0}", p);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HackerrankSolutionConsole
{
class making_anagrams : Challenge
{
public override void Main(string[] args)
{
string str1 = Console.ReadLine();
string str2 = Console.ReadLine();
int[] sb1 = new int[26];
int[] sb2 = new int[26];
foreach (char c in str1)
sb1[c - 97]++;
foreach (char c in str2)
sb2[c - 97]++;
int count = 0;
for (int k = 0; k < 26; k++)
{
count += Math.Abs(sb1[k] - sb2[k]);
}
Console.WriteLine(count);
}
public making_anagrams()
{
Name = "Making Anagrams";
Path = "making-anagrams";
Difficulty = Difficulty.Easy;
Domain = Domain.Algorithms;
Subdomain = Subdomain.Strings;
}
}
}
|
using ProtoBuf;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeService
{
public class RedisManager
{
#region init
private IDatabase db;
private ISubscriber sub;
private RedisConnectionStringElement config;
private IServer server;
private void Init(string configName)
{
//@"Host"
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(GetConnectionString(configName));
db = redis.GetDatabase(config.DB);
sub = redis.GetSubscriber();
server = redis.GetServer(config.ConnectionString, config.Port);
}
/// <summary>
/// 获取连接字符串
/// </summary>
/// <param name="configName"></param>
/// <returns></returns>
private string GetConnectionString(string configName)
{
var a = ((YuanXinRedisConfigSettings)ConfigurationManager.GetSection("yuanxinRedisSettings")).ConnectionOptions[configName];
config = YuanXinRedisConfigSettings.GetConfig().ConnectionOptions[configName];
StringBuilder conectionString = new StringBuilder();
conectionString.AppendFormat(@"{0}:{1}", config.ConnectionString, config.Port);
if (!string.IsNullOrEmpty(config.PassWord))
{
conectionString.AppendFormat(@",password={0},ConnectTimeout=10000,abortConnect=false", config.PassWord);
}
return conectionString.ToString();
}
/// <summary>
/// 将配置文件中的连接字符串传入
/// </summary>
/// <param name="configName"></param>
public RedisManager(string configName)
{
Init(configName);
}
#endregion
/// <summary>
/// 序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public RedisValue Serialize<T>(T data)
{
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, data);
return ms.ToArray();
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public T DeSerialize<T>(RedisValue value)
{
using (MemoryStream ms = new MemoryStream(value))
{
return Serializer.Deserialize<T>(ms);
}
}
/// <summary>
/// Save String Data
/// </summary>
/// <param name="keys"></param>
/// <param name="values"></param>
/// <param name="expiredTime"></param>
/// <returns></returns>
public Task<bool> SaveAsync<T>(string key, T value, TimeSpan expiredTime)
{
RedisValue rValue = this.Serialize(value);
var tran = db.CreateTransaction(true);
tran.StringSetAsync(key, rValue, expiredTime);
return tran.ExecuteAsync();
}
/// <summary>
/// Get String Data
/// </summary>
/// <param name="keys"></param>
/// <param name="values"></param>
/// <param name="expiredTime"></param>
/// <returns></returns>
public Task<T> GetAsync<T>(string key)
{
var redisValue = db.StringGetAsync(key);
if (!redisValue.Result.IsNullOrEmpty)
return Task.FromResult(this.DeSerialize<T>(redisValue.Result));
else
return null;
}
/// <summary>
/// Save String Data
/// </summary>
/// <param name="keys"></param>
/// <param name="values"></param>
/// <param name="expiredTime"></param>
/// <returns></returns>
public Task<bool> StringSetAsync(RedisKey[] keys, RedisValue[] values, TimeSpan[] expiredTime)
{
var tran = db.CreateTransaction(true);
for (var i = 0; i < keys.Length; i++)
{
var key = keys[i];
var val = values[i];
var expTime = expiredTime[i];
if (expTime == TimeSpan.Zero)
{
tran.StringSetAsync(key, val);
}
else
{
tran.StringSetAsync(key, val, expTime);
}
}
return tran.ExecuteAsync();
}
/// <summary>
///Get String Data
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Task<RedisValue> StringGetAsync(RedisKey key)
{
return db.StringGetAsync(key);
}
/// <summary>
/// 检测key是否过期
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Task<bool> KeyExistsAsync(RedisKey key)
{
return db.KeyExistsAsync(key);
}
/// <summary>
/// 设置key过期时间
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Task<bool> KeyTimeToLiveAsync(RedisKey key)
{
TimeSpan? keyTime = db.KeyTimeToLiveAsync(key).Result;
return keyTime.HasValue ? Task.FromResult(keyTime.Value.Seconds > 0) : Task.FromResult(false);
}
/// <summary>
/// 删除指定key
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public Task<bool> DeleteKeyAsync(RedisKey[] keys)
{
var tran = db.CreateTransaction(true);
foreach (var key in keys)
{
tran.KeyDeleteAsync(key);
}
return tran.ExecuteAsync();
}
/// <summary>
/// 添加项到list
/// </summary>
/// <param name="keys"></param>
/// <param name="values"></param>
public Task<bool> AddItemToListAsync(RedisKey[] keys, RedisValue[] values)
{
var tran = db.CreateTransaction(true);
for (int i = 0; i < keys.Length; i++)
{
var key = keys[i];
var val = values[i];
tran.ListRightPushAsync(key, val);
}
return tran.ExecuteAsync();
}
/// <summary>
/// 设置key过期时间
/// </summary>
/// <param name="key"></param>
/// <param name="expiredTime"></param>
/// <returns></returns>
public Task<bool> KeyExpireAsync(RedisKey key, TimeSpan expiredTime)
{
return db.KeyExpireAsync(key, expiredTime);
}
/// <summary>
/// 取list里的项,(项还是存在只是取值)
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Task<RedisValue[]> GetAllItemsFromListAsync(RedisKey key)
{
return db.ListRangeAsync(key);
}
/// <summary>
/// 取list里的项
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Task<RedisValue> ListLeftPopAsync(RedisKey key)
{
return db.ListLeftPopAsync(key);
}
/// <summary>
/// 查看list长度
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Task<long> ListLengthAsync(RedisKey key)
{
return db.ListLengthAsync(key);
}
/// <summary>
/// Save HashSet Data
/// </summary>
/// <param name="key"></param>
/// <param name="fields"></param>
/// <param name="values"></param>
/// <returns></returns>
public Task<bool> HashSetAsync(RedisKey key, RedisValue[] fields, RedisValue[] values)
{
var tran = db.CreateTransaction(true);
for (var i = 0; i < fields.Length; i++)
{
tran.HashSetAsync(key, fields[i], values[i]);
}
return tran.ExecuteAsync();
}
/// <summary>
/// Save HashSet Data
/// </summary>
/// <param name="key"></param>
/// <param name="fields"></param>
/// <param name="values"></param>
/// <returns></returns>
public Task<bool> HashSetAsync(RedisKey key, RedisValue fields, RedisValue values)
{
var tran = db.CreateTransaction(true);
tran.HashSetAsync(key, fields, values);
return tran.ExecuteAsync();
}
/// <summary>
/// 向指定键的字段,增加指定值
/// </summary>
/// <param name="key"></param>
/// <param name="fields"></param>
/// <param name="values"></param>
/// <returns></returns>
public Task<bool> HashIncrementAsync(RedisKey key, RedisValue fields, double values)
{
var tran = db.CreateTransaction(true);
tran.HashIncrementAsync(key, fields, values);
return tran.ExecuteAsync();
}
/// <summary>
/// HashGetAsync
/// </summary>
/// <param name="key"></param>
/// <param name="fields"></param>
/// <returns></returns>
public Task<RedisValue> HashGetAsync(RedisKey key, RedisValue fields)
{
return db.HashGetAsync(key, fields);
}
/// <summary>
/// HashGetAsync
/// </summary>
/// <param name="key"></param>
/// <param name="fields"></param>
/// <returns></returns>
public Task<RedisValue[]> HashGetAsync(RedisKey key, RedisValue[] fields)
{
return db.HashGetAsync(key, fields);
}
/// <summary>
/// HashGetAllAsync
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Task<HashEntry[]> HashGetAllAsync(RedisKey key)
{
return db.HashGetAllAsync(key);
}
/// <summary>
/// GetAllKeys
/// </summary>
/// <returns></returns>
public List<RedisKey> GetAllKeys()
{
return server.Keys(config.DB).ToList();
}
/// <summary>
/// redis发布消息到指定频道
/// </summary>
/// <param name="channel"></param>
/// <param name="messgae"></param>
/// <returns></returns>
public Task<bool> PublishAsync(RedisChannel channel, RedisValue[] messgae)
{
var tran = db.CreateTransaction(true);
foreach (var item in messgae)
{
tran.PublishAsync(channel, item);
}
return tran.ExecuteAsync();
}
/// <summary>
/// 无序排列存储
/// </summary>
/// <param name="key">RedisKey</param>
/// <param name="values">RedisValue</param>
/// <returns></returns>
public bool SetAdd(RedisKey key, RedisValue values)
{
return db.SetAdd(key, values);
}
/// <summary>
/// 无序列表获取数据方法法
/// </summary>
/// <param name="setOperation">并集,交集,差集</param>
/// <param name="first">firstKey</param>
/// <param name="second">secondKey</param>
/// <returns></returns>
public RedisValue[] SetCombine(SetOperation setOperation, RedisKey first, RedisKey second)
{
return db.SetCombine(setOperation, first, second);
}
/// <summary>
/// 删除指定value
/// </summary>
/// <returns></returns>
public bool SetRemove(RedisKey key, RedisValue value)
{
return db.SetRemove(key, value);
}
}
public class YuanXinRedisConfigSettings : ConfigurationSection
{
public static YuanXinRedisConfigSettings GetConfig()
{
YuanXinRedisConfigSettings result = (YuanXinRedisConfigSettings)ConfigurationManager.GetSection("yuanxinRedisSettings");
if (result == null)
result = new YuanXinRedisConfigSettings();
return result;
}
[ConfigurationProperty("connectionOptions")]
public RedisConnectionStringElementCollection ConnectionOptions
{
get
{
return (RedisConnectionStringElementCollection)base["connectionOptions"];
}
}
}
public class RedisConnectionStringElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new RedisConnectionStringElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((RedisConnectionStringElement)element).Name;
}
public RedisConnectionStringElement this[string name]
{
get
{
return BaseGet(name) as RedisConnectionStringElement;
}
}
}
public class RedisConnectionStringElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = false)]
public string Name
{
get
{
return (string)this["name"];
}
}
[ConfigurationProperty("connectionString", IsRequired = false)]
public string ConnectionString
{
get
{
return (string)this["connectionString"];
}
}
[ConfigurationProperty("port", IsRequired = false)]
public int Port
{
get
{
return (int)this["port"];
}
}
[ConfigurationProperty("passWord", IsRequired = false)]
public string PassWord
{
get
{
return (string)this["passWord"];
}
}
[ConfigurationProperty("db", IsRequired = false)]
public int DB
{
get
{
return (int)this["db"];
}
}
}
}
|
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
namespace MultiCommentCollector.Converter
{
internal class BackgroundColorConverter : IValueConverter
{
public static readonly BackgroundColorConverter Instance = new();
private static readonly int Delta = 105;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is SolidColorBrush brush)
{
var isDark = IsDark(brush.Color);
var newColor = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
if (isDark)
{
newColor.Color = Color.FromArgb(255, Range(brush.Color.R - Delta), Range(brush.Color.G - Delta), Range(brush.Color.B - Delta));
}
else
{
newColor.Color = Color.FromArgb(255, Range(brush.Color.R + Delta), Range(brush.Color.G + Delta), Range(brush.Color.B + Delta));
}
newColor.Freeze();
return newColor;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
/// <summary>
/// Determining Ideal Text Color Based on Specified Background Color
/// http://www.codeproject.com/KB/GDI-plus/IdealTextColor.aspx
/// </summary>
/// <param name = "background">The background color.</param>
/// <returns></returns>
private static bool IsDark(Color background)
{
const int nThreshold = 86; //105;
var bgDelta = System.Convert.ToInt32((background.R * 0.299) + (background.G * 0.587) + (background.B * 0.114));
return (255 - bgDelta < nThreshold) ? true : false;
}
private static byte Range(int value)
{
if (value < 0)
{
return 0;
}
if (value > 255)
{
return 255;
}
return (byte)value;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.IO;
using System.Text;
using sfShareLib;
using System.Threading.Tasks;
using sfAPIService.Models;
using System.Web.Script.Serialization;
using sfAPIService.Filter;
using Newtonsoft.Json;
using Swashbuckle.Swagger.Annotations;
using CDSShareLib.Helper;
namespace sfAPIService.Controllers
{
[Authorize]
[CustomAuthorizationFilter(ClaimType = "Roles", ClaimValue = "admin")]
[RoutePrefix("admin-api/Factory")]
public class FactoryController : ApiController
{
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpGet]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<FactoryModel.Format_Detail>))]
public IHttpActionResult GetAllFactoryByCompanyId()
{
FactoryModel factoryModel = new FactoryModel();
try
{
int companyId = Global.GetCompanyIdFromToken();
List<FactoryModel.Format_Detail> factoryList = factoryModel.GetAllByCompanyId(companyId);
return Content(HttpStatusCode.OK, factoryList);
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
return Content(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpGet]
[Route("{id}")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(FactoryModel.Format_Detail))]
public IHttpActionResult GetFactoryById(int id)
{
FactoryModel factoryModel = new FactoryModel();
try
{
FactoryModel.Format_Detail factory = factoryModel.GetById(id);
return Content(HttpStatusCode.OK, factory);
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
return Content(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpPost]
public IHttpActionResult CreateFactoryFormData([FromBody] FactoryModel.Format_Create factory)
{
int companyId = Global.GetCompanyIdFromToken();
string logForm = "Form : " + JsonConvert.SerializeObject(factory);
string logAPI = "[Post] " + Request.RequestUri.ToString();
if (!ModelState.IsValid || factory == null)
{
Global._appLogger.Warn(logAPI + " || Input Parameter not expected || " + logForm);
return Content(HttpStatusCode.BadRequest, HttpResponseFormat.InvaildData());
}
FactoryModel factoryModel = new FactoryModel();
try
{
int id = factoryModel.Create(companyId, factory);
return Content(HttpStatusCode.OK, HttpResponseFormat.Success(id));
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
logMessage.AppendLine(logForm);
Global._appLogger.Error(logAPI + logMessage);
return Content(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpPatch]
[Route("{id}")]
public IHttpActionResult UpdateFactory(int id, [FromBody] FactoryModel.Format_Update factory)
{
string logForm = "Form : " + JsonConvert.SerializeObject(factory);
string logAPI = "[Patch] " + Request.RequestUri.ToString();
if (!ModelState.IsValid || factory == null)
{
Global._appLogger.Warn(logAPI + " || Input Parameter not expected || " + logForm);
return Content(HttpStatusCode.BadRequest, HttpResponseFormat.InvaildData());
}
FactoryModel factoryModel = new FactoryModel();
try
{
factoryModel.Update(id, factory);
return Content(HttpStatusCode.OK, HttpResponseFormat.Success());
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
logMessage.AppendLine(logForm);
Global._appLogger.Error(logAPI + logMessage);
return Content(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpPut]
[Route("{id}/Image")]
public async Task<IHttpActionResult> UploadFactoryPhotoFile(int id)
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
return Content(HttpStatusCode.UnsupportedMediaType, HttpResponseFormat.UnsupportedMediaType());
try
{
// Check factory is existing
FactoryModel factoryModel = new FactoryModel();
var existingFactory = factoryModel.GetByIdForInternal(id);
//FileHelper fileHelper = new FileHelper();
BlobStorageHelper storageHelper = new BlobStorageHelper(Global._systemStorageName, Global._systemStorageKey, Global._imageStorageContainer);
string root = Path.GetTempPath();
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data.
string fileAbsoluteUri = "";
await Request.Content.ReadAsMultipartAsync(provider);
char[] trimChar = { '\"' };
//FileData
foreach (MultipartFileData fileData in provider.FileData)
{
string formColumnName = fileData.Headers.ContentDisposition.Name.ToLower().Trim(trimChar);
string fileExtenionName = fileData.Headers.ContentDisposition.FileName.Split('.')[1].ToLower().Trim(trimChar);
if (formColumnName.Equals("image"))
{
//string formColumnName = fileData.Headers.ContentDisposition.Name;
//string fileExtenionName = fileData.Headers.ContentDisposition.FileName.Replace("\"", "").Split('.')[1];
string fileExtension = Path.GetExtension(fileData.Headers.ContentDisposition.FileName.Replace("\"", "").ToLower());
if (fileExtension.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase)
|| fileExtension.Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase)
|| fileExtension.Equals(".png", StringComparison.InvariantCultureIgnoreCase))
{
ImageHelper imageHelper = new ImageHelper();
string uploadFilePath = String.Format("company-{0}/Factory/{1}", existingFactory.CompanyId, id);
fileAbsoluteUri = imageHelper.PublishImage(fileData.LocalFileName, storageHelper, uploadFilePath, Global._factoryPhotoWidthHeight, Global._imageBgColor, Global._imageFormat);
//string uploadFilePath = String.Format("company-{0}/Factory/{1}-default-{2}{3}", existingFactory.CompanyId, id, (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds, fileExtension);
//fileAbsoluteUri = storageHelper.SaveFiletoStorage(fileData.LocalFileName, uploadFilePath);
}
else
return Content(HttpStatusCode.BadRequest, HttpResponseFormat.Error("Unsupport File Type."));
}
}
if (fileAbsoluteUri.Equals(""))
return Content(HttpStatusCode.BadRequest, HttpResponseFormat.Error("File is empty"));
//Edit factory logo path
factoryModel.UpdatePhotoURL(id, fileAbsoluteUri);
return Content(HttpStatusCode.OK, new
{
imageURL = fileAbsoluteUri
});
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
string logAPI = "[Put] " + Request.RequestUri.ToString();
StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
Global._appLogger.Error(logAPI + logMessage);
return Content(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpDelete]
[Route("{id}")]
public IHttpActionResult Delete(int id)
{
FactoryModel factoryModel = new FactoryModel();
try
{
factoryModel.Delete(id);
return Content(HttpStatusCode.OK, HttpResponseFormat.Success());
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
string logAPI = "[Delete] " + Request.RequestUri.ToString();
StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
Global._appLogger.Error(logAPI + logMessage);
return Content(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Roles : admin, superadmin
/// </summary>
[Route("{factoryId}/Message")]
public IHttpActionResult GetMessageByFactoryId(int factoryId, [FromUri]int top = 10, [FromUri]int hours = 168, [FromUri]string order = "desc")
{
try
{
FactoryModel factoryModel = new FactoryModel();
int companyId = factoryModel.GetByIdForInternal(factoryId).CompanyId;
CompanyModel companyModel = new CompanyModel();
CompanyModel.Format_Detail company = companyModel.GetById(companyId);
var companySubscription = companyModel.GetValidSubscriptionPlanByCompanyId(companyId);
if (companySubscription == null)
throw new Exception("can't find valid subscription plan.");
DocumentDBHelper docDBHelpler = new DocumentDBHelper(companyId, companySubscription.CosmosDBConnectionString);
return Ok(docDBHelpler.GetMessageByFactoryId(factoryId, top, hours, order));
}
catch (Exception ex)
{
StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
string logAPI = "[Get] " + Request.RequestUri.ToString();
Global._appLogger.Error(logAPI + logMessage);
return Content(HttpStatusCode.InternalServerError, ex);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
public class ReqSceneEnter
{
private uint _door_id;
public Packet Encode()
{
Packet packet = new Packet();
packet.WriteUint(this._door_id);
packet.Encode(Msg.P_REQ_SCENE_ENTER);
return packet;
}
public uint door_id
{
get { return this._door_id; }
set { this._door_id = value; }
}
}
|
using System.Collections.Generic;
using BitcoinLib.CoinParameters.Blocknet;
using BitcoinLib.Services.Coins.Base;
using BitcoinLib.Services.Coins.Blocknet;
using BitcoinLib.Services.Coins.Blocknet.Xrouter;
using Microsoft.AspNetCore.Mvc;
public interface IBlocknetService : ICoinService, IBlocknetConstants{
#region Blocknetdx
List<ServiceNodeResponse> serviceNodeList();
#endregion
#region XCloud
ServiceResponse xrService(string service);
ServiceConsensusResponse xrServiceConsensus(string service, List<string> parameters);
#endregion
#region XRouter
ConnectResponse xrConnect(string service, int node_count);
DecodeRawTransactionResponse xrDecodeRawTransaction(string blockchain, string tx_hex, int node_count);
GetBlockCountResponse xrGetBlockCount(string blockchain, int node_count);
GetBlockHashResponse xrGetBlockHash(string blockchain, string block_number, int node_count);
GetBlockResponse xrGetBlock(string blockchain, string block_hash, int node_count);
GetBlocksResponse xrGetBlocks(string blockchain, string block_hashes, int node_count);
GetConnectedNodesResponse xrConnectedNodes();
GetNetworkServicesResponse xrGetNetworkServices();
GetReplyResponse xrGetReply(string uuid);
GetStatusResponse xrGetStatus();
GetTransactionResponse xrGetTransaction(string blockchain, string txid, int node_count);
GetTransactionsResponse xrGetTransactions(string blockchain, string txids, int node_count);
SendTransactionResponse xrSendTransaction(string blockchain, string signed_tx);
List<ShowConfigsResponse> xrShowConfigs();
UpdateConfigsResponse xrUpdateConfigs(bool force_check = false);
#endregion
#region XBridge
#endregion
} |
using System;
using UnityEngine;
public class T4MPlantObjSC : MonoBehaviour
{
}
|
using UnityEngine;
using System.Collections;
using System.Linq;
using UnityEngine.Assertions;
using UnityEngine.EventSystems;
public static class UIUtilities
{
public static void ActivateCanvasGroup(CanvasGroup group)
{
if (group == null) return;
group.alpha = 1;
group.blocksRaycasts = true;
group.interactable = true;
}
public static void ActivateWithLock(CanvasGroup group, ref bool openFlag)
{
if (openFlag) return;
TimeManager.Pause();
TimeManager.Lock();
ActivateCanvasGroup(group);
openFlag = true;
}
public static void DeactivateCanvasGroup(CanvasGroup group)
{
if (group == null) return;
group.alpha = 0;
group.blocksRaycasts = false;
group.interactable = false;
}
public static void DeactivateWithLock(CanvasGroup group, ref bool openFlag)
{
if (!openFlag) return;
DeactivateCanvasGroup(group);
TimeManager.Unlock();
TimeManager.Unpause();
openFlag = false;
}
public static T[] GetSiblingsOfType<T>(GameObject obj) where T : UIBehaviour
{
Transform parent = obj.transform.parent;
Assert.IsNotNull(parent);
GameObject[] siblings = new GameObject[parent.childCount - 1];
int i1 = 0;
for (int i = 0; i < parent.childCount; i++)
{
if (parent.GetChild(i).gameObject == obj)
continue;
siblings[i1] = parent.GetChild(i).gameObject;
i1++;
}
return siblings.Where(x => x.GetComponent<T>() != null).Select(x => x.GetComponent<T>()).ToArray();
}
}
|
using _08_CRUD_Personas_DAL.Lists;
using _08_CRUD_Personas_Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _08_CRUD_Personas_BL.Lists
{
public class clsListadoDepartamentosBL
{
/// <summary>
/// Le pide a la capa DAL todos los departamentos
/// </summary>
/// <returns>Una lista con los departamentos</returns>
public List<clsDepartamento> crearListadoDepartamentosBL()
{
clsListadoDepartamentosDAL list = new clsListadoDepartamentosDAL();
List<clsDepartamento> listado = list.crearListadoDepartamentosDAL();
return listado;
}
/// <summary>
/// Le pide a la capa DAL un departamento
/// </summary>
/// <param name="id">Del departamento que queremos</param>
/// <returns>El departamento que tenga el mismo id que le mandamos</returns>
public clsDepartamento obtenerDepartamentoIdBL(int id)
{
clsListadoDepartamentosDAL dep = new clsListadoDepartamentosDAL();
clsDepartamento departamento = dep.obtenerDepartamentoIdDAL(id);
return departamento;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR;
public class RoomSetup : MonoBehaviour
{
public SteamVR_ActionSet actionSetRoomControl;
private void Start()
{
actionSetRoomControl.Activate();
}
private void OnDestroy()
{
actionSetRoomControl.Deactivate();
}
}
|
using loggerApp.AppSettings;
using Serilog;
using System;
using Topshelf;
namespace loggerApp
{
class Program
{
static void Main(string[] args)
{
TopshelfExitCode exitCode = TopshelfExitCode.Ok;
try
{
// https://github.com/serilog/serilog/wiki/AppSettings
Log.Logger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.CreateLogger();
Log.Information("*** Begin Application. ***");
exitCode = HostFactory.Run(x =>
{
var settings = new LoggerJsonSettings().Load();
Log.Information("Loaded settings at {0}", settings.DefaultPath);
x.Service<LoggerService>(s =>
{
s.ConstructUsing(name => new LoggerService(settings));
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.EnableServiceRecovery(r =>
{
r.OnCrashOnly();
r.RestartService(1); //first
r.RestartService(1); //second
r.RestartService(1); //subsequents
});
//Windowsサービスの設定
x.RunAs(settings.LoggerSettings.ServiceUserName, settings.LoggerSettings.ServicePassword);
x.SetDescription(loggerConstants.ServiceDescription);
x.SetDisplayName(loggerConstants.ServiceDsiplayName);
x.SetServiceName(loggerConstants.ServiceServiceName);
x.StartAutomaticallyDelayed();
});
}
catch (Exception ex)
{
Log.Error(ex, "Topshelf down?");
}
finally
{
Log.Information("*** Topshelf exit code is {0} ***", exitCode);
Log.CloseAndFlush();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.ServiceModel;
using Microsoft.Practices.Prism.Logging;
using Torshify.Origo.Contracts.V1.Query;
using Torshify.Radio.Framework;
using Torshify.Radio.Spotify.LoginService;
using Torshify.Radio.Spotify.QueryService;
namespace Torshify.Radio.Spotify
{
[TrackSourceMetadata(Name = "Spotify", IconUri = "pack://application:,,,/Torstify.Radio.Spotify;component/Resources/Spotify_Logo.png")]
public class SpotifyTrackSource : ITrackSource
{
#region Fields
private readonly ILoggerFacade _logger;
#endregion Fields
#region Constructors
[ImportingConstructor]
public SpotifyTrackSource(ILoggerFacade logger)
{
_logger = logger;
}
#endregion Constructors
#region Methods
public static SpotifyTrack ConvertTrack(Origo.Contracts.V1.Track track)
{
string albumArt = null;
if (!string.IsNullOrEmpty(track.Album.CoverID))
{
// TODO : Get location of torshify from config, instead of using localhost :o
albumArt = "http://localhost:1338/torshify/v1/image/id/" + track.Album.CoverID;
}
return new SpotifyTrack
{
Index = track.Index,
TrackId = track.ID,
Name = track.Name,
Artist = track.Album.Artist.Name,
Album = track.Album.Name,
AlbumArt = albumArt,
TotalDuration = TimeSpan.FromMilliseconds(track.Duration)
};
}
public IEnumerable<Track> GetTracksByName(string name)
{
Track[] tracks = new Track[0];
if (!IsLoggedIn())
{
return tracks;
}
QueryServiceClient query = new QueryServiceClient();
try
{
QueryResult result = query.Query(name, 0, 150, 0, 0, 0, 0);
tracks = result.Tracks
.Where(t => t.IsAvailable)
.Select(ConvertTrack)
.ToArray();
query.Close();
}
catch (Exception e)
{
_logger.Log(e.Message, Category.Exception, Priority.Medium);
query.Abort();
}
return tracks;
}
public IEnumerable<TrackContainer> GetAlbumsByArtist(string artist)
{
List<TrackContainer> containers = new List<TrackContainer>();
if (!IsLoggedIn())
{
return containers;
}
QueryServiceClient query = new QueryServiceClient();
try
{
var queryResult = query.Query(artist, 0, 0, 0, 0, 0, 10);
var result =
queryResult.Artists.FirstOrDefault(
a => a.Name.Equals(artist, StringComparison.InvariantCultureIgnoreCase));
if (result == null && queryResult.Artists.Any())
{
result = queryResult.Artists.FirstOrDefault();
}
if (result != null)
{
var browse = query.ArtistBrowse(result.ID, ArtistBrowsingType.Full);
var albumGroups = browse.Tracks.Where(t => t.IsAvailable).GroupBy(t => t.Album.ID);
foreach (var albumGroup in albumGroups)
{
TrackContainer container = new TrackContainer();
container.Owner = new TrackContainerOwner(artist);
container.Tracks = albumGroup.Select(SpotifyRadioTrackPlayer.ConvertTrack).ToArray();
var firstOrDefault = container.Tracks.FirstOrDefault();
if (firstOrDefault != null)
{
container.Name = firstOrDefault.Album;
container.Image = container.Image = firstOrDefault.AlbumArt;
}
containers.Add(container);
}
}
query.Close();
}
catch (Exception e)
{
_logger.Log(e.Message, Category.Exception, Priority.Medium);
query.Abort();
}
return containers;
}
public bool SupportsLink(TrackLink trackLink)
{
return trackLink.TrackSource == "spotify";
}
public Track FromLink(TrackLink trackLink)
{
string trackId = trackLink["TrackId"];
// TODO : Implement properly
return new SpotifyTrack {TrackId = trackId};
}
private bool IsLoggedIn()
{
LoginServiceClient client = new LoginServiceClient(new InstanceContext(new NoOpCallbacks()));
try
{
bool result = client.IsLoggedIn();
client.Close();
return result;
}
catch
{
client.Abort();
return false;
}
}
#endregion Methods
#region Nested Types
private class NoOpCallbacks : LoginServiceCallback
{
#region Methods
public void OnLoggedIn()
{
}
public void OnLoginError(string message)
{
}
public void OnLoggedOut()
{
}
public void OnPing()
{
}
#endregion Methods
}
#endregion Nested Types
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class CharacterHealth : MonoBehaviour
{
public float CurrentHealth { get; set; }
public float MaxHealth { get; set; }
public GameObject enemy;
public GameObject player;
public float Damage;
public Slider healthbar;
void Start()
{
MaxHealth = 100f;
// Resets health to full on game load
CurrentHealth = MaxHealth;
healthbar.value = CalculateHealth();
}
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.gameObject.tag == "Enemy")
{
DealDamage(6);
}
}
private void OnCollisionStay(Collision collision)
{
if (collision.collider.gameObject.tag == "Enemy")
{
DealDamage(Damage);
}
}
void Update()
{
}
void DealDamage(float damageValue)
{
// Deduct the damage dealt from the character's health
CurrentHealth -= damageValue;
healthbar.value = CalculateHealth();
// If the character is out of health, die!
if (CurrentHealth <= 0)
Die();
}
float CalculateHealth()
{
return CurrentHealth / MaxHealth;
}
void Die()
{
CurrentHealth = 0;
Debug.Log("Parmigiana ehm... Sei morto!");
}
}
|
using System.Threading;
using System.Threading.Tasks;
using DotNetCore.CAP;
using MediatR;
using Project.API.Applications.IntegrationEvents;
using Project.Domain.Events;
namespace Project.API.Applications.DomainEventHandlers
{
public class ProejctViewedEventHandler : INotificationHandler<ProejctViewedEvent>
{
private readonly ICapPublisher _capPublisher;
public ProejctViewedEventHandler(ICapPublisher capPublisher)
{
_capPublisher = capPublisher;
}
public async Task Handle(ProejctViewedEvent notification, CancellationToken cancellationToken)
{
var @event=new ProejctViewedIntergrationEvent()
{
ProjectId = notification.ProjectViewer.ProjectId,
UserId = notification.ProjectViewer.UserId,
UserName = notification.ProjectViewer.UserName
};
await _capPublisher.PublishAsync("projectapi.projectviewed",@event);
}
}
} |
#region Usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Zengo.WP8.FAS.Models;
using Zengo.WP8.FAS.Helpers;
using Zengo.WP8.FAS.Resources;
#endregion
/*
Jason has confirmed that the selectable column works like this:
value = 0, only show the country in the list where you filter players by country
value = 1, only show the country in the list that appears in user details or registration forms (my country), NOT in the list where the players are flitered
value = 2, show the country in all lists
eg.
filters: selectable != 1
favourite team: selectable > 0
*
*
*
It's an int and takes a values of 0,1,2:
0 - Country is selectable only in player search
1 - Country is selectable only in user account
2 - Country is selectable in both
So your player search country list is found with the condition:
(selectable==0||selectable==2)
And your account player list is found with the condition:
(selectable==1||selectable==2)
*/
namespace Zengo.WP8.FAS.Controls
{
public partial class MyCountrySelectorControl : UserControl
{
public class MyCountryBinding
{
public int CountryId { get; set; }
public string CountryName { get; set; }
public string CountryImage { get; set; }
}
#region Fields
public event EventHandler<EventArgs> CountryPressed;
private CountryRecord country;
#endregion
#region Properties
public string NoSelectionMadeText { get; set; }
public CountryRecord Country { get { return country; } private set { } }
#endregion
#region Constructors
public MyCountrySelectorControl()
{
InitializeComponent();
CountrySelector.Tap += CountrySelect_Tap;
LayoutRoot.ManipulationStarted += Animation.Standard_ManipulationStarted_1;
LayoutRoot.ManipulationCompleted += Animation.Standard_ManipulationCompleted_1;
}
#endregion
#region Event Handlers
void CountrySelect_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if (CountryPressed != null)
{
CountryPressed(this, new EventArgs());
}
}
#endregion
#region Helpers
public void Refresh(CountryRecord country)
{
this.country = country;
if ( country != null )
{
var toBind = new MyCountryBinding() { CountryId = country.CountryId, CountryName = country.Name, CountryImage = country.ImageToRender };
LayoutRoot.DataContext = toBind;
TextBlockDescription.Foreground = App.AppConstants.NormalTextColourBrush;
}
else
{
var toBind = new MyCountryBinding() { CountryId = 0, CountryName = NoSelectionMadeText, CountryImage = "../Images/CountryNotChosen.png" };
LayoutRoot.DataContext = toBind;
TextBlockDescription.Foreground = App.AppConstants.WatermarkTextColourBrush;
}
}
#endregion
internal string SelectedId()
{
if (country != null)
{
return country.CountryId.ToString();
}
return "0";
}
}
}
|
using System.Xml.Serialization;
namespace SimpleMvcSitemap
{
public enum VideoRestrictionRelationship
{
[XmlEnum("allow")]
Allow,
[XmlEnum("deny")]
Deny
}
} |
using Microsoft.EntityFrameworkCore;
using bGrind.API.Models;
namespace bGrind.API.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options){}
public DbSet<Event> Events { get; set; } // pluralize entities (table name)
public DbSet<User> Users {get; set; }
}
} |
using LuaInterface;
using SLua;
using System;
public class Lua_UILabel_Effect : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UILabel.Effect");
LuaObject.addMember(l, 0, "None");
LuaObject.addMember(l, 1, "Shadow");
LuaObject.addMember(l, 2, "Outline");
LuaObject.addMember(l, 3, "Outline8");
LuaDLL.lua_pop(l, 1);
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using KaVE.Commons.Model.Naming;
using KaVE.Commons.Model.SSTs.Impl.Blocks;
using KaVE.Commons.Model.SSTs.Impl.Expressions.Assignable;
using KaVE.Commons.Model.SSTs.Impl.Expressions.Simple;
using KaVE.Commons.Model.SSTs.Impl.Statements;
using NUnit.Framework;
using Fix = KaVE.RS.Commons.Tests_Integration.Analysis.SSTAnalysisTestSuite.SSTAnalysisFixture;
namespace KaVE.RS.Commons.Tests_Integration.Analysis.SSTAnalysisTestSuite
{
[Ignore]
internal class CurrentlyBrokenTests : BaseSSTAnalysisTest
{
[Test]
public void StaticMembersWhenCalledByAlias()
{
// This completion is only misanalysed when an alias is used. Completing "Object.$" yields correct results.
// This is also true for other aliases such as "string" or "int".
CompleteInMethod(@"
object.$
");
AssertBody(ExprStmt(Fix.CompletionOnType(Fix.Object, "")));
}
[Test]
public void MultipleConditionsInIfBlock()
{
CompleteInMethod(@"
if (true && true)
{
$
}");
AssertBody(
VarDecl("$0", Fix.Bool),
Assign("$0", new ComposedExpression()),
new IfElseBlock
{
Condition = RefExpr("$0"),
Then =
{
ExprStmt(new CompletionExpression())
}
});
}
[Test]
public void CallingMethodWithProperty()
{
CompleteInClass(@"
public string Name { get; set; }
public void M()
{
N(this.Name);
}
public void N(string s)
{
s.$
}");
var nMethod = Fix.Method(Fix.Void, Type("C"), "N", Fix.Parameter(Fix.String, "s"));
var namePropertyRef = PropertyRef(Fix.Property(Fix.String, Type("C"), "Name"), VarRef("this"));
AssertBody(
"M",
ExprStmt(Invoke("this", nMethod, RefExpr(namePropertyRef))));
}
[Test]
public void UnnecessaryReassignmentOfThis()
{
CompleteInClass(@"
public void M()
{
this.GetH$
}");
//C $0;
//$0 = this;
//$0.GetH$;
AssertBody(
"M",
ExprStmt(Fix.CompletionOnVar(VarRef("this"), "GetH")));
}
[Test]
public void AssigningArray()
{
CompleteInMethod(@"
var array = new[] {1, 2, 3, 4, 5};
array.$");
// Analysis will assign UnknownExpression. Should probably be ConstantValueExpression instead.
AssertBody(
VarDecl("array", Names.ArrayType(1, Fix.Int)),
Assign("array", new ConstantValueExpression()),
ExprStmt(Fix.CompletionOnVar(VarRef("array"), "")));
Assert.Fail();
}
[Test]
public void ExtensionMethod()
{
CompleteInMethod(@"
static class C2
{
public static void DoSth(this C1 a, int arg) { }
}
class C1
{
public void M()
{
var a = new C1();
a.DoSth(1);
$
}
}");
//{
// "$type": "[SST:Statements.ExpressionStatement]",
// "Expression": {
// "$type": "[SST:Expressions.Assignable.InvocationExpression]",
// "Reference": {
// "$type": "[SST:References.VariableReference]",
// "Identifier": ""
// },
// "MethodName": "CSharp.MethodName:static [System.Void, mscorlib, 4.0.0.0] [AnalysisTests.C2, AnalysisTests].DoSth([AnalysisTests.C1, AnalysisTests] a, [System.String, mscorlib, 4.0.0.0] arg)",
// "Parameters": [
// {
// "$type": "[SST:Expressions.Simple.ConstantValueExpression]"
// }
// ]
// }
//},
// Should add instance "a" as first parameter.
Assert.Fail();
}
[Test]
public void CompletingNewMember()
{
CompleteInClass(@"public str$");
// This will produce a broken method declaration with name "CSharp.MethodName:[?] [?].???()".
// It seems impossible to represent a trigger point like this in a meaningful way.
Assert.Fail();
}
[Test]
public void LostTriggerPoint()
{
CompleteInClass(@"
public C Method()
{
this.Method().$
Console.WriteLine(""asdf"");
return this;
}");
// Trigger point is lost in this case. The static method call is corrupted.
// This only happens if no prefix is used. Results are as expected when completing with a prefix.
//C1 $0;
//$0 = this.Method();
//.???("...");
//return this;
//{
// "$type": "[SST:Statements.ExpressionStatement]",
// "Expression": {
// "$type": "[SST:Expressions.Assignable.InvocationExpression]",
// "Reference": {
// "$type": "[SST:References.VariableReference]",
// "Identifier": ""
// },
// "MethodName": "CSharp.MethodName:[?] [?].???()",
// "Parameters": [
// {
// "$type": "[SST:Expressions.Simple.ConstantValueExpression]"
// }
// ]
// }
//},
Assert.Fail();
}
[Test]
public void FieldMistakenForVariable()
{
// Same thing happens with properties etc. Does not happen when using explicit this.
CompleteInClass(@"
public string Str;
public void M()
{
Str.$
}");
//{
// "$type": "[SST:Statements.ExpressionStatement]",
// "Expression": {
// "$type": "[SST:Expressions.Assignable.CompletionExpression]",
// "VariableReference": {
// "$type": "[SST:References.VariableReference]",
// "Identifier": "Str"
// },
// "Token": ""
// }
//}
AssertBody(
"M",
VarDecl("$0", Fix.String),
Assign("$0", RefExpr(FieldRef(Fix.Field(Fix.String, Type("C"), "Str"), VarRef("this")))),
ExprStmt(Fix.CompletionOnVar(VarRef("$0"), "")));
}
[Test]
public void TriggerInside_WithToken()
{
// Exception => ReferenceExpression:e
// Affected Node => ReferenceExpression:e
// Case => Undefined
CompleteInMethod(@"throw e$");
AssertBody(
VarDecl("$0", Fix.Exception),
Assign("$0", new CompletionExpression {Token = "e"}),
new ThrowStatement {Reference = VarRef("$0")});
}
[Test]
public void TriggerInside_WithNewObject()
{
// Exception => IObjectCreationExpression
// Affected Node => ReferenceName:Ex
// Case => Undefined
CompleteInMethod(@"throw new Ex$");
AssertBody(
VarDecl("$0", Fix.Exception),
Assign("$0", new CompletionExpression()),
// not sure how this completion would look
new ThrowStatement {Reference = VarRef("$0")});
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using ENTITY;
//<summary>
//Summary description for CounterInfo
//</summary>
namespace ENTITY
{
public class CounterInfo
{
private decimal _counterId;
private string _counterName;
private string _narration;
private DateTime _extraDate;
private string _extra1;
private string _extra2;
public decimal CounterId
{
get { return _counterId; }
set { _counterId = value; }
}
public string CounterName
{
get { return _counterName; }
set { _counterName = value; }
}
public string Narration
{
get { return _narration; }
set { _narration = value; }
}
public DateTime ExtraDate
{
get { return _extraDate; }
set { _extraDate = value; }
}
public string Extra1
{
get { return _extra1; }
set { _extra1 = value; }
}
public string Extra2
{
get { return _extra2; }
set { _extra2 = value; }
}
}
}
|
namespace Renting.Domain.Drafts
{
//TODO Czy na to też factory method/class?
public class DraftAccepted
{
public string AgreementNumber { get; }
public string OwnerId { get; }
public string TenantId { get; }
public decimal Price { get; }
public DraftAccepted(string agreementNumber, string ownerId, string tenantId, decimal price)
{
AgreementNumber = agreementNumber;
OwnerId = ownerId;
TenantId = tenantId;
Price = price;
}
}
} |
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
using System.Web;
namespace NopSolutions.NopCommerce.Web.Modules
{
public partial class HeaderMenuControl : BaseNopUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
string sPagePath = HttpContext.Current.Request.Url.AbsolutePath;
Action.Style.Add("background",
sPagePath.Contains("Actions.aspx")
? "url(../../images/ff_images/menu/action2.gif) center no-repeat"
: "url(../../images/ff_images/menu/action.gif) center no-repeat");
Clients.Style.Add("background",
sPagePath.Contains("ToCorporateClients.aspx")
? "url(../../images/ff_images/menu/client2.gif) center no-repeat"
: "url(../../images/ff_images/menu/client.gif) center no-repeat");
Green.Style.Add("background",
sPagePath.Contains("Greening.aspx")
? "url(../../images/ff_images/menu/landscaping2.gif) center no-repeat"
: "url(../../images/ff_images/menu/landscaping.gif) center no-repeat");
News.Style.Add("background",
sPagePath.Contains("News")
? "url(../../images/ff_images/menu/news2.gif) center no-repeat"
: "url(../../images/ff_images/menu/news.gif) center no-repeat");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MediaManager.DAL.DBEntities;
namespace MediaManager.API
{
public interface IParser
{
VideoForCreationDTO video { get; set; }
string DomainName { set; get; }
bool IsValid(string properties);
bool Update(string propertyname, string value);
bool IsMatch(string domain);
IParser Create();
}
}
|
using System;
using System.Linq;
namespace TimerEx
{
/// <summary>
/// 指定された条件に合致するシステム時間にイベントを着火するタイマーです。
/// </summary>
/// <remarks>
/// 以下を参考にしました。
/// https://stackoverflow.com/a/10896628
/// </remarks>
/// <example>
/// <code>
/// var t = new SystemClockTimer(SystemClockTimer.TickAtEvery.Minute, new []{30, 35, 40, 55});
/// t.Tick += SysClockTimer_Tick;
/// t.Start();
///
/// 毎分 30,35,40,55秒にTickイベントが発生します
///
/// t.Stop();
/// t.Close();
/// </code>
/// </example>
public class SystemClockTimer
{
/// <summary>
/// <see cref="SystemClockTimer.Tick"/> イベントのイベント引数です。
/// </summary>
public class TickEventArgs : EventArgs
{
/// <summary>
/// イベントが発生した時間
/// </summary>
public DateTime SignalTime { get; }
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="signalTime">イベントが発生した時間</param>
internal TickEventArgs(DateTime signalTime)
{
this.SignalTime = signalTime;
}
}
/// <summary>
/// どの時間単位で <see cref="SystemClockTimer.Tick"/> を発生させるかを表します。
/// </summary>
public enum TickAtEvery
{
/// <summary>
/// 毎時
/// </summary>
Hour,
/// <summary>
/// 毎分
/// </summary>
Minute
}
/// <summary>
/// タイマーが発動した場合に発生するイベントです。
/// </summary>
public event EventHandler<TickEventArgs> Tick;
/// <summary>
/// 内部で利用しているタイマーオブジェクト
/// </summary>
private readonly FixedStepTimer _timer;
/// <summary>
/// 直近で発生した <see cref="Tick"/> イベントの時間
/// </summary>
private volatile string _last;
/// <summary>
/// 最小値を表す
/// </summary>
/// <remarks>
/// 初回のイベント発生かどうかを判別するために利用されています。
/// </remarks>
private readonly string _minLast;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="every">時間単位</param>
/// <param name="values">時間単位内でイベントを発生させたい値のリスト</param>
/// <remarks>
/// たとえば、毎時10分でイベントを発生させたい場合は
/// <code>
/// var t = new SystemClockTimer(SystemClockTimer.TickAtEvery.Hour, new []{10});
/// </code>
/// と指定します。
///
/// 毎分 30,35,40,55秒でイベントを発生させたい場合は
/// <code>
/// var t = new SystemClockTimer(SystemClockTimer.TickAtEvery.Minute, new []{30,35,40,55});
/// </code>
/// と指定します。
/// </remarks>
public SystemClockTimer(TickAtEvery every, int[] values)
{
this.Every = every;
this.Values = values;
this._timer = new FixedStepTimer(TimeSpan.FromMilliseconds(1000));
this._timer.Tick += this.TimerOnTick;
this._minLast = DateTime.MinValue.ToString("HH:mm:ss");
}
/// <summary>
/// 時間単位
/// </summary>
public TickAtEvery Every { get; }
/// <summary>
/// 時間単位内でイベントを発生させたい時間の値
/// </summary>
public int[] Values { get; }
/// <summary>
/// 開始します。
/// </summary>
public void Start()
{
this._timer.Start();
}
/// <summary>
/// 停止します。
/// </summary>
public void Stop()
{
this._timer.Stop();
}
/// <summary>
/// 本タイマーを閉じて、内部リソースも開放します。
/// </summary>
public void Close()
{
this._timer.Close();
}
/// <summary>
/// <see cref="FixedStepTimer.Tick"/> イベントが発生した際に呼ばれます。
/// </summary>
/// <param name="sender">イベント送信元</param>
/// <param name="e">イベント引数</param>
private void TimerOnTick(object sender, FixedStepTimer.TickEventArgs e)
{
var sigTime = e.SignalTime;
var time =
new DateTime(1, 1, 1, sigTime.Hour, sigTime.Minute, sigTime.Second);
Func<DateTime, bool> fn = d => this.Values.Contains(d.Minute);
var timeStr = time.ToString("HH:mm:00");
if (this.Every == TickAtEvery.Minute)
{
fn = d => this.Values.Contains(d.Second);
timeStr = time.ToString("HH:mm:ss");
}
if (!fn(time))
{
return;
}
if (timeStr != this._minLast && timeStr == this._last)
{
return;
}
this._last = timeStr;
this.Tick.Invoke(this, new TickEventArgs(sigTime));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ElementalistController : PlayerController
{
// Public Stats Members
public int manaMaxCount = 3;
public float manaRefreshRate = 5f;
public Texture2D manaTexture;
// Private Stats Members
private int mana = 3;
private float nextManaRefresh = 0.0f;
// Public ElementalBall Members
public GameObject fireBallToRight, fireBallToLeft;
public GameObject iceBallToRight, iceBallToLeft;
// Private ElementalBall Members
private float fireBallWaitTime;
private float iceBallWaitTime;
private float xBallPosition = 0.7f;
// --------
// Starters
// --------
new void Start()
{
base.Start();
mana = manaMaxCount;
fireBallWaitTime = base.leftClickAnimTime - 0.33f;
iceBallWaitTime = base.rightClickAnimTime - 0.33f;
}
// -----------
// Controllers
// -----------
protected override void LeftClick()
{
Cast(fireBallToRight, fireBallToLeft, fireBallWaitTime);
}
protected override void RightClick()
{
Cast(iceBallToRight, iceBallToLeft, iceBallWaitTime);
}
void Cast(GameObject elementalToRight, GameObject elementalToLeft, float waitTime)
{
// If can cast
if (mana > 0)
{
mana--;
// If first time casting, put the refresh time from this point
if (nextManaRefresh == 0)
{
nextManaRefresh = Time.time + manaRefreshRate;
}
// Coroutine of casting to wait a little before creating the elemental ball (so the animation would get to the right frame)
if (base.isFacingRight)
{
StartCoroutine(OnCast(elementalToRight, xBallPosition, waitTime));
}
else
{
StartCoroutine(OnCast(elementalToLeft, (-1) * xBallPosition, waitTime));
}
}
}
// ------
// Events
// ------
IEnumerator OnCast(GameObject elemental, float x_position, float waitTime)
{
yield return new WaitForSeconds(waitTime);
Vector2 elementalPosition = transform.position;
elementalPosition += new Vector2(x_position, 0f);
Instantiate(elemental, elementalPosition, Quaternion.identity);
}
// ------
// Stats
// ------
protected override void Refresh()
{
// Refresh mana if needed and after set period of time
if ((Time.time > nextManaRefresh) && (mana < manaMaxCount))
{
nextManaRefresh = Time.time + manaRefreshRate;
mana++;
// If reached max mana, set refresh to zero so next cast will decide when to refresh
if (mana == manaMaxCount)
{
nextManaRefresh = 0;
}
}
}
// ---
// GUI
// ---
protected override void OnGUI()
{
if (!isInputEnabled)
{
return;
}
base.OnGUI();
// Mana
Rect manaIcon = new Rect(240, 93, 25, 25);
for (int i = 1; i <= mana; i++)
{
GUI.DrawTexture(manaIcon, manaTexture);
manaIcon.x -= (manaIcon.width + 10);
}
}
}
|
using UnityEngine;
public class RandomSpawnLocation {
private Transform center;
private float minRange;
private float maxRange;
public RandomSpawnLocation(Transform center, float minRange, float maxRange) {
this.center = center;
this.minRange = minRange;
this.maxRange = maxRange;
}
public Vector3 Next() {
var relativePosition = Random.insideUnitCircle * (maxRange - minRange);
relativePosition = relativePosition.normalized * (relativePosition.magnitude + minRange);
var newPoint = this.center.TransformPoint(
new Vector3(
relativePosition.x,
0,
relativePosition.y
)
);
Debug.Log(string.Format("Point: ({0},{1}) (min: {2}, max: {3}, orig: ({4}, {5}))", newPoint.x, newPoint.z, minRange, maxRange, relativePosition.x, relativePosition.y));
return newPoint;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Entities;
using ShareTradingWebsite.Models;
namespace ShareTradingWebsite.Controllers
{
public class AddressController : Controller
{
private readonly IAddressRepository addressRepository;
public AddressController(IAddressRepository addressRepository)
{
this.addressRepository = addressRepository;
}
//
// GET: /Address/
public ViewResult Index()
{
return View(addressRepository.All);
}
//
// GET: /Address/Details/5
public ViewResult Details(long id)
{
return View(addressRepository.Find(id));
}
//
// GET: /Address/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Address/Create
[HttpPost]
public ActionResult Create(Address address)
{
if (ModelState.IsValid) {
addressRepository.InsertOrUpdate(address);
addressRepository.Save();
return RedirectToAction("Index");
} else {
return View();
}
}
//
// GET: /Address/Edit/5
public ActionResult Edit(long id)
{
return View(addressRepository.Find(id));
}
//
// POST: /Address/Edit/5
[HttpPost]
public ActionResult Edit(Address address)
{
if (ModelState.IsValid) {
addressRepository.InsertOrUpdate(address);
addressRepository.Save();
return RedirectToAction("Index");
} else {
return View();
}
}
//
// GET: /Address/Delete/5
public ActionResult Delete(long id)
{
return View(addressRepository.Find(id));
}
//
// POST: /Address/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(long id)
{
addressRepository.Delete(id);
addressRepository.Save();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing) {
addressRepository.Dispose();
}
base.Dispose(disposing);
}
}
}
|
namespace Mathml.Operations
{
/// <summary>
/// An operation that uses two values, and info related to that operation.
/// </summary>
public abstract class Operation
{
/// <summary>
/// The username of person associated with the operation.
/// </summary>
public string Username;
/// <summary>
/// The name of the operation.
/// </summary>
public string OperationName;
/// <summary>
/// Any other info associated with the operation.
/// </summary>
public string MiscellaneousInfo;
/// <summary>
/// The first value used in the operation.
/// </summary>
public int Value1;
/// <summary>
/// The second value used in the operation.
/// </summary>
public int Value2;
/// <summary>
/// The mathematical symbol that represents the operation.
/// </summary>
public char OperationSymbol;
/// <summary>
/// Execute the operation using the two values to calculate a result.
/// </summary>
/// <returns>The result of operating on the two values</returns>
public abstract float Execute();
}
}
|
using System;
namespace IMDB.Api.Services.Interfaces
{
public interface ILanguageService : IEntityService<Entities.Language>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ProyectoMIPS
{
/* ======================================================
* Clase 1: Hilillo
* Estructura de datos para mantener la información de
* los hilillos
* ====================================================== */
public class hilillo
{
int numero_hilillo;
int inicio_hilillo; // Corresponde al inicio del hilillo
int fin_hilillo; // Corresponde al final del hilillo
bool finalizado; // Bandera que indica si ya finalizó
int[] registros; // R0 - R31 y RL
int PC;
int ciclos_reloj;
int numero_nucleo;
public hilillo(int numero_hil)
{
numero_hilillo = numero_hil;
inicio_hilillo = 0;
fin_hilillo = 0;
registros = new int[33];
finalizado = false;
PC = 0;
numero_nucleo = -1;
for(int i = 0; i < 33; i++)
registros[i] = 0;
ciclos_reloj = 0;
}
public void asignar_numero_hilillo(int numero)
{
this.numero_hilillo = numero;
}
public int obtener_numero_hil()
{
return numero_hilillo;
}
public void asignar_ciclos_reloj( int ciclos)
{
this.ciclos_reloj = ciclos;
}
public int obtener_ciclos_reloj()
{
return this.ciclos_reloj;
}
// Asigna el inicio del hilillo
public void asignar_inicio_hilillo(int inicia)
{
inicio_hilillo = inicia;
}
// Retorna el inicio del hilillo
public int obtener_inicio_hilillo()
{
return inicio_hilillo;
}
// Asigna el final del hilillo
public void asignar_fin_hilillo(int termina)
{
fin_hilillo = termina;
}
// Obtener el fin del hilillo
public int obtener_fin_hilillo()
{
return fin_hilillo;
}
// Se obtiene el contador del programa
public int obtener_PC()
{
return PC;
}
// Asigna el contador de programa del hilillo
public void asignar_PC(int contador_programa)
{
PC = contador_programa;
}
// Obtener el contexto
public int[] obtener_registros()
{
return registros;
}
// Asignar contexto de un hilillo
public void asignar_contexto(int contador_programa, int[] reg)
{
PC = contador_programa;
for (int i = 0; i < 33; i++)
registros[i] = reg[i];
}
// Asignar estado del hilillo
public void asignar_finalizado()
{
finalizado = true;
}
public void asignar_finalizado(bool f)
{
finalizado = f;
}
// Obtener estado del hilillo
public bool obtener_finalizado()
{
return finalizado;
}
public void asignar_numero_nucleo(int hilo)
{
numero_nucleo = hilo;
}
public int obtener_numero_nucleo()
{
return numero_nucleo;
}
}
/* ======================================================
* Clase 2: Estructura Nucleo
*
* Inicio y fin del hilillo actual
*
* Contador de programa: PC
*
* Registros de propósito general:
* registro[0]-registro[31]
*
* Registro RL:
* registro[32]
* ====================================================== */
public class nucleo
{
public int[] registro;
public int PC;
public int inicio_hilillo;
public int fin_hilillo;
public int num_hilillo;
public bool finalizado;
public bool cambiar;
public int ciclos_reloj;
public int numero_hilillo;
public int ciclos_reloj_acumulados;
public nucleo()
{
PC = 0;
registro = new int[33];
registro[0] = 0;
inicio_hilillo = 0;
fin_hilillo = 0;
num_hilillo = -1;
finalizado = false;
cambiar = false;
ciclos_reloj = 0;
numero_hilillo = 0;
ciclos_reloj_acumulados = 0;
}
public int obtener_ciclos_reloj_acumulados()
{
return this.ciclos_reloj_acumulados;
}
public void asignar_ciclos_reloj_acumulados(int ciclos)
{
ciclos_reloj_acumulados = ciclos;
}
public int obtener_ciclos_reloj()
{
return this.ciclos_reloj;
}
public void asignar_ciclos_reloj(int ciclos)
{
this.ciclos_reloj = ciclos;
}
public void asignar_inicio_hilillo(int inicio)
{
this.inicio_hilillo = inicio;
}
public int obtener_inicio_hilillo()
{
return this.inicio_hilillo;
}
public void asignar_fin_hilillo(int fin)
{
this.fin_hilillo = fin;
}
public int obtener_fin_hilillo()
{
return this.fin_hilillo;
}
public void asignar_registro(int reg, int pos)
{
registro[pos] = reg;
}
public int obtener_registro(int pos)
{
return registro[pos];
}
public int obtener_contador_programa()
{
return this.PC;
}
public void aumentar_contador_programa()
{
PC = PC + 4;
}
public void copiar_registros(hilillo hil)
{
PC = hil.obtener_PC();
for (int i = 1; i < 33; i++)
registro[i] = hil.obtener_registros()[i];
}
public void asignar_finalizado(bool f)
{
finalizado = f;
}
public bool obtener_finalizado()
{
return finalizado;
}
public void asignar_num_hilillo(int num)
{
num_hilillo = num;
}
public int obtener_num_hilillo()
{
return num_hilillo;
}
public void asignar_cambiar(bool c)
{
cambiar = c;
}
public bool obtener_cambiar()
{
return cambiar;
}
}
/* ======================================================
* Estructura de datos para almacenar una instrucción
*
* Código de instrucción:
* instruc[0]
*
* Primer operando:
* instruc[1]
*
* Segundo operando:
* instruc[2]
*
* Tercer operando:
* instruc[3]
* ====================================================== */
public class instruccion
{
int[] instruc;
public instruccion()
{
instruc = new int[4];
}
public void setParteInstruccion(int parte, int indice)
{
instruc[indice] = parte;
}
public int getParteInstruccion(int indice)
{
return instruc[indice];
}
public int[] getInstruccion()
{
return instruc;
}
}
/* ======================================================
* Estructura de datos para almacenar un bloque de datos
*
* 4 palabras del bloque:
* datos[0]-datos[3]
*
* Bit de validez del bloque:
* validez (inicialmente falso)
* ====================================================== */
public class bloqueDatos
{
public int[] datos;
public bool validez;
public bloqueDatos()
{
datos = new int[4];
validez = false;
}
public void setDato(int dato, int indice)
{
datos[indice] = dato;
validez = true;
}
public int getDato(int indice)
{
return datos[indice];
}
public void setBloque(int[] nuevosDatos)
{
for (int i = 0; i < 4; i++)
datos[i] = nuevosDatos[i];
}
public int[] getBloque()
{
return datos;
}
}
/* ======================================================
* Estructura de datos para almacenar un bloque de instru-
* cciones
*
* 4 instrucciones del bloque:
* instrucciones[0]-instrucciones[3]
*
* Bit de validez del bloque:
* validez (inicialmente falso)
* ====================================================== */
public class bloqueInstrucciones
{
public instruccion[] instrucciones;
public bool validez;
public bloqueInstrucciones()
{
instrucciones = new instruccion[4];
validez = false;
for (int i = 0; i < 4; i++)
instrucciones[i] = new instruccion();
}
public void setInstruccion(instruccion instruccion, int indice)
{
instrucciones[indice] = instruccion;
validez = true;
}
public instruccion getInstruccion(int indice)
{
return instrucciones[indice];
}
public void setBloque(instruccion[] nuevasInstrucciones)
{
for (int i = 0; i < 4; i++)
instrucciones[i] = nuevasInstrucciones[i];
}
public instruccion[] getBloque()
{
return instrucciones;
}
}
/* ======================================================
* Estructura de datos para almacenar una caché de datos
*
* 4 bloques de datos:
* bloqueDatos[0]-bloqueDatos[3]
*
* 4 números de bloque para cada bloque:
* numeroBloque[0]-numeroBloque[3] (inicialmente en
* -1)
* ====================================================== */
public class cacheDatos
{
public bloqueDatos[] bloqueDatos;
public int[] numeroBloque;
public cacheDatos()
{
bloqueDatos = new bloqueDatos[4];
numeroBloque = new int[4];
for (int i = 0; i < 4; i++)
{
bloqueDatos[i] = new bloqueDatos();
numeroBloque[i] = -1;
}
}
public void setBloque(int[] bloqueNuevo, int nuevoNumeroBloque)
{
bloqueDatos[nuevoNumeroBloque % 4].setBloque(bloqueNuevo);
bloqueDatos[nuevoNumeroBloque % 4].validez = true;
numeroBloque[nuevoNumeroBloque % 4] = nuevoNumeroBloque;
}
public bloqueDatos getBloque(int numBloque)
{
return bloqueDatos[numBloque % 4];
}
public bool esNumeroBloque(int numBloque)
{
if (numBloque == numeroBloque[numBloque % 4])
return true;
return false;
}
public bool esValido(int numBloque)
{
return bloqueDatos[numBloque % 4].validez;
}
public void invalidar(int numBloque)
{
bloqueDatos[numBloque % 4].validez = false;
}
public void modificarPalabraBloque(int dato, int palabra, int numBloque)
{
bloqueDatos[numBloque % 4].setDato(dato, palabra);
}
}
public class estructura_reloj
{
int valor;
bool modificado;
public estructura_reloj()
{
}
public int obtener_reloj()
{
return this.valor;
}
public Boolean obtener_modificado()
{
return this.modificado;
}
public void asignar_reloj(int num)
{
this.valor = num;
}
public void asignar_modificado(bool mod)
{
this.modificado = mod;
}
}
/* ======================================================
* Estructura de datos para almacenar una caché de instru-
* cciones
*
* 4 bloques de instrucciones:
* bloqueInstrucciones[0]-bloqueInstrucciones[3]
*
* 4 números de bloque para cada bloque:
* numeroBloque[0]-numeroBloque[3] (inicialmente en
* -1)
* ====================================================== */
public class cacheInstrucciones
{
public bloqueInstrucciones[] bloqueInstruccion;
public int[] numeroBloque;
public cacheInstrucciones()
{
bloqueInstruccion = new bloqueInstrucciones[4];
numeroBloque = new int[4];
for (int i = 0; i < 4; i++)
{
bloqueInstruccion[i] = new bloqueInstrucciones();
numeroBloque[i] = -1;
}
}
public int getNumeroBloque(int numBloque)
{
return numeroBloque[numBloque % 4];
}
public void setBloque(instruccion[] bloqueNuevo, int nuevoNumeroBloque)
{
bloqueInstruccion[nuevoNumeroBloque % 4].setBloque(bloqueNuevo);
bloqueInstruccion[nuevoNumeroBloque % 4].validez = true;
numeroBloque[nuevoNumeroBloque % 4] = nuevoNumeroBloque;
}
public bloqueInstrucciones getBloque(int numBloque)
{
return bloqueInstruccion[numBloque % 4];
}
public bool esNumeroBloque(int numBloque)
{
if (numBloque == numeroBloque[numBloque % 4])
return true;
return false;
}
public bool esValido(int numBloque)
{
return bloqueInstruccion[numBloque].validez;
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DotNetNuke.Common;
using DotNetNuke.Data;
using DotNetNuke.Framework.Providers;
namespace Dnn.PersonaBar.Servers.Components.Log
{
public class LogController
{
public List<string> GetLogFilesList()
{
var files = Directory.GetFiles(Globals.ApplicationMapPath + @"\portals\_default\logs", "*.resources");
var fileList = (from file in files select Path.GetFileName(file)).ToList();
return fileList;
}
public ArrayList GetUpgradeLogList()
{
var objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data");
var strProviderPath = DataProvider.Instance().GetProviderPath();
var arrScriptFiles = new ArrayList();
var arrFiles = Directory.GetFiles(strProviderPath, "*." + objProviderConfiguration.DefaultProvider);
foreach (var strFile in arrFiles)
{
arrScriptFiles.Add(Path.GetFileNameWithoutExtension(strFile));
}
arrScriptFiles.Sort();
return arrScriptFiles;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Voronov.Nsudotnet.BuildingCompanyIS.Entities;
using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces;
namespace Voronov.Nsudotnet.BuildingCompanyIS.Logic.Impl.DbImpl
{
public class SqlBuildPlansService : CrudServiceBase<BuildPlan>, IBuildPlansService
{
public SqlBuildPlansService(DatabaseModel context) : base(context)
{
}
public IQueryable<BuildPlan> GetBuildPlansByBuildingId(int buildingId)
{
return AllIncludeAll.Where(e=>e.BuildingId == buildingId);
}
public IQueryable<BuildPlan> GetBuildPlansByOrganizationUnitId(int organizationUnitId)
{
return AllIncludeAll.Where(e => e.Building.OrganizationUnitId == organizationUnitId);
}
public IQueryable<BuildPlan> GetBuildPlansBySiteId(int siteId)
{
return AllIncludeAll.Where(e => e.Building.SiteId == siteId);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UserStorageServices.Validation
{
public class AgeValidator : IValidator
{
public void Validate(User user)
{
if (user.Age <= 0)
{
throw new ArgumentException("Age less than zero.", nameof(user.Age));
}
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace online_knjizara.Migrations
{
public partial class Pocetna : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Drzava",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Naziv = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Drzava", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Odlomak",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Sadrzaj = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Odlomak", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Stanje",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
TipStanja = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Stanje", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Uloga",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
NazivUloge = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Uloga", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Zanr",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Naziv = table.Column<string>(nullable: true),
Opis = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Zanr", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Grad",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Naziv = table.Column<string>(nullable: true),
Drzava_ID = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Grad", x => x.ID);
table.ForeignKey(
name: "FK_Grad_Drzava_Drzava_ID",
column: x => x.Drzava_ID,
principalTable: "Drzava",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Autor",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Ime = table.Column<string>(nullable: true),
Prezime = table.Column<string>(nullable: true),
Adresa = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
Grad_ID = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Autor", x => x.ID);
table.ForeignKey(
name: "FK_Autor_Grad_Grad_ID",
column: x => x.Grad_ID,
principalTable: "Grad",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Izdavac",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Naziv = table.Column<string>(nullable: true),
Adresa = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
Telefon = table.Column<string>(nullable: true),
Grad_ID = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Izdavac", x => x.ID);
table.ForeignKey(
name: "FK_Izdavac_Grad_Grad_ID",
column: x => x.Grad_ID,
principalTable: "Grad",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Korisnik",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Ime = table.Column<string>(nullable: true),
Prezime = table.Column<string>(nullable: true),
Adresa = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
Telefon = table.Column<string>(nullable: true),
Username = table.Column<string>(nullable: true),
Password = table.Column<string>(nullable: true),
Grad_ID = table.Column<int>(nullable: false),
Uloga_ID = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Korisnik", x => x.ID);
table.ForeignKey(
name: "FK_Korisnik_Grad_Grad_ID",
column: x => x.Grad_ID,
principalTable: "Grad",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Korisnik_Uloga_Uloga_ID",
column: x => x.Uloga_ID,
principalTable: "Uloga",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Skladiste",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Naziv = table.Column<string>(nullable: true),
Adresa = table.Column<string>(nullable: true),
Kolicina = table.Column<int>(nullable: false),
Grad_ID = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Skladiste", x => x.ID);
table.ForeignKey(
name: "FK_Skladiste_Grad_Grad_ID",
column: x => x.Grad_ID,
principalTable: "Grad",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Knjiga",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Autor_ID = table.Column<int>(nullable: false),
Izdavac_ID = table.Column<int>(nullable: false),
Skladiste_ID = table.Column<int>(nullable: false),
Zanr_ID = table.Column<int>(nullable: false),
Stanje_ID = table.Column<int>(nullable: false),
Odlomak_ID = table.Column<int>(nullable: false),
Naziv = table.Column<string>(nullable: true),
Cijena = table.Column<float>(nullable: false),
DatumIzdavanja = table.Column<DateTime>(nullable: false),
Slika = table.Column<byte[]>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Knjiga", x => x.ID);
table.ForeignKey(
name: "FK_Knjiga_Autor_Autor_ID",
column: x => x.Autor_ID,
principalTable: "Autor",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Knjiga_Izdavac_Izdavac_ID",
column: x => x.Izdavac_ID,
principalTable: "Izdavac",
principalColumn: "ID",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_Knjiga_Odlomak_Odlomak_ID",
column: x => x.Odlomak_ID,
principalTable: "Odlomak",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Knjiga_Skladiste_Skladiste_ID",
column: x => x.Skladiste_ID,
principalTable: "Skladiste",
principalColumn: "ID",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_Knjiga_Stanje_Stanje_ID",
column: x => x.Stanje_ID,
principalTable: "Stanje",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Knjiga_Zanr_Zanr_ID",
column: x => x.Zanr_ID,
principalTable: "Zanr",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "KomentarOcjena",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Korisnik_ID = table.Column<int>(nullable: false),
Knjiga_ID = table.Column<int>(nullable: false),
Komentar = table.Column<string>(nullable: true),
Ocjena = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_KomentarOcjena", x => x.ID);
table.ForeignKey(
name: "FK_KomentarOcjena_Knjiga_Knjiga_ID",
column: x => x.Knjiga_ID,
principalTable: "Knjiga",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_KomentarOcjena_Korisnik_Korisnik_ID",
column: x => x.Korisnik_ID,
principalTable: "Korisnik",
principalColumn: "ID",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateTable(
name: "Narudzba",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Knjiga_ID = table.Column<int>(nullable: false),
Korisnik_ID = table.Column<int>(nullable: false),
Kolicina = table.Column<int>(nullable: false),
Cijena = table.Column<float>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Narudzba", x => x.ID);
table.ForeignKey(
name: "FK_Narudzba_Knjiga_Knjiga_ID",
column: x => x.Knjiga_ID,
principalTable: "Knjiga",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Narudzba_Korisnik_Korisnik_ID",
column: x => x.Korisnik_ID,
principalTable: "Korisnik",
principalColumn: "ID",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateIndex(
name: "IX_Autor_Grad_ID",
table: "Autor",
column: "Grad_ID");
migrationBuilder.CreateIndex(
name: "IX_Grad_Drzava_ID",
table: "Grad",
column: "Drzava_ID");
migrationBuilder.CreateIndex(
name: "IX_Izdavac_Grad_ID",
table: "Izdavac",
column: "Grad_ID");
migrationBuilder.CreateIndex(
name: "IX_Knjiga_Autor_ID",
table: "Knjiga",
column: "Autor_ID");
migrationBuilder.CreateIndex(
name: "IX_Knjiga_Izdavac_ID",
table: "Knjiga",
column: "Izdavac_ID");
migrationBuilder.CreateIndex(
name: "IX_Knjiga_Odlomak_ID",
table: "Knjiga",
column: "Odlomak_ID");
migrationBuilder.CreateIndex(
name: "IX_Knjiga_Skladiste_ID",
table: "Knjiga",
column: "Skladiste_ID");
migrationBuilder.CreateIndex(
name: "IX_Knjiga_Stanje_ID",
table: "Knjiga",
column: "Stanje_ID");
migrationBuilder.CreateIndex(
name: "IX_Knjiga_Zanr_ID",
table: "Knjiga",
column: "Zanr_ID");
migrationBuilder.CreateIndex(
name: "IX_KomentarOcjena_Knjiga_ID",
table: "KomentarOcjena",
column: "Knjiga_ID");
migrationBuilder.CreateIndex(
name: "IX_KomentarOcjena_Korisnik_ID",
table: "KomentarOcjena",
column: "Korisnik_ID");
migrationBuilder.CreateIndex(
name: "IX_Korisnik_Grad_ID",
table: "Korisnik",
column: "Grad_ID");
migrationBuilder.CreateIndex(
name: "IX_Korisnik_Uloga_ID",
table: "Korisnik",
column: "Uloga_ID");
migrationBuilder.CreateIndex(
name: "IX_Narudzba_Knjiga_ID",
table: "Narudzba",
column: "Knjiga_ID");
migrationBuilder.CreateIndex(
name: "IX_Narudzba_Korisnik_ID",
table: "Narudzba",
column: "Korisnik_ID");
migrationBuilder.CreateIndex(
name: "IX_Skladiste_Grad_ID",
table: "Skladiste",
column: "Grad_ID");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "KomentarOcjena");
migrationBuilder.DropTable(
name: "Narudzba");
migrationBuilder.DropTable(
name: "Knjiga");
migrationBuilder.DropTable(
name: "Korisnik");
migrationBuilder.DropTable(
name: "Autor");
migrationBuilder.DropTable(
name: "Izdavac");
migrationBuilder.DropTable(
name: "Odlomak");
migrationBuilder.DropTable(
name: "Skladiste");
migrationBuilder.DropTable(
name: "Stanje");
migrationBuilder.DropTable(
name: "Zanr");
migrationBuilder.DropTable(
name: "Uloga");
migrationBuilder.DropTable(
name: "Grad");
migrationBuilder.DropTable(
name: "Drzava");
}
}
}
|
using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityUIPlayables
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
internal class NormalizedAnimationCurveAttribute : MultiPropertyAttribute
{
private readonly bool _normalizeTime;
private readonly bool _normalizeValue;
public NormalizedAnimationCurveAttribute(bool normalizeValue = true, bool normalizeTime = true)
{
_normalizeValue = normalizeValue;
_normalizeTime = normalizeTime;
}
#if UNITY_EDITOR
public override void OnPostGUI(Rect position, SerializedProperty property, bool changed)
{
if (changed)
{
if (_normalizeValue)
{
property.animationCurveValue = NormalizeValue(property.animationCurveValue);
}
if (_normalizeTime)
{
property.animationCurveValue = NormalizeTime(property.animationCurveValue);
}
}
}
private static AnimationCurve NormalizeValue(AnimationCurve curve)
{
var keys = curve.keys;
if (keys.Length <= 0)
{
return curve;
}
var minVal = keys[0].value;
var maxVal = minVal;
foreach (var t in keys)
{
minVal = Mathf.Min(minVal, t.value);
maxVal = Mathf.Max(maxVal, t.value);
}
var range = maxVal - minVal;
var valScale = range < 1 ? 1 : 1 / range;
var valOffset = 0f;
if (range < 1)
{
if (minVal > 0 && minVal + range <= 1)
{
valOffset = minVal;
}
else
{
valOffset = 1 - range;
}
}
for (var i = 0; i < keys.Length; ++i)
{
keys[i].value = (keys[i].value - minVal) * valScale + valOffset;
}
curve.keys = keys;
return curve;
}
private static AnimationCurve NormalizeTime(AnimationCurve curve)
{
var keys = curve.keys;
if (keys.Length <= 0)
{
return curve;
}
var minTime = keys[0].time;
var maxTime = minTime;
foreach (var t in keys)
{
minTime = Mathf.Min(minTime, t.time);
maxTime = Mathf.Max(maxTime, t.time);
}
var range = maxTime - minTime;
var timeScale = range < 0.0001f ? 1 : 1 / range;
for (var i = 0; i < keys.Length; ++i)
{
keys[i].time = (keys[i].time - minTime) * timeScale;
}
curve.keys = keys;
return curve;
}
#endif
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Stuff : MonoBehaviour {
public Rigidbody Body { get; private set; }
private void Awake()
{
Body = GetComponent<Rigidbody>();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace EdubranApi.Models
{
/// <summary>
/// Student
/// </summary>
public class Student
{
[Key]
public int Id { get; set; }
[Required]
public string registrationId { get; set; }
[Required]
[EmailAddress]
public string email { get; set; }
public string phone { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public string profilePic { get; set; }
public string wallpaper { get; set; }
public string dateOfBirth { get; set; }
public string gender { get; set; }
[Required]
public string category { get; set; }
[Required]
/// <summary>
/// academic level, 1 means first year, 2 means second year etc
/// </summary>
public int level { get; set; }
public int application_number { get; set; }
public string transcripts { get; set; }
public string cv { get; set; }
public string national_id { set; get; }
public string linkdn { get; set; }
public string ethinicity { get; set; }
[Required]
public string institute { get; set; }
}
} |
using System;
using Server.Mobiles;
using Server.Targeting;
using System.Collections;
using System.Collections.Generic;
namespace Server.Items
{
public class Runescribing
{
// Blacklisted items
public static Type[] Blacklist = new Type[]
{
typeof( Dagger ),
};
public static void Enhance( Mobile from, BaseTool tool )
{
if ( from.Skills.Imbuing.Value < 80 )
{
from.SendMessage( "You lack the skill to enhance anything." );
}
else
{
from.Target = new EnhanceTarget( tool );
from.SendMessage( "Select the item you wish to enhance." );
}
}
private class EnhanceTarget : Target
{
private BaseTool m_Tool;
public EnhanceTarget( BaseTool tool ) : base( -1, false, TargetFlags.None )
{
m_Tool = tool;
}
protected override void OnTarget( Mobile from, object target )
{
if ( target is BaseArmor || target is BaseWeapon || target is BaseClothing || target is BaseJewel || target is BaseTalisman || target is BaseQuiver || target is Spellbook )
{
}
else if ( target is BaseMinorRune )
{
}
else
{
from.SendMessage( "This item cannot be enhanced." );
}
}
}
public static bool CheckBlacklist( Type type )
{
foreach ( Type check in Blacklist )
{
if ( check == type )
return true;
}
return false;
}
public static Item GetResoureDrop( bool isTmap, bool isGrave )
{
int amount = Utility.RandomMinMax( 2, 8 );
int roll = Utility.Random( 4 );
if ( isTmap == true )
{
if ( roll == 1 )
return new AncientSkeletonKey( amount );
if ( roll == 2 )
return new BrokenLockpicks( amount );
if ( roll == 3 )
return new CureAllTonic( amount );
if ( roll == 4 )
return new DustBunny( amount );
return new DustBunny( amount );
}
else if ( isGrave == true )
{
if ( Utility.Random( 100 ) < 3 )
{
return new WrappedBody();
}
else
{
if ( roll == 1 )
return new BoneDust( amount );
if ( roll == 2 )
return new BrokenHeart( amount );
if ( roll == 3 )
return new FreshBrain( amount );
if ( roll == 4 )
return new PerfectSkull( amount );
return new PerfectSkull( amount );
}
}
else
{
return new MagicalDust( amount );
}
}
public static int GetProps( Item sent )
{
int value = 0;
if ( sent is BaseArmor )
{
BaseArmor item = sent as BaseArmor;
foreach( int i in Enum.GetValues(typeof( AosAttribute ) ) )
{
if ( item != null && item.Attributes[ (AosAttribute)i ] > 0 )
value += 1;
}
foreach( int i in Enum.GetValues(typeof( AosArmorAttribute ) ) )
{
if ( item.ArmorAttributes[ (AosArmorAttribute)i ] > 0 )
value += 1;
}
if ( item.SkillBonuses.Skill_1_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_2_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_3_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_4_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_5_Value > 0 )
{
value += 1;
}
if ( item.ColdBonus > 0 )
{
value += 1;
}
if ( item.EnergyBonus > 0 )
{
value += 1;
}
if ( item.FireBonus > 0 )
{
value += 1;
}
if ( item.PhysicalBonus > 0 )
{
value += 1;
}
if ( item.PoisonBonus > 0 )
{
value += 1;
}
}
if ( sent is BaseWeapon )
{
BaseWeapon item = sent as BaseWeapon;
foreach( int i in Enum.GetValues(typeof( AosAttribute ) ) )
{
if ( item != null && item.Attributes[ (AosAttribute)i ] > 0 )
value += 1;
}
foreach( int i in Enum.GetValues(typeof( AosWeaponAttribute ) ) )
{
if ( item.WeaponAttributes[ (AosWeaponAttribute)i ] > 0 )
value += 1;
}
if ( item.SkillBonuses.Skill_1_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_2_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_3_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_4_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_5_Value > 0 )
{
value += 1;
}
if ( item.Slayer != SlayerName.None )
value += 1;
if ( item.Slayer2 != SlayerName.None )
value += 1;
}
if ( sent is BaseClothing )
{
BaseClothing item = sent as BaseClothing;
foreach( int i in Enum.GetValues(typeof( AosAttribute ) ) )
{
if ( item != null && item.Attributes[ (AosAttribute)i ] > 0 )
value += 1;
}
foreach( int i in Enum.GetValues(typeof( AosArmorAttribute ) ) )
{
if ( item.ClothingAttributes[ (AosArmorAttribute)i ] > 0 )
value += 1;
}
if ( item.SkillBonuses.Skill_1_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_2_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_3_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_4_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_5_Value > 0 )
{
value += 1;
}
if ( item.Resistances.Chaos > 0 )
value += 1;
if ( item.Resistances.Cold > 0 )
value += 1;
if ( item.Resistances.Direct > 0 )
value += 1;
if ( item.Resistances.Energy > 0 )
value += 1;
if ( item.Resistances.Fire > 0 )
value += 1;
if ( item.Resistances.Physical > 0 )
value += 1;
if ( item.Resistances.Poison > 0 )
value += 1;
}
if ( sent is BaseJewel )
{
BaseJewel item = sent as BaseJewel;
foreach( int i in Enum.GetValues(typeof( AosAttribute ) ) )
{
if ( item != null && item.Attributes[ (AosAttribute)i ] > 0 )
value += 1;
}
if ( item.SkillBonuses.Skill_1_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_2_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_3_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_4_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_5_Value > 0 )
{
value += 1;
}
if ( item.Resistances.Chaos > 0 )
value += 1;
if ( item.Resistances.Cold > 0 )
value += 1;
if ( item.Resistances.Direct > 0 )
value += 1;
if ( item.Resistances.Energy > 0 )
value += 1;
if ( item.Resistances.Fire > 0 )
value += 1;
if ( item.Resistances.Physical > 0 )
value += 1;
if ( item.Resistances.Poison > 0 )
value += 1;
}
if ( sent is BaseQuiver )
{
BaseQuiver item = sent as BaseQuiver;
foreach( int i in Enum.GetValues(typeof( AosAttribute ) ) )
{
if ( item != null && item.Attributes[ (AosAttribute)i ] > 0 )
value += 1;
}
if ( item.DamageIncrease > 0 )
value += 1;
if ( item.LowerAmmoCost > 0 )
value += 1;
}
if ( sent is BaseTalisman )
{
BaseTalisman item = sent as BaseTalisman;
foreach( int i in Enum.GetValues(typeof( AosAttribute ) ) )
{
if ( item != null && item.Attributes[ (AosAttribute)i ] > 0 )
value += 1;
}
if ( item.SkillBonuses.Skill_1_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_2_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_3_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_4_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_5_Value > 0 )
{
value += 1;
}
}
if ( sent is Spellbook )
{
Spellbook item = sent as Spellbook;
foreach( int i in Enum.GetValues(typeof( AosAttribute ) ) )
{
if ( item != null && item.Attributes[ (AosAttribute)i ] > 0 )
value += 1;
}
if ( item.SkillBonuses.Skill_1_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_2_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_3_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_4_Value > 0 )
{
value += 1;
}
if ( item.SkillBonuses.Skill_5_Value > 0 )
{
value += 1;
}
if ( item.Slayer != SlayerName.None )
value += 1;
if ( item.Slayer2 != SlayerName.None )
value += 1;
}
return value;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace EncryptDecryptMagic.EncryptDecrypt
{
public class EncryptDecrypt
{
public enum _enum_EncryptionDecryptionSecret { SECRET1, SECRET2, SECRET3};
public static string _fx_Encrypt(string DecryptedString, _enum_EncryptionDecryptionSecret EncryptionDecryptionSecret, LoggingFramework.ILog iLog, string UserTag)
{
string EncryptedString = string.Empty;
try
{
iLog.WriteDebug("Encryption - Decrypted String {0}", DecryptedString);
switch (EncryptionDecryptionSecret)
{
case _enum_EncryptionDecryptionSecret.SECRET1:
case _enum_EncryptionDecryptionSecret.SECRET2:
case _enum_EncryptionDecryptionSecret.SECRET3:
default:
EncryptedString = DecryptedString;
break;
}
}
catch (Exception exception)
{
iLog.WriteError(exception.ToString());
}
finally
{ }
return EncryptedString;
}
public static string _fx_Decrypt(string EncryptedString, _enum_EncryptionDecryptionSecret EncryptionDecryptionSecret, LoggingFramework.ILog iLog, string UserTag)
{
string DecryptedString = string.Empty;
try
{
iLog.WriteDebug("Decryption - Encrypted String {0}", EncryptedString);
switch (EncryptionDecryptionSecret)
{
case _enum_EncryptionDecryptionSecret.SECRET1:
case _enum_EncryptionDecryptionSecret.SECRET2:
case _enum_EncryptionDecryptionSecret.SECRET3:
default:
DecryptedString = EncryptedString;
break;
}
}
catch (Exception exception)
{
iLog.WriteError(exception.ToString());
}
finally
{ }
return DecryptedString;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.