text stringlengths 13 6.01M |
|---|
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 Entities;
using BLL;
using System.Data.Entity;
namespace WinFormUI
{
public partial class ProjectForm : MetroFramework.Forms.MetroForm
{
int selectedID;
EmployeeBusiness _employee;
CustomerBusiness _customer;
ProjectBusiness _project;
public ProjectForm()
{
InitializeComponent();
_customer = new CustomerBusiness(LoginForm.EmployeeId());
_employee = new EmployeeBusiness(LoginForm.EmployeeId());
_project = new ProjectBusiness(LoginForm.EmployeeId());
}
//Bu method yapılan değişiklikler için DataGridView 'imizi yenilememizi sağlar.
public void RefreshGridProject()
{
try
{
ICollection<Project> projectList = _project.GetAll();
dvgProjectList.DataSource = null;
dvgProjectList.DataSource = projectList;
}
catch (Exception ex)
{
MetroFramework.MetroMessageBox.Show(this, ex.Message);
}
}
private void btnAddEmployee_Click(object sender, EventArgs e)
{
}
private void ProjectForm_Load(object sender, EventArgs e)
{
//Bu method yapılan değişiklikler için DataGridView 'imizi yenilememizi sağlar.
RefreshGridProject();
//ProjectBusiness _project = new ProjectBusiness(employee);
cmbCompanyName.DataSource = _customer.GetAll();
cmbCompanyName.ValueMember = "ID";
cmbCompanyName.DisplayMember = "CompanyName";
cmbCompanyName.SelectedIndex = -1;
cmbJobAnalyst.DataSource = (from c in _employee.GetAll()
where c.RoleID == 3
select c).ToList();
cmbJobAnalyst.DisplayMember = "FullName";
cmbJobAnalyst.ValueMember = "ID";
cmbSoftwareDeveloper.DataSource = (from c in _employee.GetAll()
where c.RoleID == 4
select c).ToList();
cmbSoftwareDeveloper.DisplayMember = "FullName";
cmbSoftwareDeveloper.ValueMember = "ID";
cmbTeamLeader.DataSource = (from c in _employee.GetAll()
where c.RoleID == 2
select c).ToList();
cmbTeamLeader.DisplayMember = "FullName";
cmbTeamLeader.ValueMember = "ID";
cmbTester.DataSource = (from c in _employee.GetAll()
where c.RoleID == 5
select c)
.ToList();
cmbTester.DisplayMember = "FullName";
cmbTester.ValueMember = "ID";
}
#region Listeye göndermemize yarayan Buton Eventleri
private void btnAddTeamLeader_Click(object sender, EventArgs e)
{
lstEmployee.Items.Add(_employee.Get((int)cmbTeamLeader.SelectedValue));
}
private void btnAddJobAnalist_Click(object sender, EventArgs e)
{
lstEmployee.Items.Add(_employee.Get((int)cmbJobAnalyst.SelectedValue));
}
private void btnAddTester_Click(object sender, EventArgs e)
{
lstEmployee.Items.Add(_employee.Get((int)cmbTester.SelectedValue));
}
private void btnAddSoftwareDevelepor_Click(object sender, EventArgs e)
{
lstEmployee.Items.Add(_employee.Get((int)cmbSoftwareDeveloper.SelectedValue));
}
private void btnDeleteEmployee_Click(object sender, EventArgs e)
{
lstEmployee.Items.RemoveAt(lstEmployee.SelectedIndex);
}
#endregion
private void btnSaveCustomer_Click(object sender, EventArgs e)
{
CustomerForm customerForm = new CustomerForm();
customerForm.Show();
}
private void btnAddProject_Click(object sender, EventArgs e)
{
try
{
Project project = new Project();
project.Name = txtProjectName.Text;
project.Description = txtDescription.Text;
project.PlannedStartDate = dtpPlannedStartDate.Value;
project.PlannedEndDate = dtpPlannedEndDate.Value;
project.RealStartDate = dtpPlannedStartDate.Value;
project.RealEndDate = dtpPlannedEndDate.Value;
Customer customer = new Customer();
if (cmbCompanyName.SelectedValue == null)
{
MetroFramework.MetroMessageBox.Show(this, "Müşterisi Olmayan bir Proje Oluşturulamaz.Lütfen Bir Müşteri Seçiniz ", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
foreach (Customer item in _customer.GetAll())
{
if (cmbCompanyName.SelectedValue.ToString() == item.ID.ToString())
{
project.CustomerID = item.ID;
//Customer seçildiğinde veritabanına o id 'li Customerı komple gönderildi.
//Customer customName = _customer.Get(item.ID);
//project.Customer = customName;
}
}
//TODO:Çalışanlarımı gönderirken hata ile karşılaşıyorum
List<Employee> empCollection = new List<Employee>();
for (int i = 0; i < lstEmployee.Items.Count; i++)
{
empCollection.Add((Employee)lstEmployee.Items[i]);
}
project.Employees = empCollection;
_project.Add(project);
}
//Bu method yapılan değişiklikler için DataGridView 'imizi yenilememizi sağlar.
RefreshGridProject();
}
catch (Exception ex)
{
MetroFramework.MetroMessageBox.Show(this,ex.Message);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
Project deleteProject = null;
deleteProject = _project.Get(selectedID);
selectedID = 0;
_project.Remove(deleteProject);
RefreshGridProject();
}
catch (Exception ex)
{
MetroFramework.MetroMessageBox.Show(this, ex.Message);
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
Project updateProject = null;
updateProject = new Project();
updateProject = _project.Get(selectedID);
updateProject.Name = txtProjectName.Text;
updateProject.Description = txtDescription.Text;
updateProject.PlannedStartDate = dtpPlannedStartDate.Value;
updateProject.PlannedEndDate = dtpPlannedEndDate.Value;
updateProject.RealStartDate = dtpPlannedStartDate.Value;
updateProject.RealEndDate = dtpPlannedEndDate.Value;
//Customer customer = new Customer();
if (cmbCompanyName.SelectedValue == null)
{
MetroFramework.MetroMessageBox.Show(this, "Müşterisi Olmayan bir Proje Güncellenemez.Lütfen Bir Müşteri Seçiniz ", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
foreach (Customer item in _customer.GetAll())
{
if (cmbCompanyName.SelectedValue.ToString() == item.ID.ToString())
{
updateProject.CustomerID = item.ID;
Customer customName = _customer.Get(item.ID);
updateProject.Customer = customName;
}
}
for (int i = 0; i < lstEmployee.Items.Count; i++)
{
updateProject.Employees.Add((Employee)lstEmployee.Items[i]);
}
_project.Update(updateProject);
}
RefreshGridProject();
}
catch (Exception ex)
{
MetroFramework.MetroMessageBox.Show(this, ex.Message);
}
}
//BU Event DataGridView'de seçili olan satırımızı sayfamızda olan toolbox ürünlerimize göndermemizi sağlar.
private void dvgProjectList_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (dvgProjectList.SelectedRows.Count > 0)
{
DataGridViewRow dr = dvgProjectList.SelectedRows[0];
string updateIdInput = dr.Cells[0].Value.ToString();
selectedID = int.Parse(updateIdInput);
Project updateProject = _project.Get(selectedID);
txtProjectName.Text = updateProject.Name;
txtDescription.Text = updateProject.Description;
dtpPlannedStartDate.Value = updateProject.PlannedStartDate;
dtpPlannedEndDate.Value = updateProject.PlannedEndDate;
dtpPlannedStartDate.Value = (DateTime)updateProject.RealStartDate;
dtpPlannedEndDate.Value =(DateTime)updateProject.RealEndDate;
txtState.Text = updateProject.State;
cmbCompanyName.SelectedValue = (int)updateProject.CustomerID;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
|
using System;
namespace MySingleton
{
class Program
{
static void Main(string[] args)
{
//SingletonClass.getInstance();
//SingletonClass.getInstance();
//SingletonClass.getInstance();
LazySingleton a = LazySingleton.getInstance();
LazySingleton b = LazySingleton.getInstance();
if(a == b)
Console.WriteLine("Hello World!"); //the best check SHALLOW check,
//if they are pointed to the same object
//SingletonClass sc = new SingletonClass(); //cannot access
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace P03.Detail_Printer
{
interface IPrinter
{
public void Print();
}
}
|
using System;
namespace Fingo.Auth.DbAccess.Models
{
public class AuditLog
{
public AuditLog()
{
CreationDate = DateTime.UtcNow;
}
public int Id { get; set; }
public int? UserId { get; set; }
public string EventType { get; set; }
public string EventMassage { get; set; }
public DateTime CreationDate { get; set; }
}
} |
using EntVenta;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatVentas
{
public class DatGastoIngreso
{
public void InsertarIngresoGastos(IngresosGastos ig)
{
using (SqlConnection conn = new SqlConnection(MasterConnection.connection))
{
try
{
int resultado = 0;
conn.Open();
string query = ig.idConcepto == 0 ? "[insertar_tb_Ingresos]" : "[insertar_tb_Gastos]";
SqlCommand sc = new SqlCommand(query, conn);
sc.CommandType = CommandType.StoredProcedure;
sc.Parameters.AddWithValue("@Caja_Id", ig.idCaja);
if (ig.idConcepto != 0)
{
sc.Parameters.AddWithValue("@Concepto_Id", ig.idConcepto);
}
sc.Parameters.AddWithValue("@Fecha", ig.Fecha);
sc.Parameters.AddWithValue("@Nro_Documento", ig.NoComprobante);
sc.Parameters.AddWithValue("@Tipo_Comprobante", ig.TipoComprobante);
sc.Parameters.AddWithValue("@Importe", ig.Importe);
sc.Parameters.AddWithValue("@Descripcion", ig.Descripcion);
resultado = sc.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
conn.Close();
throw ex;
}
}
}
public DataTable ObtenerComrpobante()
{
using (SqlConnection conn = new SqlConnection(MasterConnection.connection))
{
try
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("[sp_Mostrar_TicketImpreso]", conn);
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
conn.Close();
throw ex;
}
}
}
public DataTable Obtener_VentasEnEspera()
{
using (SqlConnection con = new SqlConnection(MasterConnection.connection))
{
try
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tb_VentaEnEspera", con);
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
con.Close();
throw ex;
}
}
}
public int InsertarVentaEspera(VentaEspera ve)
{
using (SqlConnection conn = new SqlConnection(MasterConnection.connection))
{
try
{
int resultado = 0;
conn.Open();
SqlCommand sc = new SqlCommand("[sp_insertarVentaEspera]", conn);
sc.CommandType = CommandType.StoredProcedure;
sc.Parameters.AddWithValue("@idcliente", ve.IdCliente);
sc.Parameters.AddWithValue("@idusuario", ve.IdUsuario);
sc.Parameters.AddWithValue("@idcaja", ve.IdCaja);
sc.Parameters.AddWithValue("@fechaventa", ve.FechaVenta);
sc.Parameters.AddWithValue("@referencia", ve.Referencia);
sc.Parameters.AddWithValue("@montototal", ve.MontoTotal);
resultado = sc.ExecuteNonQuery();
conn.Close();
return resultado;
}
catch (Exception ex)
{
conn.Close();
throw ex;
}
}
}
public int EliminarVentaEspera(int id)
{
using (SqlConnection conn = new SqlConnection(MasterConnection.connection))
{
try
{
int resultado = 0;
conn.Open();
SqlCommand sc = new SqlCommand("DELETE FROM tb_VentaEnEspera WHERE Id="+id, conn);
resultado = sc.ExecuteNonQuery();
conn.Close();
return resultado;
}
catch (Exception ex)
{
conn.Close();
throw ex;
}
}
}
}
}
|
namespace Website.Models
{
public class GoToMoveResource
{
public GameStateResource GameState { get; set; }
public int HistoryIndex { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Totem.Util
{
public class ValidacionException : Exception
{
public ValidacionException(string msg)
: base(msg)
{
}
}
}
|
using System;
/*Write methods that calculate the surface of a triangle by given:
Side and an altitude to it;
Three sides;
Two sides and an angle between them;
Use System.Math.*/
class Program
{
static double SideAndAltitude()
{
Console.Write("side = ");
double side = double.Parse(Console.ReadLine());
Console.Write("altitude = ");
double altitude = double.Parse(Console.ReadLine());
return (side * altitude) / 2;
}
static double ThreeSides()
{
Console.Write("side = ");
double a = double.Parse(Console.ReadLine());
Console.Write("side = ");
double b = double.Parse(Console.ReadLine());
Console.Write("side = ");
double c = double.Parse(Console.ReadLine());
double p = (a + b + c) / 2;
return Math.Sqrt(p * (p - a) * (p - b) * (p - c));
}
static double TwoSidesAndAngle()
{
Console.Write("side = ");
double a = double.Parse(Console.ReadLine());
Console.Write("side = ");
double b = double.Parse(Console.ReadLine());
Console.Write("angle = ");
double gamma = double.Parse(Console.ReadLine());
return (a * b * Math.Sin(Math.PI * (gamma / 180))) / 2;
}
static void Main()
{
Console.WriteLine("1. Side and an altitude to it.");
Console.WriteLine("2. Three sides.");
Console.WriteLine("3. Two sides and an angle between them.");
Console.WriteLine("Press 1, 2 or 3 and then Enter.");
int method = int.Parse(Console.ReadLine());
double surface = 0;
if (method == 1)
surface = SideAndAltitude();
if (method == 2)
surface = ThreeSides();
if (method == 3)
surface = TwoSidesAndAngle();
Console.WriteLine("surface = {0}", surface);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
namespace TwiBo.Components.Model
{
public class TweetHistory : TableServiceEntity
{
public const string TableName = "TweetHistory";
public static string GetPartitionKey(string queryId)
{
return queryId.ToString().Replace("\\", "-").Replace("/", "-").Replace("#", "-").Replace("?", "-");
}
public string Author { get; set; }
public DateTime Created { get; set; }
public string Text { get; set; }
public string TextAsHtml { get; set; }
public bool Retweeted { get; set; }
}
public class TweetHistoryLimited : TableServiceEntity
{
public const string TableName = "TweetHistory";
public static string GetPartitionKey(string queryId)
{
return queryId.ToString().Replace("\\", "-").Replace("/", "-").Replace("#", "-").Replace("?", "-");
}
public string Author { get; set; }
public DateTime Created { get; set; }
public string Text { get; set; }
public string TextAsHtml { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.CosmosDb.GraphSyncers.Helpers;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.EmbeddedContentItemsGraphSyncer;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Helpers;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.Flows.Models;
namespace DFC.ServiceTaxonomy.GraphSync.CosmosDb.GraphSyncers.Parts.Flow
{
public class CosmosDbFlowPartEmbeddedContentItemsGraphSyncer : CosmosDbEmbeddedContentItemsGraphSyncer, IFlowPartEmbeddedContentItemsGraphSyncer
{
private const string Ordinal = "Ordinal";
private const string Alignment = "Alignment";
private const string Size = "Size";
private const string FlowMetaData = "FlowMetadata";
public CosmosDbFlowPartEmbeddedContentItemsGraphSyncer(
IContentDefinitionManager contentDefinitionManager,
ISyncNameProvider statelessSyncNameProvider,
IServiceProvider serviceProvider,
ILogger<CosmosDbFlowPartEmbeddedContentItemsGraphSyncer> logger)
: base(contentDefinitionManager, statelessSyncNameProvider, serviceProvider, logger)
{
}
protected override IEnumerable<string> GetEmbeddableContentTypes(IGraphSyncContext context)
{
return _contentDefinitionManager.ListTypeDefinitions()
.Where(t => t.GetSettings<ContentTypeSettings>().Stereotype == "Widget")
.Select(t => t.Name);
}
protected override async Task<Dictionary<string, object>?> GetRelationshipProperties(
ContentItem contentItem,
int ordinal,
ISyncNameProvider syncNameProvider)
{
// set the FlowMetaData as the relationship's properties
var flowMetaData = new Dictionary<string, object>
{
{Ordinal, (long)ordinal}
};
//todo: do we need more config/method for RelationshipPropertyName (and rename existing NodePropertyName?)
//todo: handle nulls?
JObject flowMetaDataContent = (JObject)contentItem.Content[FlowMetaData]!;
FlowAlignment alignment = (FlowAlignment)(int)flowMetaDataContent[Alignment]!;
flowMetaData.Add(await syncNameProvider!.PropertyName(Alignment), alignment.ToString());
flowMetaData.Add(await syncNameProvider!.PropertyName(Size), (long)flowMetaDataContent[Size]!);
return flowMetaData;
}
}
}
|
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.CommitmentsV2.Api.Client;
using SFA.DAS.CommitmentsV2.Types;
using SFA.DAS.ProviderCommitments.Queries.GetTrainingCourses;
using SFA.DAS.ProviderCommitments.Web.Models;
namespace SFA.DAS.ProviderCommitments.Web.Mappers
{
public class SelectCourseViewModelMapperHelper : ISelectCourseViewModelMapperHelper
{
private readonly ICommitmentsApiClient _commitmentsApiClient;
private readonly IMediator _mediator;
public SelectCourseViewModelMapperHelper(ICommitmentsApiClient commitmentsApiClient, IMediator mediator)
{
_commitmentsApiClient = commitmentsApiClient;
_mediator = mediator;
}
public async Task<SelectCourseViewModel> Map(string courseCode, long accountLegalEntityId, bool? isOnFlexiPaymentsPilot)
{
var ale = await _commitmentsApiClient.GetAccountLegalEntity(accountLegalEntityId);
return new SelectCourseViewModel
{
CourseCode = courseCode,
Courses = await GetCourses(ale.LevyStatus),
IsOnFlexiPaymentsPilot = isOnFlexiPaymentsPilot
};
}
private async Task<TrainingProgramme[]> GetCourses(ApprenticeshipEmployerType levyStatus)
{
var result = await _mediator.Send(new GetTrainingCoursesQueryRequest { IncludeFrameworks = levyStatus != ApprenticeshipEmployerType.NonLevy });
return result.TrainingCourses;
}
}
} |
namespace SubC.Attachments.ClingyEditor {
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(AngleLimits))]
public class AngleLimitsPropertyDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
EditorGUI.BeginProperty(position, label, property);
int indentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
float labelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 30;
Rect leftRect = new Rect(position.x, position.y, position.width, position.height);
// Rect leftRect = new Rect(position.x, position.y, position.width - 105, position.height);
float width = leftRect.width / 2 - 1;
Rect rect = new Rect(leftRect.x, leftRect.y, width, leftRect.height);
SerializedProperty prop = property.FindPropertyRelative("min");
EditorGUI.BeginChangeCheck();
float newMin = EditorGUI.FloatField(rect, "Min", prop.floatValue);
if (EditorGUI.EndChangeCheck())
prop.floatValue = newMin;
rect.x += width + 2;
prop = property.FindPropertyRelative("max");
EditorGUI.BeginChangeCheck();
float newMax = EditorGUI.FloatField(rect, "Max", prop.floatValue);
if (EditorGUI.EndChangeCheck())
prop.floatValue = newMax;
// Rect rightRect = new Rect(leftRect.x + leftRect.width + 8, leftRect.y, 95, leftRect.height);
// prop = property.FindPropertyRelative("relativeTo");
// EditorGUI.PropertyField(rightRect, prop, GUIContent.none);
EditorGUIUtility.labelWidth = labelWidth;
EditorGUI.indentLevel = indentLevel;
EditorGUI.EndProperty();
}
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Uintra.Features.Location.Models;
namespace Uintra.Core.Activity.Entities
{
public abstract class IntranetActivity : IIntranetActivity
{
[JsonIgnore]
public Guid Id { get; set; }
[JsonIgnore]
public Enum Type { get; set; }
[JsonIgnore]
public DateTime CreatedDate { get; set; }
[JsonIgnore]
public DateTime ModifyDate { get; set; }
[JsonIgnore]
public bool IsPinActual { get; set; }
[JsonIgnore]
public IEnumerable<int> MediaIds { get; set; } = Enumerable.Empty<int>();
public string Title { get; set; }
public string Description { get; set; }
public bool IsHidden { get; set; }
public bool IsPinned { get; set; }
public DateTime? EndPinDate { get; set; }
[JsonIgnore]
public ActivityLocation Location { get; set; }
}
} |
using Pe.Stracon.PoliticasCross.Core.Base;
namespace Pe.Stracon.PoliticasCross.Core.Exception
{
/// <summary>
/// Application Exception
/// </summary>
/// <remarks>
/// Creación: GMD 22122014 <br />
/// Modificación: <br />
/// </remarks>
public class ApplicationLayerException<T> : GenericException<T>
where T : class
{
/// <summary>
///
/// </summary>
public bool IsCustomException { get; set; }
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public ApplicationLayerException(string message, System.Exception e) : base(message, e) { }
/// <summary>
///
/// </summary>
/// <param name="e"></param>
public ApplicationLayerException(System.Exception e) : base(e) { }
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public ApplicationLayerException(string message)
: base(message)
{
this.IsCustomException = true;
}
}
}
|
namespace Krafteq.ElsterModel
{
using System;
public class KzFieldMeta
{
public string Description { get; }
public int Number { get; }
public KzFieldType Type { get; }
public KzFieldMeta(int number, KzFieldType type, string description)
{
this.Description = description ?? throw new ArgumentNullException(nameof(description));
this.Number = number;
this.Type = type ?? throw new ArgumentNullException(nameof(type));
}
}
} |
using PatientService.CustomException;
using System;
namespace PatientService.Model
{
public class Drug
{
public int Id { get; }
public string Name { get; }
public Drug(int id, string name)
{
Id = id;
Name = name;
Validate();
}
private void Validate()
{
if (String.IsNullOrWhiteSpace(Name))
throw new ValidationException("Drug name cannot be empty.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HandlingWordRules;
namespace ClientForWordApp
{
//This is the client program .The Words rule program is called from here.
class Program
{
static void Main(string[] args)
{
//This is the list of words that is provided for testing
List<string> data = new List<string> {"Chad","Australia" ,"Chinese", "Arab", "Indian", "African", "Canadian", "Azerbaijani", "Egyptian" ,"Bile","Beleize","Beligium", "Mozambique" };
WordsRuleContext sortingContext = new WordsRuleContext();
float result = 0;
//For all the words starts with “a” or “A”, count the average length of the words, save the result to file
//“average_length_of_words_starting_with_a.txt”
result = sortingContext.GetAnswer("Rule1", data);
//For all the words starts with “b” or “B”, count the total number of “e” or “E” in the words, save the
//result to file “count_of_e_in_words_starting_with_b.txt”
result = sortingContext.GetAnswer("Rule2", data);
//For all the words starts with “a” or “b” or “c”, get the longest length of the words.Save the result to
//file “longest_words_starting_with_abc.txt”
result = sortingContext.GetAnswer("Rule3", data);
//For all the words starts with “c” or “C”, if the next word starts with “a” or “A”, count the number of this
//sequence.Save the result to “count_of_sequence_of_words_starting_withs_c_and_a.txt”
result = sortingContext.GetAnswer("Rule4", data);
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using System.Xml.Serialization;
namespace FiiiCoin.Wallet.Win.Models
{
[XmlRoot("MenuSeparator")]
public class MenuSeparator : MenuBase
{
public MenuSeparator()
{
this.MenuType = MenuType.Separator;
}
}
}
|
a b c d e f g |
namespace ProgrammingGame.Domain
{
public class Submission
{
public int Id { get; set; }
public int ProblemId { get; set; }
public string Nickname { get; set; }
public string Solution { get; set; }
public bool IsSuccessful { get; set; }
}
}
|
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
using OrchardCore.Navigation;
namespace DFC.ServiceTaxonomy.JobProfiles.DataTransfer
{
public class AdminMenu : INavigationProvider
{
private readonly IStringLocalizer S;
public AdminMenu(IStringLocalizer<AdminMenu> localizer) =>
S = localizer;
public Task BuildNavigationAsync(string name, NavigationBuilder builder)
{
if (string.Equals(name, "admin", StringComparison.OrdinalIgnoreCase))
{
builder
.Add(S["Azure Search"], "99", azSearch =>
azSearch
.Id("index")
.Add(S["Reindex"], "1", reindex => reindex
.Permission(Permissions.ManageAzureSearchIndex)
.Action("TriggerReindex", "Admin", new { area = typeof(Startup)!.Namespace }))
);
}
return Task.CompletedTask;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DemoLibrary.Models;
using MediatR;
namespace DemoLibrary.Writes
{
// this will create properties based on those names down here FirstName and LastName
public record InsertPersonCommand(string FirstName, string LastName): IRequest<PersonModel>;
// This is the class approach
//public class InsertPersonCommand : IRequest<PersonModel>
//{
// public string FirstName { get; set; }
// public string LastName { get; set; }
// public InsertPersonCommand(string firstName, string lastName)
// {
// FirstName = firstName;
// LastName = lastName;
// }
//}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CheckIt.Tests.Data.CallingMethod
{
class ClassCalled
{
public void CalledMethod<T>()
{
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace SingLife.FacebookShareBonus.Model
{
internal class AscendingOrderOfPoliciesStartDate : IPolicySortService
{
public IEnumerable<Policy> Sort(IEnumerable<Policy> policies)
{
policies = policies.OrderBy(p => p.StartDate);
return policies;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shipwreck.TypeScriptModels.Declarations
{
public sealed class PropertySignature : Signature
{
public string PropertyName { get; set; }
public bool IsOptional { get; set; }
public ITypeReference PropertyType { get; set; }
internal override void WriteSignature(TextWriter writer)
{
writer.Write(PropertyName);
if (IsOptional)
{
writer.Write('?');
}
if (PropertyType != null)
{
writer.Write(": ");
PropertyType.WriteTypeReference(writer);
}
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using ApiTemplate.Core.Entities.Weathers;
namespace ApiTemplate.Service.Weathers
{
public interface IWeatherService
{
Task AddWeather(Weather weather, CancellationToken cancellationToken=default);
}
} |
namespace PlayWithToList
{
using System;
using System.Diagnostics;
using System.Linq;
using Ads.Data;
class Program
{
static void Main()
{
AdsContext context = new AdsContext();
context.Ads.Count();
//SlowWay(context); //Time elapsed for slow query: 00:00:00.0610211
//FasterWay(context); //Time elapsed for fast query: 00:00:00.0158581
}
private static void SlowWay(AdsContext context)
{
Stopwatch slowway = new Stopwatch();
slowway.Start();
var ads = context.Ads.ToList().Where(ad => ad.AdStatus?.Status == "Published").Select(ad => new
{
ad.Title,
CategoryName = ad.Category?.Name,
TownName = ad.Town?.Name,
Date = ad.Date
}).ToList().OrderBy(arg => arg.Date);
foreach (var ad in ads)
{
Console.WriteLine($"{ad.Title} {ad.CategoryName} {ad.TownName} {ad.Date}");
}
slowway.Stop();
Console.WriteLine($"Time elapsed for slow query: {slowway.Elapsed}");
}
private static void FasterWay(AdsContext context)
{
Stopwatch fastwatch = new Stopwatch();
fastwatch.Start();
var adsInfo = context.Ads
.Where(ad => ad.AdStatus.Status == "Published")
.OrderBy(ad => ad.Date)
.Select(ad => new
{
ad.Title,
CategoryName = ad.Category.Name,
TownName = ad.Town.Name,
ad.Date
});
foreach (var adInfo in adsInfo)
{
Console.WriteLine($"{adInfo.Title} {adInfo.TownName} {adInfo.CategoryName} {adInfo.Date}");
}
fastwatch.Stop();
Console.WriteLine($"Time elapsed for fast query: {fastwatch.Elapsed}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using UniversityCourseAndResultMangementSystem.Models;
namespace UniversityCourseAndResultMangementSystem.Gateway
{
public class DepartmentGateway
{
private string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionDB"].ConnectionString;
public int InsertDepartment(DepartmentModel saveDepartment)
{
SqlConnection con = new SqlConnection(connectionString);
string query = "insert into Department values('" + saveDepartment.Name + "','" +
saveDepartment.Code + "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
int rowAffect = cmd.ExecuteNonQuery();
con.Close();
return rowAffect;
}
public string IsExisteDepartmentModel(DepartmentModel departmentModel)
{
string message = null;
SqlConnection con = new SqlConnection(connectionString);
string query = "select * from Department where DepartName = '" + departmentModel.Name + "' OR DepartCode = '" + departmentModel.Code + "'";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
if (dataReader.Read())
{
message = "This Name OR Code Already Existe";
}
return message;
}
public List<DepartmentModel> GateAllDepertmentGateway()
{
SqlConnection con = new SqlConnection(connectionString);
string query = "select * from Department";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
List<DepartmentModel> saveDepartments = new List<DepartmentModel>();
if (dataReader.HasRows)
{
while (dataReader.Read())
{
DepartmentModel departmentModel = new DepartmentModel();
departmentModel.DepartmentID = Convert.ToInt32(dataReader["DepartmentID"]);
departmentModel.Name = dataReader["DepartName"].ToString();
departmentModel.Code = dataReader["DepartCode"].ToString();
saveDepartments.Add(departmentModel);
}
dataReader.Close();
}
con.Close();
return saveDepartments;
}
}
} |
using System.Reflection;
using Harmony;
namespace MultiplayerEmotes.Framework.Patches {
public abstract class ClassPatch : IClassPatch {
public virtual MethodInfo Original => null;
public virtual MethodInfo Prefix => null;
public virtual MethodInfo Postfix => null;
public virtual MethodInfo Transpiler => null;
public bool PrefixEnabled { get; set; } = true;
public bool PostfixEnabled { get; set; } = true;
public bool TranspilerEnabled { get; set; } = true;
public void Register(HarmonyInstance harmony) {
harmony.Patch(Original, Prefix == null ? null : new HarmonyMethod(Prefix), Postfix == null ? null : new HarmonyMethod(Postfix), Transpiler == null ? null : new HarmonyMethod(Transpiler));
}
public void Remove(HarmonyInstance harmony, HarmonyPatchType patchType = HarmonyPatchType.All) {
harmony.Unpatch(Original, patchType, harmony.Id);
}
}
}
|
using ISE.Framework.Common.CommonBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISE.SM.Common.DTO
{
public partial class CompanyDto:BaseDto
{
public CompanyDto()
{
this.PrimaryKeyName = "SecurityCompanyId";
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class StateSaver
{
public static Scene savedScene; //:D
}
|
public class Solution {
public double MyPow(double x, int n) {
if (n == 0) return 1.0;
if (n == 1) return x;
int half = Math.Abs(n/2);
double halfRes = MyPow(x, half);
if (n % 2 == 0) return n>0 ? halfRes*halfRes : 1/(halfRes*halfRes);
return n>0 ? halfRes*halfRes*x : 1/(halfRes*halfRes*x);
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace GFW
{
public sealed class GameSystem : ServiceModule<GameSystem>
{
private string m_domain;
private MonoBehaviour m_MonoEntity;
private IController m_controller;
private Dictionary<string, ManagerModule> m_ManagerDic = new Dictionary<string, ManagerModule>();
private List<ManagerModule> m_ManagerList = new List<ManagerModule>();
public GameSystem()
{
m_controller = Controller.Instance;
}
public ManagerModule this[string name]
{
get
{
ManagerModule mgr;
if (m_ManagerDic.TryGetValue(name, out mgr))
{
return mgr;
}
return null;
}
private set { }
}
public void Init(string domain = "")
{
this.m_domain = domain;
}
public void OnAwake(MonoBehaviour mono)
{
m_MonoEntity = mono;
for (int i = 0;i< m_ManagerList.Count;i++)
{
m_ManagerList[i].Awake(mono);
}
}
public void OnStart()
{
for (int i = 0; i < m_ManagerList.Count; i++)
{
m_ManagerList[i].Start();
}
}
public void OnUpdate()
{
for (int i = 0; i < m_ManagerList.Count; i++)
{
m_ManagerList[i].Update();
}
}
public void ReleaseAll()
{
for (int i = 0; i < m_ManagerList.Count; i++)
{
m_ManagerList[i].Release();
}
m_ManagerList.Clear();
m_ManagerList = null;
m_ManagerDic.Clear();
m_ManagerDic = null;
}
#region - Command
public void ExecuteCommand(string commandName, object body = null, string type = null)
{
if(!this.HasCommand(commandName))
{
RegisterCommand(commandName);
}
m_controller.ExecuteCommand(new Message(commandName, body, type));
}
public void ExecuteCommandOnce(string commandName, object body = null, string type = null)
{
this.ExecuteCommand(commandName, body, type);
this.RemoveCommand(commandName);
}
public void RegisterCommand(string commandName)
{
Type type = Type.GetType(m_domain + "." + commandName);
if(type == null)
{
LogMgr.LogError("Register Command<{0}> Type Not Exist!", commandName);
return;
}
m_controller.RegisterCommand(type);
}
public void RemoveCommand(string commandName)
{
m_controller.RemoveCommand(commandName);
}
public bool HasCommand(string commandName)
{
return m_controller.HasCommand(commandName);
}
#endregion
public ManagerModule CreateManager(string mgrName)
{
if (this.GetManager(mgrName) != null)
{
LogMgr.LogError("The Manager<{0}> Has Existed!", mgrName);
return null;
}
Type type = Type.GetType(m_domain + "." + mgrName);
if (type == null)
{
LogMgr.LogError("The Manager<{0}> Type Is Error!", mgrName);
return null;
}
return AddManager(type);
}
private ManagerModule AddManager(Type type)
{
ManagerModule mgr = null;
if (m_ManagerDic.TryGetValue(type.Name, out mgr))
{
return mgr;
}
LogMgr.Log("AddManager type = {0}",type.Name);
mgr = Activator.CreateInstance(type) as ManagerModule;
m_ManagerDic.Add(type.Name, mgr);
m_ManagerList.Add(mgr);
return mgr;
}
public ManagerModule GetManager(string name)
{
ManagerModule mgr = null;
if (m_ManagerDic.TryGetValue(name, out mgr))
{
return mgr;
}
return mgr;
}
public T GetManager<T>() where T:ManagerModule
{
Type t = typeof(T);
T mgr = (T)this.GetManager(t.Name);
if (mgr != null)
{
return mgr;
}
return default(T);
}
public void SendMessage(string mgrName, string handlerName, params object[] args)
{
this.SendMessage_Internal(mgrName, handlerName, args);
}
private void SendMessage_Internal(string mgrName, string handlerName, object[] args)
{
ManagerModule module = GetManager(mgrName);
if (module != null)
{
module.HandleMessage(handlerName, args);
}
else
{
//List<MessageObject> list = GetCacheMessageList(target);
//MessageObject obj = new MessageObject();
//obj.target = target;
//obj.msg = msg;
//obj.args = args;
//list.Add(obj);
//LogMgrWarning("模块不存在!将消息缓存起来! target:{0}, msg:{1}, args:{2}", target, msg, args);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class AudioManager : MonoBehaviour {
public bool foundEnemy = false;
public AudioClip[] clips;
public AudioSource source;
public bool activateChange = false;
// Use this for initialization
void Start () {
source = GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
if (activateChange) {
if (source.volume > 0.1)
source.volume = Mathf.Max(0, source.volume - Time.deltaTime/2);
else {
source.clip = clips [2];
source.volume = 1;
source.Play ();
activateChange = false;
}
}
}
public void FoundPlayer() {
if (!foundEnemy) {
foundEnemy = true;
source.clip = clips [0];
source.Play ();
Invoke ("Clip1", clips [0].length);
}
}
void Clip1() {
source.clip = clips [1];
source.Play ();
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CQRS.MediatR.Command;
using CQRS.MediatR.Event;
using CsvHelper;
using MediatR;
using Scheduler.FileService.Events;
namespace Scheduler.FileService.Commands
{
public class SaveHandler : ICommandHandler<SaveToCsv>
{
private readonly IEventBus _eventBus;
public SaveHandler(IEventBus eventBus)
{
this._eventBus = eventBus;
}
public async Task<Unit> Handle(SaveToCsv request, CancellationToken cancellationToken)
{
StreamWriter streamWriter = new StreamWriter(request.FilePath);
CsvWriter csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture);
await csvWriter.WriteRecordsAsync(request.Collection);
await csvWriter.DisposeAsync();
await _eventBus.Publish(new RecordsSavedToFile(request.FilePath, request.Collection.Count), cancellationToken);
return Unit.Value;
}
}
} |
using System;
using System.ComponentModel;
using System.Linq;
using DelftTools.Shell.Core;
using DelftTools.Tests.Core.Mocks;
using DelftTools.Utils;
using DelftTools.Utils.IO;
using NetTopologySuite.Extensions.Coverages;
using NUnit.Framework;
using Rhino.Mocks;
namespace DelftTools.Tests.Core
{
[TestFixture]
public class DataItemTest
{
private static readonly MockRepository mocks = new MockRepository();
[Test]
public void CreateContainingObjectValue()
{
var dataObject = new CloneableClassWithThreeProperties {Name = "b"};
var data = new DataItem(dataObject, "a");
Assert.AreEqual(dataObject, data.Value);
Assert.AreEqual("a", data.Name);
Assert.AreEqual(typeof(CloneableClassWithThreeProperties), data.ValueType);
Assert.AreEqual(DataItem.DefaultRole, data.Role);
Assert.AreEqual(null, data.Owner);
Assert.AreEqual(0, data.Id);
Assert.AreEqual(0, data.LinkedBy.Count);
Assert.AreEqual(null, data.LinkedTo);
}
[Test]
public void LinkAndUnlinkTwoDataItems()
{
var dataObject1 = new CloneableClassWithThreeProperties();
var dataObject2 = new CloneableClassWithThreeProperties();
var dataItem1 = new DataItem(dataObject1, "a1");
var dataItem2 = new DataItem(dataObject2, "a2");
dataItem2.LinkTo(dataItem1);
Assert.IsTrue(dataItem2.IsLinked);
Assert.AreSame(dataItem1, dataItem2.LinkedTo);
Assert.AreSame(dataItem2, dataItem1.LinkedBy[0]);
dataItem2.Unlink();
Assert.AreEqual(null, dataItem2.LinkedTo);
Assert.AreEqual(0, dataItem1.LinkedBy.Count);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void AssigningValueOfWrongValueTypeShowThrowException()
{
var dataItem = new DataItem { Name = "item", ValueType = typeof(int) };
dataItem.Value = 0.0; // <-- throws exception
}
[Test]
[NUnit.Framework.Description("TODO: is this type of data items allowed? Or only object-based")]
public void CreateContainingSimpleValue()
{
var dataItem = new DataItem { Name = "item", ValueType = typeof(int) };
int i = 0;
dataItem.Value = i;
dataItem.Name = "i";
dataItem.Description = "simple integer value";
Assert.AreEqual(dataItem.Name, "i");
}
[Test]
public void GetAllItemsRecursive()
{
DataItem di = new DataItem();
di.Value = 9;
Assert.AreEqual(new object[]{di,9},di.GetAllItemsRecursive().ToArray());
DataItem emptyDi = new DataItem();
Assert.AreEqual(new object[] { emptyDi}, emptyDi.GetAllItemsRecursive().ToArray());
DataItem stringDi = new DataItem();
stringDi.Value = "9";
Assert.AreEqual(new object[] { stringDi, "9" }, stringDi.GetAllItemsRecursive().ToArray());
}
[Test]
public void Clone()
{
DataItem di = new DataItem(9,"name",typeof(int),DataItemRole.Output,"tag");
di.Id = 5;
DataItem clone = (DataItem) di.DeepClone();
//be sure the id gets reset
Assert.AreEqual(0,clone.Id);
Assert.AreEqual(di.Value,clone.Value);
Assert.AreEqual(di.Name, clone.Name);
Assert.AreEqual(di.ValueType, clone.ValueType);
Assert.AreEqual(di.Role, clone.Role);
Assert.AreEqual(di.Tag, clone.Tag);
Assert.AreEqual(di.IsCopyable, clone.IsCopyable);
Assert.AreEqual(di.IsRemoveable, clone.IsRemoveable);
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void CloneNotCloneableValueObject()
{
IDataItem dataItem = new DataItem();
dataItem.Value = mocks.Stub<IFileBased>();
var clone = (DataItem)dataItem.DeepClone();
}
[Test]
public void CloneLinkedDataItem()
{
var dataItem = new DataItem();
dataItem.Value = new CloneableClassWithThreeProperties();
//TODO: why do we need to set the valuetype. Why is this not Typeof(value)???
//or (next best) why is this determined at construction time.
dataItem.ValueType = typeof (CloneableClassWithThreeProperties);
IDataItem linkedDataItem = new DataItem();
linkedDataItem.ValueType = typeof(CloneableClassWithThreeProperties);
linkedDataItem.LinkTo(dataItem);
Assert.AreEqual(dataItem.ValueType,linkedDataItem.ValueType);
//action! clone the linked dataitem
var clonedLinkedDataItem = (DataItem)linkedDataItem.DeepClone();
Assert.AreEqual(linkedDataItem.ValueType,clonedLinkedDataItem.ValueType );
}
[Test]
public void CloneShouldNotCausePropertyChangeOnSourceValue()
{
//set a nameable property changing class in the dataItem
var propertyChangingClass = new CloneableClassWithThreeProperties();
var dataItem = new DataItem(propertyChangingClass);
propertyChangingClass.PropertyChanged += delegate
{
Assert.Fail("Clone should not cause a change in the source!");
};
//action clone the dataitem.
dataItem.DeepClone();
}
[Test]
public void NameShouldNotChangeWhenSettingValueWithANotNamedValue()
{
IDataItem dataItem = new DataItem();
dataItem.Name = "Hoi";
//assign a not nameble value.
dataItem.Value = new DateTime();
Assert.AreEqual("Hoi", dataItem.Name);
}
[Test]
public void NameShouldChangeWhenSettingValueWithANamedValue()
{
IDataItem dataItem = new DataItem {Name = "Hoi"};
//assign a nameble value.
var cloneableClassWithThreeProperties = new CloneableClassWithThreeProperties { Name = "Dag" };
dataItem.Value = cloneableClassWithThreeProperties;
Assert.AreEqual("Dag", dataItem.Name);
}
[Test]
public void VerifyDefaults()
{
IDataItem dataItem = new DataItem { Name = "Hoi" };
Assert.IsTrue(dataItem.IsRemoveable);
Assert.IsTrue(dataItem.IsCopyable);
Assert.IsFalse(dataItem.NameIsReadOnly);
}
[Test]
public void ShouldBeAbleToChangeNameOfNotINameAbleClass()
{
IDataItem dataItem = new DataItem { Name = "Hoi" };
//a class with a name but not inameable..for example 3rd party ..for example grouplayer,vectorlayer
var nameableClass = new ClassWithNameButNotINameable();
dataItem.Value = nameableClass;
nameableClass.Name = "kees";
//check the name did not go..maybe change this functionality but this requires reflection..
Assert.AreEqual("Hoi", dataItem.Name);
}
[Test]
public void DataItemNameShouldChangeWhenNamedValueNameChanges()
{
IDataItem dataItem = new DataItem {Name = "Hoi"};
//assign a nameble value.
CloneableClassWithThreeProperties cloneableClassWithThreeProperties = new CloneableClassWithThreeProperties {Name = "Dag"};
dataItem.Value = cloneableClassWithThreeProperties;
cloneableClassWithThreeProperties.Name = "huh";
Assert.AreEqual("huh", dataItem.Name);
}
[Test]
public void NameValueNameShouldChangeWhenDataItemNameChanges()
{
IDataItem dataItem = new DataItem { Name = "Hoi" };
//assign a nameble value.
CloneableClassWithThreeProperties cloneableClassWithThreeProperties = new CloneableClassWithThreeProperties { Name = "Dag" };
dataItem.Value = cloneableClassWithThreeProperties;
dataItem.Name = "huh";
//cloneableClassWithThreeProperties.Name = "huh";
Assert.AreEqual("huh", cloneableClassWithThreeProperties.Name);
}
/// <summary>
/// When creating a dataitem with a named value should be ignored
/// </summary>
[Test]
public void NameShouldBeSetWhenCreatingNameableDataItem()
{
var dataObject = new CloneableClassWithThreeProperties { Name = "OldName" };
var dataItem = new DataItem(dataObject, "NewName");
Assert.AreEqual("NewName", dataItem.Name);
}
/// <summary>
/// When creating a dataitem with a named value should be ignored
/// </summary>
[Test]
public void NameShouldBeKeptWhenCreatingNameableDataItem()
{
var dataObject = new CloneableClassWithThreeProperties { Name = "OldName" };
var dataItem = new DataItem(dataObject);
Assert.AreEqual("OldName", dataItem.Name);
}
[Test]
public void NameShouldChangeWhenLinkedNamedValueNameChanges()
{
var dataObject1 = new CloneableClassWithThreeProperties();
var dataObject2 = new CloneableClassWithThreeProperties();
var dataItem1 = new DataItem(dataObject1, "name1");
var dataItem2 = new DataItem(dataObject2, "name2");
dataItem2.LinkTo(dataItem1);
Assert.AreEqual("name1", dataItem1.Name);
Assert.AreEqual("name2", dataItem2.Name, "name of the target data item remains the same after linking");
Assert.AreEqual("name1", ((INameable)dataItem1.Value).Name);
Assert.AreEqual("name1", ((INameable)dataItem2.Value).Name);
dataObject2.Name = "newName2";
Assert.AreEqual("name1", ((INameable)dataItem1.Value).Name);
Assert.AreEqual("name1", ((INameable)dataItem2.Value).Name);
dataObject1.Name = "newName1";
Assert.AreEqual("newName1", ((INameable)dataItem1.Value).Name);
Assert.AreEqual("newName1", ((INameable)dataItem2.Value).Name);
dataItem2.Unlink();
// unlinking results in a new object of the original type as Value in the
// item with an uninitialized name.
// The original dataObject2 is now an orphan.
Assert.AreEqual("newName1", ((INameable)dataItem1.Value).Name);
Assert.AreEqual("newName1", ((INameable)dataItem2.Value).Name); // item was linked to newName1
((INameable)dataItem2.Value).Name = "newerName2";
Assert.AreEqual("newerName2", dataItem2.Name);
dataItem2.Name = "weereensietsanders";
Assert.AreEqual("weereensietsanders", ((INameable)dataItem2.Value).Name);
}
[Test]
public void PropertyChangedWorkOnLinkedItems()
{
var propertyChangedClass = new CloneableClassWithThreeProperties();
var sourceDataItem = new DataItem(propertyChangedClass);
var linkedDataItem = new DataItem(new CloneableClassWithThreeProperties());
linkedDataItem.LinkTo(sourceDataItem);
int callCount = 0;
((INotifyPropertyChanged) linkedDataItem).PropertyChanged += (s, e) =>
{
callCount++;
Assert.AreEqual(propertyChangedClass, s);
Assert.AreEqual("StringProperty", e.PropertyName);
};
propertyChangedClass.StringProperty = "newName";
Assert.AreEqual(1,callCount);
}
[Test]
public void LinkedEventIncludesPreviousValue()
{
//old value is needed to close views.
var oldValue = new Url();
var sourceDataItem = new DataItem(new Url());
var targetDataItem = new DataItem(oldValue);
int callCount = 0;
targetDataItem.Linked += (s, e) =>
{
callCount++;
Assert.AreEqual(sourceDataItem, e.Source);
Assert.AreEqual(targetDataItem, e.Target);
Assert.AreEqual(oldValue,e.PreviousValue);
};
targetDataItem.LinkTo(sourceDataItem);
}
[Test]
public void UnLinkEventIncludesPreviousValue()
{
//old value is needed to close views.
var linkedValue = new Url();
var sourceDataItem = new DataItem(linkedValue);
var targetDataItem = new DataItem(new Url());
int callCount = 0;
targetDataItem.Unlinked += (s, e) =>
{
callCount++;
Assert.AreEqual(sourceDataItem, e.Source);
Assert.AreEqual(targetDataItem, e.Target);
Assert.AreEqual(linkedValue, e.PreviousValue);
};
targetDataItem.LinkTo(sourceDataItem);
//action! unlink
targetDataItem.Unlink();
}
[Test]
public void LinkAndUnlinkTwoDiscretizationItems()
{
var dataObject1 = new Discretization();
var dataObject2 = new Discretization();
var dataItem1 = new DataItem(dataObject1, "a1");
var dataItem2 = new DataItem(dataObject2, "a2");
dataItem2.LinkTo(dataItem1);
Assert.IsTrue(dataItem2.IsLinked);
Assert.AreSame(dataItem1, dataItem2.LinkedTo);
Assert.AreSame(dataItem2, dataItem1.LinkedBy[0]);
dataItem2.Unlink();
Assert.AreEqual(null, dataItem2.LinkedTo);
Assert.AreEqual(0, dataItem1.LinkedBy.Count);
}
[Test]
public void LinkAndUnlinkTwoDiscretizationItemsCheckValueAndName()
{
var grid1 = new Discretization { Name = "grid1" };
var grid2 = new Discretization { Name = "grid2" };
var dataItem1 = new DataItem(grid1, "a1");
var dataItem2 = new DataItem(grid2, "a2");
dataItem2.LinkTo(dataItem1);
dataItem2.Unlink();
Assert.AreEqual(typeof(Discretization), dataItem2.Value.GetType());
Assert.AreEqual(typeof(Discretization), dataItem1.Value.GetType());
var grid2X = (Discretization)dataItem2.Value;
Assert.AreEqual("a2", grid2X.Name, "name is the same as a data item name");
}
[Test]
public void DoNotCallGetAllItemsRecursiveOnValuesWhenDataItemIsLinked()
{
var value = mocks.StrictMock<IItemContainer>();
var source = new DataItem(value, "source");
var target = new DataItem(value, "target");
mocks.ReplayAll();
target.LinkTo(source);
target.GetAllItemsRecursive().ToArray(); // should not call value.GetAllItemsRecursive()
mocks.VerifyAll();
}
}
} |
using System.Web.Http;
using TestApi.BL;
using TestApi.BO;
namespace TestApi.Controllers
{
[RoutePrefix("Tasks")]
public class MainController : ApiController
{
[HttpPost]
[Route("insertask")]
public ReplyBo<bool> InsertTask(Task task)
{
return new TaskHandler().InsertTask(task);
}
[HttpGet]
[Route("getasks")]
public ReplyBo<TaskCollection> GetAllTasks()
{
return new TaskHandler().GetTasks();
}
}
}
|
using MikeGrayCodes.BuildingBlocks.Application;
namespace MikeGrayCodes.BuildingBlocks.Infrastructure.Outbox.Processing
{
public class ProcessOutboxCommand : Command, IRecurringCommand
{
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StageSequenceState {
protected GameObject player;
protected Animator animator;
protected StageSequenceMachine stateMachine;
protected PlayerStateMachine playerStateMachine;
protected Vector3 enterPosition;
protected Vector3 startPosition;
protected Vector3 goalPosition;
protected Vector3 exitPosition;
protected static int deadTimes;
public StageSequenceState()
{
player = GameObject.FindGameObjectWithTag("Player");
animator = player.GetComponent<Animator>();
stateMachine = GameObject.Find("StageStateMachine").GetComponent<StageSequenceMachine>();
playerStateMachine = player.GetComponent<PlayerStateMachine>();
enterPosition = GameObject.Find("EnterPosition").transform.position;
startPosition = GameObject.Find("StartPosition").transform.position;
goalPosition = GameObject.Find("GoalPosition").transform.position;
exitPosition = GameObject.Find("ExitPosition").transform.position;
//y軸はプレイヤーに合わせる
enterPosition.y = player.transform.position.y;
startPosition.y = player.transform.position.y;
startPosition.y = player.transform.position.y;
deadTimes = 0;
}
public virtual void StageEnter() { }
public virtual void StageUpdate() { }
public virtual void StageExit() { }
}
|
using System.Collections.Generic;
using Abp.Application.Services.Dto;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.GeneralTree;
using Newtonsoft.Json;
namespace RegionTree
{
public class Region : FullAuditedEntity, IGeneralTree<Region, int>
{
public string RegionCode { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public string Code { get; set; }
public int Level { get; set; }
[JsonIgnore]
public Region Parent { get; set; }
public int? ParentId { get; set; }
public ICollection<Region> Children { get; set; }
}
public class RegionDto : EntityDto, IGeneralTreeDto<RegionDto, int>
{
public string RegionCode { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public string Code { get; set; }
public int Level { get; set; }
public int? ParentId { get; set; }
public ICollection<RegionDto> Children { get; set; }
}
} |
using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace SauvignonInStardew
{
/// <summary>The model for mod data stored in the save file.</summary>
internal class SaveData
{
/*********
** Accessors
*********/
/// <summary>The tile coordinates for winery buildings.</summary>
public List<Point> WineryCoords { get; set; } = new List<Point>();
}
}
|
using System.IO;
using Tomelt.Environment.Extensions.Models;
namespace Tomelt.Packaging.Services {
public interface IPackageBuilder : IDependency {
Stream BuildPackage(ExtensionDescriptor extensionDescriptor);
}
} |
namespace ApartmentApps.Api.Modules
{
public interface IUserConfigurable<T>
{
}
} |
using Alabo.Domains.Services;
using Alabo.Tables.Dtos;
namespace Alabo.Tables.Domain.Services {
public interface ISmsService : IService {
SmsEntity Sent(string phone, string content);
}
} |
using BP12;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Combat.StatusEffects.Configurations
{
[System.Serializable]
public struct CorrosionConfig : IStatusConfig
{
[SerializeField]
[AttackType(AttackType.Corrosion)]
private AttackDamage m_damage;
[SerializeField]
[MinValue(0.1f)]
private float m_damageInterval;
[SerializeField]
[MinValue(0.1f)]
private float m_duration;
public CorrosionConfig(int m_damage, float m_intervalDamage, float m_duration)
{
this.m_damage = new AttackDamage(AttackType.Corrosion, m_damage);
this.m_damageInterval = m_intervalDamage;
this.m_duration = m_duration;
}
public AttackDamage damage => m_damage;
public float damageInterval => m_damageInterval;
public float duration => m_duration;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace task5_Short_Words_Sorted
{
class Program
{
static void Main()
{
var separator = new []{ '.', ',', ':', ';', '(', ')', '[', ']', '\"', '\'', '\\', '/', '!', '?', ' ' };
var input = Console.ReadLine().ToLower().Split(separator, StringSplitOptions.RemoveEmptyEntries).ToList();
var result = input
.Where(n => n.Length<5)
.OrderBy(n => n)
.Distinct()
.ToList();
Console.WriteLine(string.Join(", ", result));
}
}
}
|
using System;
using System.Collections.Generic;
using WebShop.API.Models;
using WebShop.Contracts.v1.Requests;
using WebShop.Data.Models;
using WebShop.Data.Models.Dto;
using WebShop.Data.Repository.Contract;
using WebShop.Service.v1;
namespace WebShop.Core.Service
{
public class ServiceV1 : IServiceV1
{
private readonly IUnitOfWork _unitOfWork;
public ServiceV1(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public OrderDto CreateOrder(RequestOrderDto requestOrder)
{
ValidateOrderInput(requestOrder);
var order = BuildOrder(requestOrder);
var response = _unitOfWork.Order.CreateOrderAsync(order);
var result = ConvertOrder(response.Result);
return result;
}
public OrderDto GetOrder(int id, string userId)
{
var order = _unitOfWork.Order.GetOrderByIdAsync(id);
if (order == null)
throw new Exception("Bad request. Order not found");
if (order.UserId != userId)
throw new Exception("Unauthorized");
var result = ConvertOrder(order);
return result;
}
public IEnumerable<OrderDto> GetAllOrders(string userId)
{
var lista = _unitOfWork.Order.GetOrdersByUserIdAsync(userId).Result;
var orders = new List<OrderDto>();
if (lista == null)
throw new Exception("No orders found");
foreach(var o in lista)
{
orders.Add(ConvertOrder(o));
}
return orders;
}
public IEnumerable<ProductDto> GetProductsInCategory(int categoryId)
{
var products = _unitOfWork.Product.GetAllinCategoryAsync(categoryId).Result;
var _products = ConvertProducts(products);
return _products;
}
#region Private Methods
private ORDER BuildOrder(RequestOrderDto order)
{
var NewOrderStatus = _unitOfWork.Order.GetOrderStatus("New").Result;
var result = new ORDER
{
OrderInfo = order.OrderInfo,
OrderRecords = new List<ORDERRECORD>(),
UserId = order.UserId,
OrderStatus = NewOrderStatus,
};
foreach (var item in order.Items)
{
var product = _unitOfWork.Product.GetAsync(item).Result;
if (product == null)
throw new Exception($"Product {item} not found");
result.OrderRecords.Add(
new ORDERRECORD
{
ItemName = product.NAME,
Price = product.EXTRA_PRICE_ACTIVE ? product.EXTRA_PRICE : product.PRICE,
ProductId = product.ID
});
};
return result;
}
private void ValidateOrderInput(RequestOrderDto order)
{
if (order == null)
throw new Exception("Bad input");
if (order.Items == null)
throw new Exception("Empty order");
if (order.Items.Count < 1)
throw new Exception("Empty order");
if (String.IsNullOrEmpty(order.OrderInfo) || order.OrderInfo.Length < 4)
throw new Exception("Order info not set.");
}
#endregion
#region Private Static Converters
private static IEnumerable<ProductDto> ConvertProducts(IEnumerable<PRODUCT> products)
{
var result = new List<ProductDto>();
foreach (var p in products)
{
result.Add(new ProductDto
{
Category_id = p.PARENT_CATEGORY_ID,
Description = p.DESCRIPTION,
ExtraPrice = p.EXTRA_PRICE,
ExtraPriceActive = p.EXTRA_PRICE_ACTIVE,
Id = p.ID,
Name = p.NAME,
Price = p.PRICE,
Avalible = p.AmountInStock,
});
}
return result;
}
private static OrderDto ConvertOrder(ORDER order)
{
var result = new OrderDto
{
OrderInfo = order.OrderInfo,
OrderId = order.OrderId,
Items = new List<Dto.OrderRecordDto>(),
Status = order.OrderStatus.OrderStatusText
};
foreach (var r in order.OrderRecords)
{
result.Items.Add(new Dto.OrderRecordDto
{
ItemName = r.ItemName,
OrderItemSequence = r.OrderItemSequence,
Price = r.Price,
ProductId = r.ProductId
});
}
return result;
}
#endregion
}
}
|
using System;
using Atc.Math.Geometry;
using Xunit;
// ReSharper disable JoinDeclarationAndInitializer
namespace Atc.Tests.Math.Geometry
{
public class TriangleHelperTests
{
[Fact]
public void IsSumOfTheAnglesATriangle()
{
Assert.False(TriangleHelper.IsSumOfTheAnglesATriangle(45, 45, 91), "A:45, B:45, C:91");
Assert.True(TriangleHelper.IsSumOfTheAnglesATriangle(45, 45, 90), "A:45, B:45, C:90");
}
[Fact]
public void IsSumOfTheAnglesATriangleWithNulls()
{
double? angleA = null;
double? angleB = 45;
double? angleC = 90;
Assert.Throws<ArgumentNullException>(() => TriangleHelper.IsSumOfTheAnglesATriangle(angleA, angleB, angleC));
angleA = 20;
Assert.False(TriangleHelper.IsSumOfTheAnglesATriangle(angleA, angleB, angleC), $"A:{angleA}, B:{angleB}, C:{angleC}");
angleA = 45;
Assert.True(TriangleHelper.IsSumOfTheAnglesATriangle(angleA, angleB, angleC), $"A:{angleA}, B:{angleB}, C:{angleC}");
}
[Fact]
public void Pythagorean()
{
double? sideA = 10;
double? sideB = 20;
double? sideC;
double? expected = 22.360679774997898;
Assert.Equal(expected, TriangleHelper.Pythagorean(sideA, sideB, null));
sideA = 15;
sideC = 25;
expected = 20;
Assert.Equal(expected, TriangleHelper.Pythagorean(sideA, null, sideC));
sideB = 5;
sideC = 25;
expected = 24.494897427831781;
Assert.Equal(expected, TriangleHelper.Pythagorean(null, sideB, sideC));
}
}
} |
//Both music files loop continuously
//SFX is labeled generically, and can be mixed/matched how you see fit. You don't even have to use all of it!
//Bonks are for things hitting a wall (player and objects)
//ObjectPush and PlayerWalk both loop, so as long as an object is moving/player is walking the sound can play
//PlayerGrab_Release is the sound for when the character grabs AND releases an object
//UI_Hover is for when the mouse hovers over a button
//This is all I can do for now. There is a chance that I can get home early from work but I misread the times and so most likely this will be it for sound on my end. SOrry that I didn't get to a happy version of the song! |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using HarmonyLib;
using Verse;
using RimWorld;
namespace D9Framework
{
/// <summary>
/// Allows modders to use the <see cref="D9Framework.UseNegativeFertility"/> <c>DefModExtension</c> to create plants which grow faster in poorer soil.
/// </summary>
/// <remarks>
/// Generally mod-compatible and performant because of how it caches <c>MaxNaturalFertility</c>, but probably contributes to longer start-up times.
/// </remarks>
[StaticConstructorOnStartup]
[ClassWithPatches("Negative Fertility Patch", "ApplyNegativeFertilityPatch", "D9FSettingsApplyNFP")]
static class NegativeFertilityPatch
{
public static float MaxNaturalFertility;
/// <summary>
/// Caches <c>MaxNaturalFertility</c> on startup by getting the most fertile natural terrain.
/// </summary>
/// <remarks>
/// Where "natural" is defined as "generated by a <c>BiomeDef</c>".
/// </remarks>
static NegativeFertilityPatch()
{
HashSet<TerrainDef> allPossibleNaturalTerrains = new HashSet<TerrainDef>();
foreach (BiomeDef bd in DefDatabase<BiomeDef>.AllDefsListForReading)
{
foreach (TerrainThreshold tt in bd.terrainsByFertility) allPossibleNaturalTerrains.Add(tt.terrain);
foreach (TerrainPatchMaker tpm in bd.terrainPatchMakers)
foreach (TerrainThreshold tt in tpm.thresholds) allPossibleNaturalTerrains.Add(tt.terrain);
}
IEnumerable<TerrainDef> terrainsByFertility = (from td in DefDatabase<TerrainDef>.AllDefsListForReading
where allPossibleNaturalTerrains.Contains(td)
orderby td.fertility descending
select td);
if (terrainsByFertility.EnumerableNullOrEmpty())
{
ULog.Error("Negative Fertility Patch: terrainsByFertility was empty. Setting EffectiveMaxFertility to 1.");
MaxNaturalFertility = 1f;
}
else
{
MaxNaturalFertility = terrainsByFertility.First().fertility;
}
}
[HarmonyPatch(typeof(Plant), nameof(Plant.GrowthRateFactor_Fertility), MethodType.Getter)]
class NegativeFertilityPostfix
{
[HarmonyPostfix]
public static void GrowthRateFactor_FertilityPostfix(ref float __result, ref Plant __instance)
{
UseNegativeFertility me;
if ((me = __instance.def.GetModExtension<UseNegativeFertility>()) != null)
{
__result = Mathf.Clamp((MaxNaturalFertility - __instance.Map.fertilityGrid.FertilityAt(__instance.Position)) * __instance.def.plant.fertilitySensitivity + (1f - __instance.def.plant.fertilitySensitivity),
me.minFertility,
me.maxFertility);
}
}
}
}
/// <summary>
/// <c>DefModExtension</c> which flags the parent plant <c>ThingDef</c> as using negative fertility. Specifies minimum and maximum fertility values within which the final fertility is clamped.
/// </summary>
/// <remarks>
/// See <see cref="D9Framework.NegativeFertilityPatch"/> for implementation details.
/// </remarks>
public class UseNegativeFertility : DefModExtension
{
public float minFertility = 0.05f, maxFertility = 1.4f;
}
} |
using System;
using System.Collections.Generic;
using Aquamonix.Mobile.Lib.Utilities;
namespace Aquamonix.Mobile.Lib.Environment
{
/// <summary>
/// Some server urls can be 'named' rather than specified by actual url. This class is a utility for translating between
/// urls and their aliases.
/// </summary>
public static class ServerAliases
{
private static List<AliasSpec> _aliases = new List<AliasSpec>();
static ServerAliases()
{
//TODO: get these from config file, not hard-code
_aliases.Add(new AliasSpec("EngServer", "wss://raincloud.aquamonix.com.au:60000/service"));
_aliases.Add(new AliasSpec("DevServer", "wss://raincloud.aquamonix.com.au:60001/service"));
_aliases.Add(new AliasSpec("RainCloud_demo2", "ws://mce-appdemo.dyndns.info:60444/service"));
_aliases.Add(new AliasSpec("RainCloud_demo", "ws://172.16.2.12:60444/service"));
_aliases.Add(new AliasSpec("RainCloud", "wss://raincloud.aquamonix.com.au:444/service"));
_aliases.Add(new AliasSpec("Dev Server", "ws://mce-appdemo.dyndns.info:40003/service"));
_aliases.Add(new AliasSpec("Upton", "wss://raincloud.aquamonix.com.au:60446/service"));
_aliases.Add(new AliasSpec("PivotPro", "wss://raincloud.aquamonix.com.au:60447/service"));
//local nodejs mock server (for testing)
_aliases.Add(new AliasSpec("LocalMock", "ws://192.168.1.40:8086"));
}
/// <summary>
/// Converts an alias to a url.
/// </summary>
/// <param name="alias">The case-insensitive alias</param>
/// <returns>A url or, if none is found, the given string.</returns>
public static string AliasToUri(string alias)
{
return ExceptionUtility.Try<string>(() =>
{
if (String.IsNullOrEmpty(alias))
alias = String.Empty;
alias = alias.Trim().RemoveWhitespace().ToLower();
foreach (var a in _aliases)
{
if (a.Alias == alias)
return a.Uri;
}
return alias;
});
}
/// <summary>
/// Converts a url to its alias.
/// </summary>
/// <param name="uri">The url to convert.</param>
/// <returns>The corresponding alias, or the original url if none found.</returns>
public static string UriToAlias(string uri)
{
return ExceptionUtility.Try<string>(() =>
{
if (String.IsNullOrEmpty(uri))
uri = String.Empty;
uri = uri.Trim().ToLower();
foreach (var a in _aliases)
{
if (a.Uri == uri)
return a.DisplayAlias;
}
return uri;
});
}
private class AliasSpec
{
public string Uri { get; set;}
public string Alias { get; set;}
public string DisplayAlias { get; private set; }
public AliasSpec(string displayAlias, string uri)
{
this.Uri = uri;
this.DisplayAlias = displayAlias;
this.Alias = displayAlias.RemoveWhitespace().Trim().ToLower();
}
}
}
}
|
using System;
using System.Web.Script.Serialization;
namespace LeadChina.CCDMonitor.Infrastrue
{
public static class Commoncs
{
public static double GetTimestamp(DateTime d)
{
TimeSpan ts = d.ToUniversalTime() - new DateTime(1970, 1, 1);
return ts.TotalMilliseconds; // 精确到毫秒
}
public static string SerializeJson<T>(T entity)
{
JavaScriptSerializer js = new JavaScriptSerializer();
js.MaxJsonLength = int.MaxValue;
return js.Serialize(entity);
}
public static T DeserializeJson<T>(string json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Deserialize<T>(json);
}
}
public enum SourceTypeEnum
{
Vedio = 1,
Picture = 2
}
public enum RowStatusEnum
{
Ready = 2,
Enable = 1,
Disable = 0
}
}
|
using System;
namespace minAvgTwoSlice
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine(solution(new int[] {4, 2, 2, 5, 1, 5, 8}));
}
public static int solution(int[] A)
{
if(A.Length == 2)
{
return 0;
}
//could get average of whole array
//then could check average of left / right
//recurisvely do this until you find the smallest?, but no garuntee it would be an exact slice
//realization
//all sums could be assmebled with a combination of 2 slices or 2 and 3 slices, so just find the minimum of that
//intialize first cases
int minTwoSlice = A[0] + A[1];
int minTwoIdx = 0;
int minThreeSlice = int.MaxValue;
int minThreeIdx = 0;
//iterate and find smallest of the 2 and 3 slices
for(int i = 2; i< A.Length; i++)
{
int twoSlice = A[i - 1] + A[i];
if(twoSlice < minTwoSlice)
{
minTwoSlice = twoSlice;
minTwoIdx = i-1;
}
int threeSlice = twoSlice + A[i-2];
if(threeSlice < minThreeSlice)
{
minThreeSlice = threeSlice;
minThreeIdx = i - 2;
}
}
double averageTwo = (double)minTwoSlice/2;
double averageThree = (double)minThreeSlice/3;
//same average, return earlier idx
if(averageTwo == averageThree)
{
return Math.Min(minTwoIdx, minThreeIdx);
}
//otherwise return the smaller of the two averages
else
{
return averageTwo < averageThree ? minTwoIdx : minThreeIdx;
}
}
}
}
|
using UnityEngine;
public class cameraFollow : MonoBehaviour {
GameObject Push;
GameObject Pull;
public float targetSize;
public bool follow = true;
LineRenderer lr;
public float yClamp;
public Vector2 camOffset = Vector2.zero;
bool showLine;
// Use this for initialization
void Start () {
Push = GameObject.Find("Push");
Pull = GameObject.Find("Pull");
lr = GetComponent<LineRenderer>();
if(follow){
transform.position = new Vector3((Push.transform.position.x+Pull.transform.position.x)/2 + camOffset.x,(Push.transform.position.y+Pull.transform.position.y)/2 + camOffset.y,-10);
}
Time.timeScale = 1;
}
// Update is called once per frame
void Update () {
if(follow){
if (gameManager.Instance != null && gameManager.Instance.singlePlayer) {
if (gameManager.Instance.activePlayer == gameManager.ActivePlayer.push) {
transform.position = Vector3.Lerp(transform.position, new Vector3(Push.transform.position.x + camOffset.x, Push.transform.position.y + camOffset.y, -10), Time.deltaTime);
} else if (gameManager.Instance.activePlayer == gameManager.ActivePlayer.pull) {
transform.position = Vector3.Lerp(transform.position, new Vector3(Pull.transform.position.x + camOffset.x, Pull.transform.position.y + camOffset.y, -10), Time.deltaTime);
}
} else {
transform.position = Vector3.Lerp(transform.position, new Vector3((Push.transform.position.x + Pull.transform.position.x) / 2 + camOffset.x, (Push.transform.position.y + Pull.transform.position.y) / 2 + camOffset.y, -10), Time.deltaTime);
}
}
if(showLine){
lr.SetPosition(0,Push.transform.position);
lr.SetPosition(1,Pull.transform.position+(Pull.transform.position-Push.transform.position).normalized);
}
if(Input.GetKeyDown(KeyCode.JoystickButton2)||Input.GetKeyDown(KeyCode.Space)){
ToggleLine(true);
}
if(Input.GetKeyUp(KeyCode.JoystickButton2)||Input.GetKeyUp(KeyCode.Space)){
ToggleLine(false);
}
transform.position = new Vector3(transform.position.x,Mathf.Clamp(transform.position.y,yClamp,100),-10);
}
void ToggleLine(bool On){
GetComponent<LineRenderer>().enabled = On;
showLine = On;
}
} |
using UnityEngine;
namespace DChild.Inputs
{
[System.Serializable]
public struct SkillInput
{
private const string INPUT_DASH = "Dash";
private const string INPUT_GLIDE = "Glide";
private bool m_isDashPressed;
private bool m_isGlideHeld;
public bool isDashPressed => m_isDashPressed;
public bool isGlideHeld => m_isGlideHeld;
public void Disable()
{
m_isDashPressed = false;
m_isGlideHeld = false;
}
public void Update()
{
m_isDashPressed = Input.GetButtonDown(INPUT_DASH);
m_isGlideHeld = Input.GetButton(INPUT_GLIDE);
}
}
}
|
using lsc.Model.Enume;
using System;
using System.Collections.Generic;
using System.Text;
namespace lsc.Model
{
/// <summary>
/// 销售项目
/// </summary>
[Serializable]
public class SalesProject
{
public int ID { get; set; }
/// <summary>
/// 项目标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 客户ID
/// </summary>
public int EnterCustomerID { get; set; }
/// <summary>
/// 录入人员ID
/// </summary>
public int CreateUserID { get; set; }
/// <summary>
/// 录入时间
/// </summary>
public DateTime CreateTime { get; set; }
/// <summary>
/// 项目概要
/// </summary>
public string ProjectAbstract { get; set; }
/// <summary>
/// 项目状态
/// </summary>
public ProjectStateEnum ProjectState { get; set; }
/// <summary>
/// 项目类型
/// </summary>
public ProjectTypeEnum ProjectType { get; set; }
/// <summary>
/// 项目负责人ID
/// </summary>
public int HeadID { get; set; }
/// <summary>
/// 立项时间
/// </summary>
public DateTime ProjectTime { get; set; }
/// <summary>
/// 项目金额
/// </summary>
public double ProjectAmt { get; set; }
/// <summary>
/// 回款金额
/// </summary>
public double ReceoverPay { get; set; }
/// <summary>
/// 预计到款时间
/// </summary>
public DateTime ReceoverPayTime { get; set; }
}
}
|
namespace EFCrudDEMO.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Calls",
c => new
{
CallID = c.Int(nullable: false, identity: true),
MobileNumber = c.String(maxLength: 20),
})
.PrimaryKey(t => t.CallID);
}
public override void Down()
{
DropTable("dbo.Calls");
}
}
}
|
using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;
// using UnityEngine.UI;
public class TransparentWindow : MonoBehaviour
{
public bool debugMode = false;
[SerializeField]
Material _material;
[Header("Textures (Unsupported compression!)")]
[SerializeField]
Texture2D _enableTexture;
[SerializeField]
Texture2D _systemTrayTexture;
Image _enableImage;
Icon _systemTrayIcon;
int _maxWidth = 0, _maxHeight = 0, _xOffset = 0, _yOffset = 0;
Config _config;
ObjPoolManager _pool;
#region Win32
private struct MARGINS
{
public int cxLeftWidth;
public int cxRightWidth;
public int cyTopHeight;
public int cyBottomHeight;
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[DllImport("user32.dll", EntryPoint = "GetWindowLong")]
public static extern long GetWindowLong(IntPtr hwnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong);
[DllImport("Dwmapi.dll")]
private static extern uint DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS margins);
/// <summary>
/// uFlags = 1:忽略大小;2:忽略位置;4:忽略Z顺序
/// </summary>
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
private static extern int SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int cx, int cy, int uFlags);
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetClassName(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumThreadWindows(uint dwThreadId, EnumWindowsProc lpEnumFunc, IntPtr lParam);
const string UnityWindowClassName = "UnityWndClass";
const int GWL_STYLE = -16;
const int GWL_EXSTYLE = -20;
const uint WS_POPUP = 0x80000000;
const uint WS_VISIBLE = 0x10000000;
const uint WS_EX_LAYERED = 0x00080000;
const uint WS_EX_TRANSPARENT = 0x00000020;
const uint WS_EX_TOOLWINDOW = 0x00000080;//隐藏图标
IntPtr HWND_BOTTOM = new IntPtr(1);
IntPtr HWND_TOP = new IntPtr(0);
IntPtr HWND_TOPMOST = new IntPtr(-1);
IntPtr HWND_NOTOPMOST = new IntPtr(-2);
IntPtr _windowHandle = IntPtr.Zero;
public IntPtr windowHandle
{
get
{
if (_windowHandle == IntPtr.Zero)
{
uint threadId = GetCurrentThreadId();
EnumThreadWindows(threadId, (hWnd, lParam) =>
{
var classText = new System.Text.StringBuilder(UnityWindowClassName.Length + 1);
GetClassName(hWnd, classText, classText.Capacity);
if (classText.ToString() == UnityWindowClassName)
{
_windowHandle = hWnd;
return false;
}
return true;
}, IntPtr.Zero);
}
return _windowHandle;
}
}
#endregion
void Start()
{
_config = FindObjectOfType<Config>();
_pool = FindObjectOfType<ObjPoolManager>();
GetSystemInfo();
if (!Application.isEditor)
{
Application.targetFrameRate = 60;
LoadIconFile(Application.persistentDataPath);
SetWindowStyle();
AddSystemTray();
StartCoroutine("AutoUpdate");
}
InitRole();
}
void GetSystemInfo()
{
// 获取多屏幕的总宽度和最高高度,以及任务栏offset
foreach (var screen in System.Windows.Forms.Screen.AllScreens)
{
_maxWidth += screen.Bounds.Width;
if (screen.Bounds.Height > _maxHeight)
{
_maxHeight = screen.Bounds.Height;
}
if (screen.Primary)
{
_xOffset = screen.WorkingArea.X;
_yOffset = screen.WorkingArea.Y;
}
}
if (_maxWidth == 0 || _maxHeight == 0)
Debug.LogError("获取分辨率失败");
}
void SetWindowStyle()
{
SetWindowFullScreen();
Invoke("SetWindowMinAABB", 8);
if (!debugMode)
{
// Set properties of the window
// See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591%28v=vs.85%29.aspx
SetWindowLong(windowHandle, GWL_STYLE, WS_POPUP | WS_VISIBLE);
SetWindowLong(windowHandle, GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT); // 实现鼠标穿透
MARGINS margins = new MARGINS() { cxLeftWidth = -1 };
// Extend the window into the client area
//See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa969512%28v=vs.85%29.aspx
DwmExtendFrameIntoClientArea(windowHandle, ref margins);
}
if (DataModel.Instance.Data.isTopMost)
{
SetWindowPos(windowHandle, HWND_NOTOPMOST, 0, 0, 0, 0, 1 | 2);
SetWindowPos(windowHandle, HWND_TOPMOST, 0, 0, 0, 0, 1 | 2);
}
}
void InitRole()
{
// 实例化已启用的role
foreach (var item in DataModel.Instance.Data.roles)
{
if (item.enable)
_pool.AddRole(InstantiateRole(item.index), item.index);
}
}
GameObject InstantiateRole(int roleIndex)
{
var data = DataModel.Instance.Data.roles[roleIndex];
var go = GameObject.Instantiate(_config.roles[(int)roleIndex], data.rootPos, Quaternion.identity);
var role = go.transform.GetComponentInChildren<RoleCtrlBase>();
Debug.Assert(role != null, $"Role:{go.name} is missing {typeof(RoleCtrlBase)}");
role.transform.position = data.rolePos;
role.transform.rotation = data.roleRot;
return go;
}
// 获取从Windows桌面空间转换到Unity屏幕空间的鼠标位置
public Vector2Int GetMousePosW2U()
{
if (Application.isEditor)
return new Vector2Int((int)Input.mousePosition.x, (int)Input.mousePosition.y);
RECT rect = new RECT();
GetWindowRect(windowHandle, ref rect);
Vector2Int leftBottom = new Vector2Int(rect.Left, rect.Bottom);
var mousePos = new Vector2Int(System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y);
leftBottom.y = _maxHeight - leftBottom.y;
mousePos.y = _maxHeight - mousePos.y;
return mousePos - leftBottom;
}
public void SetMousePenetrate(bool isPenetrate)
{
var s = GetWindowLong(windowHandle, GWL_EXSTYLE);
if (isPenetrate)
{
SetWindowLong(windowHandle, GWL_EXSTYLE, (uint)(s | WS_EX_TRANSPARENT));
}
else
{
SetWindowLong(windowHandle, GWL_EXSTYLE, (uint)(s & ~WS_EX_TRANSPARENT));
}
}
public void SetBottom(bool isBottom)
{
if (isBottom)
{
SetWindowPos(windowHandle, HWND_NOTOPMOST, 0, 0, 0, 0, 1 | 2);
SetWindowPos(windowHandle, HWND_BOTTOM, 0, 0, 0, 0, 1 | 2);
}
else
{
SetWindowPos(windowHandle, HWND_NOTOPMOST, 0, 0, 0, 0, 1 | 2);
if (DataModel.Instance.Data.isTopMost)
{
SetWindowPos(windowHandle, HWND_TOPMOST, 0, 0, 0, 0, 1 | 2);
}
else
{
SetWindowPos(windowHandle, HWND_TOP, 0, 0, 0, 0, 1 | 2);
}
}
}
public void SetWindowFullScreen()
{
SetWindowPos(windowHandle, IntPtr.Zero, _xOffset, _yOffset, _maxWidth, _maxHeight, 4);
}
public void SetWindowMinAABB()
{
var cam = Camera.main;
var bound = _pool.GetMinAABB();
Vector3 min = cam.WorldToScreenPoint(bound.min),// windows max
max = cam.WorldToScreenPoint(bound.max);// windows min
max.y = _maxHeight - max.y;
min.y = _maxHeight - min.y;
var trueMin = Vector3.Max(max, Vector3.zero);
var trueMax = Vector3.Max(min, Vector3.one);
var wh = trueMax - trueMin;
float widthScale = wh.x / wh.y / cam.aspect;
var fov = cam.fieldOfView;
cam.fieldOfView = fov * (wh.y / _maxHeight);
cam.transform.position = new Vector3(
bound.center.x,
bound.center.y,
cam.transform.position.z
);
SetWindowPos(windowHandle, IntPtr.Zero,
_xOffset + (int)trueMin.x,
_yOffset + (int)trueMin.y,
(int)wh.x,
(int)wh.y,
4);
}
#region 托盘
SystemTray _icon;
System.Windows.Forms.ToolStripItem _topmost, _runOnStart;
System.Windows.Forms.ToolStripItem[] _roleItem;
// 创建托盘图标、添加选项
void AddSystemTray()
{
_icon = new SystemTray(_systemTrayIcon);
_topmost = _icon.AddItem("置顶显示", ToggleTopMost);
_runOnStart = _icon.AddItem("开机自启", ToggleRunOnStartup);
_icon.AddItem("重置位置", ResetPos);
_icon.AddSeparator();
AddRoleItem(_icon);
_icon.AddSeparator();
_icon.AddItem("查看文档", OpenDoc);
_icon.AddItem("检查更新", CheckUpdate);
_icon.AddSeparator();
_icon.AddItem("退出", Exit);
_icon.AddDoubleClickEvent(ToggleTopMost);
_icon.AddSingleClickEvent(ShowRole);
_topmost.Image = DataModel.Instance.Data.isTopMost ? _enableImage : null;
_runOnStart.Image = DataModel.Instance.Data.isRunOnStartup ? _enableImage : null;
}
//! 不支持压缩
void LoadIconFile(string basePath)
{
string enableImagePath = basePath + "/Checkmark.png";
string iconPath = basePath + "/Icon.png";
File.WriteAllBytes(enableImagePath, _enableTexture.EncodeToPNG());
_enableImage = Image.FromFile(enableImagePath);
File.WriteAllBytes(iconPath, _systemTrayTexture.EncodeToPNG());
_systemTrayIcon = Icon.FromHandle((new Bitmap(iconPath)).GetHicon());
}
void ToggleTopMost()
{
bool isTop = !DataModel.Instance.Data.isTopMost;
DataModel.Instance.Data.isTopMost = isTop;
DataModel.Instance.SaveData();
if (_pool.IsAnyRoleEnable())
SetWindowPos(windowHandle, isTop ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, 1 | 2);
_topmost.Image = isTop ? _enableImage : null;
}
void ToggleRunOnStartup()
{
bool isRun = !DataModel.Instance.Data.isRunOnStartup;
DataModel.Instance.Data.isRunOnStartup = isRun;
DataModel.Instance.SaveData();
_runOnStart.Image = isRun ? _enableImage : null;
if (isRun)
{
Rainity.AddToStartup();
}
else
{
Rainity.RemoveFromStartup();
}
}
void ToggleRole(int roleIndex)
{
if (_pool.rootPool[roleIndex] == null)
{
_pool.AddRole(InstantiateRole(roleIndex), roleIndex);
}
else
{
_pool.RemoveRole(roleIndex);
}
bool enable = _pool.rootPool[roleIndex] != null;
_roleItem[roleIndex].Image = enable ? _enableImage : null;
DataModel.Instance.Data.roles[roleIndex].enable = enable;
DataModel.Instance.SaveData();
}
void AddRoleItem(SystemTray tray)
{
_roleItem = new System.Windows.Forms.ToolStripItem[_config.roles.Length];
foreach (var item in DataModel.Instance.Data.roles)
{
var i = item.index;
_roleItem[i] = tray.AddItem(((Roles)i).ToString(), () =>
{
ToggleRole(i);
});
_roleItem[i].Image = item.enable ? _enableImage : null;
}
}
void Exit()
{
_icon.Dispose();
Application.Quit();
}
void ResetPos()
{
foreach (var role in _pool.rolePool)
{
if (role == null)
continue;
role.transform.parent.position = Vector3.zero;
role.transform.position = Vector3.zero;
role.transform.rotation = Quaternion.identity;
}
DataModel.Instance.Data.roles = null;
DataModel.Instance.SaveData();
DataModel.Instance.Init();
}
void OpenDoc()
{
Application.OpenURL("https://github.com/Jason-Ma-233/Sakura_DesktopMascot");
}
IEnumerator AutoUpdate()
{
yield return new WaitForSeconds(1);
// 写入版本文件以供py读取
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\" + "Ver.data", Application.version + "\n"
+ Application.productName + ".exe");
// 比较日期,大于一周则调用检查更新
var lateUpdateDate = DateTime.FromFileTime(DataModel.Instance.Data.updateTime);
var now = DateTime.Now;
TimeSpan ts = now - lateUpdateDate;
if (ts.Days >= 7)
{
CheckUpdate();
DataModel.Instance.Data.updateTime = DateTime.Now.ToFileTime();
DataModel.Instance.SaveData();
}
}
void CheckUpdate()
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "\\" + "Update.exe";
p.StartInfo.Arguments = AppDomain.CurrentDomain.BaseDirectory;
p.Start();
}
void ShowRole()
{
if (DataModel.Instance.Data.isTopMost || !_pool.IsAnyRoleEnable())
return;
SetWindowPos(windowHandle, HWND_TOPMOST, 0, 0, 0, 0, 1 | 2);
SetWindowPos(windowHandle, HWND_NOTOPMOST, 0, 0, 0, 0, 1 | 2);
}
#endregion
} |
using gView.Framework.Network.Algorthm;
using gView.Framework.system;
using gView.Framework.UI;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace gView.Framework.Network.Tracers
{
[RegisterPlugInAttribute("63AF7F85-6617-4944-ABED-A98CA2B45CA9")]
class TraceConnected : INetworkTracer, IProgressReporterEvent
{
#region INetworkTracer Member
public string Name
{
get { return "Trace Connected"; }
}
public bool CanTrace(NetworkTracerInputCollection input)
{
if (input == null)
{
return false;
}
return input.Collect(NetworkTracerInputType.SourceNode).Count == 1 ||
input.Collect(NetworkTracerInputType.SoruceEdge).Count == 1;
}
async public Task<NetworkTracerOutputCollection> Trace(INetworkFeatureClass network, NetworkTracerInputCollection input, ICancelTracker cancelTraker)
{
if (network == null || !CanTrace(input))
{
return null;
}
GraphTable gt = new GraphTable(network.GraphTableAdapter());
NetworkSourceInput sourceNode = null;
NetworkSourceEdgeInput sourceEdge = null;
if (input.Collect(NetworkTracerInputType.SourceNode).Count == 1)
{
sourceNode = input.Collect(NetworkTracerInputType.SourceNode)[0] as NetworkSourceInput;
}
else if (input.Collect(NetworkTracerInputType.SoruceEdge).Count == 1)
{
sourceEdge = input.Collect(NetworkTracerInputType.SoruceEdge)[0] as NetworkSourceEdgeInput;
}
else
{
return null;
}
Dijkstra dijkstra = new Dijkstra(cancelTraker);
dijkstra.reportProgress += this.ReportProgress;
dijkstra.ApplySwitchState = input.Contains(NetworkTracerInputType.IgnoreSwitches) == false &&
network.HasDisabledSwitches;
Dijkstra.ApplyInputIds(dijkstra, input);
if (sourceNode != null)
{
dijkstra.Calculate(gt, sourceNode.NodeId);
}
else if (sourceEdge != null)
{
IGraphEdge graphEdge = gt.QueryEdge(sourceEdge.EdgeId);
if (graphEdge == null)
{
return null;
}
bool n1_2_n2 = gt.QueryN1ToN2(graphEdge.N1, graphEdge.N2) != null;
bool n2_2_n1 = gt.QueryN1ToN2(graphEdge.N2, graphEdge.N1) != null;
bool n1switchState = dijkstra.ApplySwitchState ? gt.SwitchState(graphEdge.N1) : true;
bool n2switchState = dijkstra.ApplySwitchState ? gt.SwitchState(graphEdge.N2) : true;
if (n1_2_n2 && n1switchState == true)
{
dijkstra.Calculate(gt, graphEdge.N1);
}
else if (n2_2_n1 && n2switchState == true)
{
dijkstra.Calculate(gt, graphEdge.N2);
}
else
{
return null;
}
}
Dijkstra.Nodes dijkstraNodes = dijkstra.DijkstraNodesWithMaxDistance(double.MaxValue);
if (dijkstraNodes == null)
{
return null;
}
ProgressReport report = (ReportProgress != null ? new ProgressReport() : null);
#region Collect EdgedIds
if (report != null)
{
report.Message = "Collected Edges...";
report.featurePos = 0;
report.featureMax = dijkstraNodes.Count;
ReportProgress(report);
}
NetworkInputForbiddenEdgeIds forbiddenEdgeIds = (input.Contains(NetworkTracerInputType.ForbiddenEdgeIds)) ? input.Collect(NetworkTracerInputType.ForbiddenEdgeIds)[0] as NetworkInputForbiddenEdgeIds : null;
NetworkInputForbiddenStartNodeEdgeIds forbiddenStartNodeEdgeIds = (input.Contains(NetworkTracerInputType.ForbiddenStartNodeEdgeIds)) ? input.Collect(NetworkTracerInputType.ForbiddenStartNodeEdgeIds)[0] as NetworkInputForbiddenStartNodeEdgeIds : null;
int counter = 0;
List<int> edgeIds = new List<int>();
foreach (Dijkstra.Node dijkstraNode in dijkstraNodes)
{
if (dijkstra.ApplySwitchState)
{
if (gt.SwitchState(dijkstraNode.Id) == false) // hier ist Schluss!!
{
continue;
}
}
GraphTableRows gtRows = gt.QueryN1(dijkstraNode.Id);
if (gtRows == null)
{
continue;
}
foreach (IGraphTableRow gtRow in gtRows)
{
int eid = gtRow.EID;
if (sourceNode != null &&
forbiddenStartNodeEdgeIds != null && dijkstraNode.Id == sourceNode.NodeId &&
forbiddenStartNodeEdgeIds.Ids.Contains(eid))
{
continue;
}
if (forbiddenEdgeIds != null && forbiddenEdgeIds.Ids.Contains(eid))
{
continue;
}
int index = edgeIds.BinarySearch(eid);
if (index < 0)
{
edgeIds.Insert(~index, eid);
}
}
counter++;
if (report != null && counter % 1000 == 0)
{
report.featurePos = counter;
ReportProgress(report);
}
}
#endregion
NetworkTracerOutputCollection output = new NetworkTracerOutputCollection();
if (report != null)
{
report.Message = "Add Edges...";
report.featurePos = 0;
report.featureMax = edgeIds.Count;
ReportProgress(report);
}
counter = 0;
NetworkPathOutput pathOutput = new NetworkPathOutput();
foreach (int edgeId in edgeIds)
{
pathOutput.Add(new NetworkEdgeOutput(edgeId));
counter++;
if (report != null && counter % 1000 == 0)
{
report.featurePos = counter;
ReportProgress(report);
}
//var x = network.GetEdgeFeatureAttributes(edgeId, null);
}
output.Add(pathOutput);
if (input.Collect(NetworkTracerInputType.AppendNodeFlags).Count > 0)
{
await Helper.AppendNodeFlags(network, gt, Helper.NodeIds(dijkstraNodes), output);
}
return output;
}
#endregion
#region IProgressReporterEvent Member
public event ProgressReporterEvent ReportProgress = null;
#endregion
}
}
|
namespace Alabo.Domains.Query.Dto {
/// <summary>
/// 将input/output参数命名为MethodNameInput和 MethodNameOutput,
/// 并为每个应用服务方法定义一个单独的input和output DTO。即使你的方法只需要或返回一个参数,
/// 最好也创建一个DTO类。这样,你的代码回更具有扩展性。以后你可以添加更多的属性而不用改变方法的签名
/// ,而且也不用使已存在的客户端应用发生重大变化
/// </summary>
public interface IEntityDto : IEntityDto<long> {
}
public interface IEntityDto<TPrimaryKey> {
/// <summary>
/// Id of the entity.
/// </summary>
//TPrimaryKey Id { get; set; }
}
} |
using gView.Framework.Carto;
using gView.Framework.Data.Cursors;
using gView.Framework.Data.Filters;
using gView.Framework.Geometry;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace gView.Framework.Data
{
public class FeatureCache
{
static private Dictionary<Guid, CachedFeatureCollection> _collections = new Dictionary<Guid, CachedFeatureCollection>();
static private object lockThis = new object();
static public ICachedFeatureCollection CreateCachedFeatureCollection(Guid guid, IQueryFilter filter)
{
return CreateCachedFeatureCollection(guid, filter, -1);
}
static public ICachedFeatureCollection CreateCachedFeatureCollection(Guid guid, IQueryFilter filter, int LifeTime)
{
lock (lockThis)
{
CachedFeatureCollection collection;
if (_collections.TryGetValue(guid, out collection))
{
return null;
}
else
{
collection = new CachedFeatureCollection(guid, filter);
_collections.Add(guid, collection);
return collection;
}
}
}
static internal ICachedFeatureCollection GetCachedFeatureCollection(Guid guid)
{
CachedFeatureCollection collection;
if (_collections.TryGetValue(guid, out collection))
{
return collection;
}
return null;
}
static public void RemoveFeatureCollection(Guid guid)
{
_collections.Remove(guid);
}
static public void RemoveFeatureCollection(ICachedFeatureCollection collection)
{
Guid guid = new Guid();
bool found = false;
foreach (Guid g in _collections.Keys)
{
if (_collections[g] == collection)
{
guid = g;
found = true;
}
}
if (found)
{
RemoveFeatureCollection(guid);
}
}
static public ICachedFeatureCollection GetUsableFeatureCollection(Guid guid, IQueryFilter filter)
{
CachedFeatureCollection collection = GetCachedFeatureCollection(guid) as CachedFeatureCollection;
if (collection == null || !collection.UsableWith(filter))
{
return null;
}
if (collection.Released)
{
return collection;
}
else
{
//
// Wait for release!!! (Hope there is no deadlocking)
//
if (Thread.CurrentThread != collection._myThread)
{
ManualResetEvent resetEvent = new ManualResetEvent(false);
collection._resetEvents.Add(resetEvent);
resetEvent.WaitOne(10000, false);
if (collection.Released)
{
return collection;
}
}
else
{
throw new Exception("Can't use unreleased cached featurecollection\nWaiting thread is identical with work thread!\nDeadlocking situation!");
}
}
return null;
}
static public void ReleaseCachedFeatureCollection(ICachedFeatureCollection cachedFeatureColledion)
{
CachedFeatureCollection collection = cachedFeatureColledion as CachedFeatureCollection;
if (collection != null)
{
collection.Released = true;
}
}
static public bool UseCachingForDataset(Guid datasetGUID)
{
// für WMS/WFS und ArcXML Feature Queries
if (datasetGUID == new Guid("538F0731-31FE-493a-B063-10A2D37D6E6D") ||
datasetGUID == new Guid("3B26682C-BF6E-4fe8-BE80-762260ABA581"))
{
return true;
}
return false;
}
#region Classes
class CachedFeatureCollection : ICachedFeatureCollection
{
private Guid _guid;
private IQueryFilter _filter;
private Dictionary<long, List<IFeature>> _features;
private BinarySearchTree2 _tree = null;
public CachedFeatureCollection(Guid guid, IQueryFilter filter)
{
_guid = guid;
_filter = filter;
_myThread = Thread.CurrentThread;
if (_filter is ISpatialFilter &&
((ISpatialFilter)_filter).Geometry != null)
{
_tree = new BinarySearchTree2(((ISpatialFilter)_filter).Geometry.Envelope,
20, 200, 0.55, null);
}
_features = new Dictionary<long, List<IFeature>>();
_features.Add((long)0, new List<IFeature>());
}
private bool _released = false;
internal List<ManualResetEvent> _resetEvents = new List<ManualResetEvent>();
internal Thread _myThread;
public bool Released
{
get { return _released; }
set
{
_released = true;
foreach (ManualResetEvent resetEvent in _resetEvents)
{
resetEvent.Set();
}
}
}
#region ICachedFeatureCollection Member
public void AddFeature(IFeature feature)
{
if (feature == null)
{
return;
}
long NID = (feature.Shape != null && _tree != null) ?
_tree.InsertSINode(feature.Shape.Envelope) : 0;
if (_tree != null)
{
_tree.AddNodeNumber(NID);
}
List<IFeature> features;
if (!_features.TryGetValue(NID, out features))
{
features = new List<IFeature>();
_features.Add(NID, features);
}
features.Add(feature);
}
public Guid CollectionGUID
{
get { return _guid; }
}
public IQueryFilter QueryFilter
{
get { return _filter.Clone() as IQueryFilter; }
}
public bool UsableWith(IQueryFilter filter)
{
if (_filter == null || filter == null)
{
return false;
}
// Type überprüfen
if (_filter.GetType() != filter.GetType())
{
return false;
}
#region WhereClause
if (_filter.WhereClause != filter.WhereClause)
{
return false;
}
#endregion
#region Subfields
if (_filter.SubFields != "*")
{
if (filter.SubFields == "*")
{
return false;
}
string[] subFields_o = _filter.SubFields.Split(' ');
string[] subFields_n = filter.SubFields.Split(' ');
foreach (string fn in subFields_n)
{
string shortNameN = Field.shortName(fn);
bool found = false;
foreach (string fo in subFields_o)
{
if (Field.shortName(fo) == shortNameN)
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
}
#endregion
#region Geometry Envelope
if (_filter is ISpatialFilter && filter is ISpatialFilter)
{
IGeometry geomN = ((ISpatialFilter)filter).Geometry;
IGeometry geomO = ((ISpatialFilter)_filter).Geometry;
if (geomN == null || geomO == null)
{
return false;
}
if (((ISpatialFilter)_filter).SpatialRelation == spatialRelation.SpatialRelationMapEnvelopeIntersects &&
((ISpatialFilter)filter).SpatialRelation == spatialRelation.SpatialRelationMapEnvelopeIntersects)
{
return geomO.Envelope.Contains(geomN.Envelope);
}
else
{
return SpatialAlgorithms.Algorithm.Contains(geomO, geomN);
}
}
#endregion
return true;
}
public IFeatureCursor FeatureCursor()
{
return new CachedFeatureCursor(GetFeatures(), null);
}
public IFeatureCursor FeatureCursor(IQueryFilter filter)
{
return new CachedFeatureCursor(GetFeatures(filter), filter);
}
#endregion
private List<IFeature> GetFeatures()
{
List<IFeature> features = new List<IFeature>();
foreach (long nid in _features.Keys)
{
features.AddRange(_features[nid]);
}
return features;
}
private List<IFeature> GetFeatures(IQueryFilter filter)
{
if (_tree != null)
{
List<IFeature> features = new List<IFeature>();
if (filter is ISpatialFilter &&
((ISpatialFilter)filter).Geometry != null)
{
List<long> nids = _tree.CollectNIDs(((ISpatialFilter)filter).Geometry.Envelope);
foreach (long nid in nids)
{
features.AddRange(_features[nid]);
}
}
else
{
GetFeatures();
}
return features;
}
else
{
return _features[(long)0];
}
}
}
class CachedFeatureCursor : IFeatureCursor
{
private List<IFeature> _features;
private int _pos = 0;
private IQueryFilter _filter;
public CachedFeatureCursor(List<IFeature> features, IQueryFilter filter)
{
_features = features;
_filter = filter;
}
#region IFeatureCursor Member
public Task<IFeature> NextFeature()
{
while (true)
{
if (_features == null || _features.Count <= _pos)
{
return null;
}
IFeature feature = _features[_pos++];
if (feature == null)
{
return null;
}
if (_filter is ISpatialFilter)
{
if (!gView.Framework.Geometry.SpatialRelation.Check(_filter as ISpatialFilter, feature.Shape))
{
continue;
}
}
return Task.FromResult<IFeature>(feature);
}
}
#endregion
#region IDisposable Member
public void Dispose()
{
}
#endregion
}
#endregion
}
public abstract class CacheableFeatureClass : ISelectionCache
{
private Guid _selectionGUID = Guid.NewGuid();
private Guid _mapEnvelopeGUID = Guid.NewGuid();
private Guid _getFeatureGUID = Guid.NewGuid();
async private Task<IFeatureCursor> GetFeatures(Guid guid, IQueryFilter filter)
{
ICachedFeatureCollection collection = FeatureCache.GetUsableFeatureCollection(guid, filter);
if (collection != null)
{
return collection.FeatureCursor(filter);
}
else
{
FeatureCache.RemoveFeatureCollection(guid);
collection = FeatureCache.CreateCachedFeatureCollection(guid, filter);
return new CachingFeatureCursor(collection, await this.FeatureCursor(filter));
}
}
#region FeatureClass Members
async virtual public Task<IFeatureCursor> GetFeatures(IQueryFilter filter)
{
if (filter is ISpatialFilter &&
((ISpatialFilter)filter).SpatialRelation == spatialRelation.SpatialRelationMapEnvelopeIntersects)
{
return await GetFeatures(_mapEnvelopeGUID, filter);
}
else
{
return await GetFeatures(_getFeatureGUID, filter);
}
}
async virtual public Task<ICursor> Search(IQueryFilter filter)
{
return await GetFeatures(_getFeatureGUID, filter);
}
virtual public IFieldCollection Fields
{
get
{
return new FieldCollection();
}
}
async virtual public Task<ISelectionSet> Select(IQueryFilter filter)
{
FeatureCache.RemoveFeatureCollection(_selectionGUID);
if (this.IDFieldName != String.Empty && this.FindField(this.IDFieldName) != null)
{
filter.SubFields = this.IDFieldName;
filter.AddField(this.ShapeFieldName);
filter.AddField(this.IDFieldName);
using (IFeatureCursor cursor = await this.GetFeatures(_selectionGUID, filter))
{
if (cursor != null)
{
IFeature feat;
IDSelectionSet selSet = new IDSelectionSet();
while ((feat = await cursor.NextFeature()) != null)
{
selSet.AddID(feat.OID);
}
return selSet;
}
}
}
else
{
int count = 0;
using (IFeatureCursor cursor = await this.GetFeatures(_selectionGUID, filter))
{
if (cursor == null)
{
return null;
}
IFeature feature;
while ((feature = await cursor.NextFeature()) != null)
{
count++;
}
}
return new QueryFilteredSelectionSet(filter, count);
}
return null;
}
public abstract string IDFieldName { get; }
public abstract string ShapeFieldName { get; }
public abstract IField FindField(string fieldname);
#endregion
protected abstract Task<IFeatureCursor> FeatureCursor(IQueryFilter filter);
#region ISelectionCache Member
public IFeatureCursor GetSelectedFeatures()
{
return GetSelectedFeatures(null);
}
public IFeatureCursor GetSelectedFeatures(IDisplay display)
{
ICachedFeatureCollection collection = FeatureCache.GetCachedFeatureCollection(this._selectionGUID);
if (collection == null)
{
return null;
}
if (display != null)
{
SpatialFilter filter = new SpatialFilter();
filter.SpatialRelation = spatialRelation.SpatialRelationMapEnvelopeIntersects;
filter.Geometry = display.Envelope;
filter.FilterSpatialReference = display.SpatialReference;
return collection.FeatureCursor(filter);
}
else
{
return collection.FeatureCursor();
}
}
#endregion
}
internal class CachingFeatureCursor : IFeatureCursor
{
private IFeatureCursor _cursor = null;
private ICachedFeatureCollection _cfCollection = null;
private bool _released = false;
public CachingFeatureCursor(ICachedFeatureCollection cfCollection, IFeatureCursor cursor)
{
_cursor = cursor;
_cfCollection = cfCollection;
}
#region IFeatureCursor Member
async public Task<IFeature> NextFeature()
{
if (_cursor == null)
{
return null;
}
IFeature feature = await _cursor.NextFeature();
if (_cfCollection != null)
{
if (feature != null)
{
_cfCollection.AddFeature(feature);
}
else
{
FeatureCache.ReleaseCachedFeatureCollection(_cfCollection);
_released = true;
}
}
return feature;
}
#endregion
#region IDisposable Member
public void Dispose()
{
if (_cursor != null)
{
_cursor.Dispose();
_cursor = null;
if (!_released)
{
FeatureCache.RemoveFeatureCollection(_cfCollection);
}
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using UI.Entidades;
using UI.Models;
namespace UI.Controllers
{
public class GestionParticipanteController : ApiController
{
[HttpPost]
public Response<List<Participante>> ListaParticipantes()
{
Response<List<Participante>> obj = new Response<List<Participante>>();
Participantes lis = new Participantes();
return obj = lis.ListaParticipantes();
}
[HttpPost]
public Response<Participante> ListarParticipante([FromBody] Participante pa)
{
Response<Participante> obj = new Response<Participante>();
Participantes li = new Participantes();
return obj = li.ListarParticipante(pa.id);
}
[HttpPost]
public Response<Participante> GuardarParticipante([FromBody] Participante pa)
{
Response<Participante> obj = new Response<Participante>();
Participantes tra = new Participantes();
if (pa.operacion == "Nuevo")
{
return obj = tra.RegistrarParticipante(pa);
}
else
{
return obj = tra.ActualizarParticipante(pa);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
namespace Kingdee.CAPP.DAL
{
/// <summary>
/// 类型说明:物料DAL类
/// 作 者:jason.tang
/// 完成时间:2013-03-05
/// </summary>
public class MaterialModuleDAL
{
private static Database db = DatabaseFactory.Instance();
/// <summary>
/// 方法说明:获取物料类型表数据
/// 作 者:jason.tang
/// 完成时间:2013-03-05
/// </summary>
/// <returns>DataSet</returns>
public static DataSet GetMaterialModuleDataset()
{
try
{
string strsql = @"select
[TypeId]
,[TypeName]
from [MAT_CommonType]";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
//db.AddInParameter(cmd, "@ParentNode", DbType.Int32, parentNode);
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据物料类型获取物料分类表数据
/// 作 者:jason.tang
/// 完成时间:2013-03-05
/// </summary>
/// <returns>DataSet</returns>
public static DataSet GetCategoryByCommonType(string commonType)
{
try
{
string strsql = @"select CategoryId,CategoryCode,CategoryName,DisplaySeq from ps_BusinessCategory t1
where DisplaySeq is not null and t1.DeleteFlag =0 and t1.ObjectOption = 1 and t1.CategoryId in
(select t2.CategoryId from ps_BusinessCategoryRelation t2 where t2.CommonType = @CommonType) --CommonType条件为上层的类别
and t1.ParentCategory is null --父类别为Null
Order by t1.CategoryCode,t1.CategoryName";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
db.AddInParameter(cmd, "@CommonType", DbType.String, commonType);
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据物料版本ID查找子物料
/// 作 者:jason.tang
/// 完成时间:2013-03-08
/// </summary>
/// <param name="materialVerId">物料版本ID</param>
/// <returns>DataSet</returns>
public static DataSet GetChildMaterialByVersionId(string materialVerId)
{
try
{
string strsql = @"select t1.MaterialVerId,Code,Name,BaseId
from Mat_MaterialVersion t1 with(nolock)
left join Mat_MaterialRelation t2 with(nolock)
on t1.MaterialVerId = t2.ChildVerId
where ParentVerId = @ParentVerId";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
db.AddInParameter(cmd, "@ParentVerId", DbType.String, materialVerId);
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据物料分类父ID获取物料子分类数据
/// 作 者:jason.tang
/// 完成时间:2013-03-05
/// </summary>
/// <param name="parentCategory">父分类ID</param>
/// <returns>DataSet</returns>
public static DataSet GetCategoryByParentCategory(string parentCategory)
{
try
{
string strsql = @"select CategoryId,CategoryCode,CategoryName,DisplaySeq from ps_BusinessCategory t1
where t1.DeleteFlag =0 and t1.ObjectOption = 1
and t1.ParentCategory = @ParentCategory --父类型的ID
Order by t1.CategoryCode,t1.CategoryName";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
db.AddInParameter(cmd, "@ParentCategory", DbType.String, parentCategory);
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据物料分类ID获取物料数据
/// 作 者:jason.tang
/// 完成时间:2013-03-05
/// </summary>
/// <param name="typeId">分类ID</param>
/// <param name="categoryId">业务类型ID</param>
/// <param name="conditions">其他条件</param>
/// <returns>DataSet</returns>
public static DataSet GetMaterialModuleDataByCategoryId(string typeId, string categoryId, string conditions)
{
try
{
string strsql = @"select objecticonpath,isinflow,intimage,disginstateiconpath,designcycle,qualitystateiconpath,
technicscycle,lastarchive,baseid,technicsstateiconpath,materialverid,code,
name,drawnumber,spec,vercode,intproductmode,
createdate,count,productname,categoryname,categoryid_typeid,
isvirtualdesign,typename,papercount,memberspec,
IsCreateNew,ChangingApply from v_mat_materialversion WHERE ArticleType = 0 and IsEffect = 1
and FactoryId = '' And LanguageId = 0 ";
if (!string.IsNullOrEmpty(conditions))
{
if (!string.IsNullOrEmpty(typeId))
{
strsql += string.Format("and TypeId ='{0}' ", typeId);
}
if (!string.IsNullOrEmpty(categoryId))
{
strsql += string.Format("and CategoryId in (select CategoryId from dbo.f_PS_GetCategoryId('{0}') )", categoryId);
}
strsql += conditions;
}
else
{
string categoryId_typeId = categoryId + typeId;
strsql += string.Format(" and categoryId_typeId = '{0}'", categoryId_typeId);
}
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据物料分类ID获取物料数据
/// 作 者:jason.tang
/// 完成时间:2013-03-05
/// </summary>
/// <param name="categoryId">分类ID</param>
/// <param name="code">物料编码</param>
/// <returns>DataSet</returns>
public static DataSet GetMaterialModuleListByCategoryId(string categoryId, string code)
{
try
{
string strsql = @"select objecticonpath,isinflow,intimage,disginstateiconpath,designcycle,qualitystateiconpath,
technicscycle,lastarchive,baseid,technicsstateiconpath,materialverid,code,
name,drawnumber,spec,vercode,intproductmode,
createdate,count,productname,categoryname,categoryid_typeid,
isvirtualdesign,typename,papercount,memberspec,typeid,
IsCreateNew,ChangingApply from v_mat_materialversion
where IsFrozen = 0
and (IsShow=1 OR (IsEffect=1 AND IsShow=2 AND BaseId NOT IN
(SELECT mm.BaseId FROM MAT_MaterialVersion mm WHERE mm.IsShow=1 ) ))
and DesignCycle in (1,2,3,4) and CategoryId_TypeId = @CategoryId_TypeId
and code = @code
and FactoryId in ('') and ArticleType = 0 And LanguageId = 0";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
db.AddInParameter(cmd, "@CategoryId_TypeId", DbType.String, categoryId);
db.AddInParameter(cmd, "@code", DbType.String, code);
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:获取物料版本数据
/// 作 者:jason.tang
/// 完成时间:2013-03-06
/// </summary>
/// <returns>物料版本结合</returns>
public static DataSet GetMaterialVersionModuleList()
{
try
{
string strsql = @"select MaterialVerId,BaseId,Code,Name,MaterialType,ProductId,ObjectIconPath
from Mat_MaterialVersion with(nolock)";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据PBOM ID获取下层对应的物料数据
/// 作 者:jason.tang
/// 完成时间:2013-08-22
/// </summary>
/// <param name="verId">Ver ID</param>
/// <returns>物料版本数据集</returns>
public static DataSet GetChildPbomMaterialByPbomId(string verId)
{
try
{
string strsql = @"select parent.VerId,a.ChildId,
MaterialVerId,
BaseId,
Code,
Name,
MaterialType,
ProductId,
parent.ObjectIconPath from pp_pbomChild a
inner join pp_pbomVer parent
on a.ParentId=Parent.VerId
left join pp_pbomVer child
on a.ChildId=child.Verid
inner join Mat_materialVersion mat
on a.objectId=mat.BaseId and mat.IsEffect=1
where parent.VerId='{0}' ";
strsql = string.Format(strsql, verId);
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据父版本ID获取物料版本数据
/// 作 者:jason.tang
/// 完成时间:2013-03-06
/// </summary>
/// <param name="versionId">版本ID</param>
/// <returns>物料版本数据集</returns>
public static DataSet GetMaterialVersionModuleListByVersionId(string versionId)
{
try
{
string strsql = @"select ParentVerId,RelationId,ChildVerId,DisplaySeq,IsLock,name
FROM Mat_MaterialRelation t1 with(nolock)
Left join Mat_MaterialVersion t2 on t1.ParentVerId = t2.MaterialVerId
where t1.ParentVerId = @ParentVerId
order by t1.DisplaySeq";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
db.AddInParameter(cmd, "@ParentVerId", DbType.String, versionId);
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据BaseId获取PBOM资料
/// 作 者:jason.tang
/// 完成时间:2013-03-06
/// </summary>
/// <param name="baseId">BaseId</param>
/// <returns>PBOM数据集</returns>
public static DataSet GetPBomModuleListByBaseId(string baseId)
{
try
{
string strsql = @"select a.VerId,a.PbomId,c.MaterialVerId FolderId,c.Name FolderName,
a.Creator,a.CreateDate,
b.ArchivePerson,b.ArchiveDate from pp_pbomVer a
inner join pp_pbom b
on a.PBOMId=b.PBomId and a.Ver=b.CurrentVer
inner join PP_Folder f
on f.FolderId=b.FolderId
inner join mat_materialversion c
on b.ObjectId=c.BaseId and c.IsEffect=1
where c.BaseId in ({0})";
strsql = string.Format(strsql, baseId);
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
//db.AddInParameter(cmd, "@ObjectId", DbType.String, baseId);
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据PBomId获取对应的工序
/// 作 者:jason.tang
/// 完成时间:2013-08-23
/// </summary>
/// <param name="pbomid">PBOM ID</param>
/// <returns></returns>
public static DataSet GetOperByPBomId(string pbomid)
{
try
{
string strsql = @"select o.* from PP_PBOMVer v
inner join pp_PBOMVerRouting r
on v.VerId=r.VerId
inner join PP_RoutingOper rt
on r.RoutingId= rt.RoutingId
inner join pp_oper o
on o.OperId=rt.OperId
where v.VerId='{0}' ";
strsql = string.Format(strsql, pbomid);
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据PBomId获取对应的工艺路线
/// 作 者:jason.tang
/// 完成时间:2013-08-27
/// </summary>
/// <param name="pbomid">PBOM ID</param>
/// <returns></returns>
public static DataSet GetRoutingByPBomId(string pbomid)
{
try
{
string strsql = @"select top 1 pr.* from PP_PBOMVer v
inner join pp_PBOMVerRouting r
on v.VerId=r.VerId
inner join PP_RoutingOper rt
on r.RoutingId= rt.RoutingId
inner join PP_routing pr
on rt.RoutingId=pr.RoutingId
where v.VerId='{0}' ";
strsql = string.Format(strsql, pbomid);
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch(Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据物料版本ID获取相关对象
/// 作 者:jason.tang
/// 完成时间:2013-09-13
/// </summary>
/// <param name="verId">版本ID</param>
/// <returns></returns>
public static DataSet GetMaterialObjectByVerId(string verId)
{
try
{
string strsql = @"SELECT
case ObjectOption
when '0' then N'文档'
when '5' then N'业务表单'
when '8' then N'邮件'
when '13' then N'工装'
when '11' then N'PBOM'
when '30' then N'工艺卡片'
end as ObjectOption,
Name,
Code,
VerCode,
CategoryName,
case RelationType
when 1 then N'设计'
when 2 then N'质量'
when 3 then N'工艺'
when 4 then N'生产'
when 5 then N'其他'
else '' end as RelationType,
case OriginalMode
when 1 then '文档创建'
else '' end as OriginalMode,
ObjectOption as ObjOption,
CheckOutState,
KeyId, ObjectId,
(select CopyId from Doc_DocumentCopy where VerId= ObjectId And IsActive = 1 ) as CopyId,
ObjectOption, CategoryId, State,CheckOutState, ObjectIconPath ,RelationType,
SrcObjectId
from V_Mat_RelationObject_New v
WHERE SrcObjectId = '{0}'
OR DesObjectId = '{1}' ";
strsql = string.Format(strsql, verId, verId);
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch(Exception ex)
{
throw ex;
}
}
}
}
|
using Huajie.Practices.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Airbest.Db;
using Meow.Diagnosis;
using Airbest.Products.Specials;
using Huajie.Practices.Models;
using Airbest.Languages;
using System.IO;
namespace Airbest.Products
{
public class ProductService
{
private readonly Db.AirbestDbContext db;
private readonly TextResService textSvr;
public ProductService(AirbestDbContext db, TextResService textSvr)
{
ThrowHelper.ThrowNullArgument(db, nameof(db));
ThrowHelper.ThrowNullArgument(textSvr, nameof(textSvr));
this.db = db;
this.textSvr = textSvr;
}
public Product Get(Guid id, ProductQueryIncludes includes = ProductQueryIncludes.None, bool throwIfNull = true)
{
var dbm = FindDbm(id, throwIfNull);
return dbm == null ? null : FromDbm(dbm, includes);
}
public QueryResult<Product> GetResult(ProductQueryFilter filter)
{
ThrowHelper.ThrowNullArgument(filter, nameof(filter));
var q = from it in db.Products
orderby it.Index, it.CreateDate
select it;
return filter.GetResult(q, dbm => FromDbm(dbm, includes: filter.Includes));
}
public Guid Create(Product product)
{
ThrowHelper.ThrowNullArgument(product, nameof(product));
var dbm = CreateDbm(product);
UpdateDbm(dbm, product);
db.Products.Add(dbm);
db.SaveChanges();
return dbm.Id;
}
public void Update(Product product)
{
ThrowHelper.ThrowNullArgument(product, nameof(product));
ThrowHelper.ThrowNullArgument(product.Id, $"{nameof(product)}.{nameof(product.Id)}");
var dbm = FindDbm((Guid)product.Id);
UpdateDbm(dbm, product);
db.SaveChanges();
}
public void Delete(Guid id)
{
var dbm = FindDbm(id, false);
if (dbm != null)
{
db.Products.Remove(dbm);
db.SaveChanges();
}
}
#region privates
private Db.Product FindDbm(Guid id, bool throwIfNull = true)
{
var dbm = db.Products.Find(id);
ThrowHelper.ThrowIf(dbm == null && throwIfNull, "未能找到Product, id=" + id);
return dbm;
}
private void UpdateDbm(Db.Product dbm, Product product)
{
dbm.Name = product.Name;
dbm.CategoryId = product.CategoryId;
dbm.ImageUrl = product.ImageUrl;
dbm.Index = product.Index;
if (product.Res != null)
textSvr.Update(dbm.Id, product.Res);
}
private Db.Product CreateDbm(Product product)
{
return new Db.Product()
{
Id = Guid.NewGuid(),
};
}
private Product FromDbm(Db.Product dbm, ProductQueryIncludes includes)
{
var product = new Product()
{
Id = dbm.Id,
Name = dbm.Name,
CategoryId = dbm.CategoryId,
Index = dbm.Index,
ImageUrl = dbm.ImageUrl
};
if (includes.HasFlag(ProductQueryIncludes.Res))
product.Res = textSvr.Get((Guid)product.Id);
return product;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
namespace KartExchangeEngine
{
public class ImportSupplierCSV:Entity
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get { return "Импорт контрагентов"; }
}
public string SupplierCode
{
get;
set;
}
public string SupplierName
{
get;
set;
}
public string INN
{
get;
set;
}
}
}
|
using System;
using System.Linq;
namespace _03._Custom_Min_Function
{
class Program
{
static void Main(string[] args)
{
Func<string, int> getMin = (input) => { return input.Split(' ',StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList().Min(); };
Console.WriteLine(getMin(Console.ReadLine()));
}
}
}
|
using System;
namespace Ease.Application
{
public class Class1
{
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using BitClassroom.DAL.Models;
namespace BitClassroom.MVC.Controllers
{
public class QuestionResponsesController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: QuestionResponses
public ActionResult Index()
{
var questionResponses = db.QuestionResponses;
var surveyTitle = db.Surveys.Include(st => st.Title);
return View(questionResponses.ToList());
}
public ActionResult SurveyQuestionResponses(int id)
{
var questionResponses = db.QuestionResponses.Where(qr => qr.SurveyId == id); //.Include(q => q.Question);
return View(questionResponses.ToList());
}
// GET: QuestionResponses/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
QuestionResponse questionResponse = db.QuestionResponses.Find(id);
if (questionResponse == null)
{
return HttpNotFound();
}
return View(questionResponse);
}
// GET: QuestionResponses/Create
public ActionResult Create()
{
ViewBag.MentorReportId = new SelectList(db.MentorReports.Include("Mentor").Include("Student"), "Id", "MentorStudentCombo");
ViewBag.SurveyId = new SelectList(db.Surveys, "Id", "Title");
ViewBag.QuestionId = new SelectList(db.Questions, "Id", "QContent");
return View();
}
// POST: QuestionResponses/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,MentorReportId,SurveyId,Answer,QuestionId")] QuestionResponse questionResponse)
{
if (ModelState.IsValid)
{
db.QuestionResponses.Add(questionResponse);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MentorReportId = new SelectList(db.MentorReports.Include("Mentor").Include("Student"), "Id", "MentorStudentCombo");
ViewBag.SurveyId = new SelectList(db.Surveys, "Id", "Title");
ViewBag.QuestionId = new SelectList(db.Questions, "Id", "QContent", questionResponse.QuestionId);
return View(questionResponse);
}
// GET: QuestionResponses/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
QuestionResponse questionResponse = db.QuestionResponses.Find(id);
if (questionResponse == null)
{
return HttpNotFound();
}
var MentorReportId = db.MentorReports.Include("Mentor").Include("Student");
ViewBag.SurveyId = new SelectList(db.Surveys, "Id", "Title");
ViewBag.QuestionId = new SelectList(db.Questions, "Id", "QContent", questionResponse.QuestionId);
return View(questionResponse);
}
// POST: QuestionResponses/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,MentorReportId,SurveyId,Answer,QuestionId")] QuestionResponse questionResponse)
{
if (ModelState.IsValid)
{
db.Entry(questionResponse).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MentorReportId = new SelectList(db.MentorReports.Include("Mentor").Include("Student"), "Id", "MentorStudentCombo");
ViewBag.SurveyId = new SelectList(db.Surveys, "Id", "Title");
ViewBag.QuestionId = new SelectList(db.Questions, "Id", "QContent", questionResponse.QuestionId);
return View(questionResponse);
}
// GET: QuestionResponses/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
QuestionResponse questionResponse = db.QuestionResponses.Find(id);
if (questionResponse == null)
{
return HttpNotFound();
}
return View(questionResponse);
}
// POST: QuestionResponses/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
QuestionResponse questionResponse = db.QuestionResponses.Find(id);
db.QuestionResponses.Remove(questionResponse);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
namespace NBatch.Main.Readers.FileReader
{
public interface IFieldSetMapper<out T>
{
T MapFieldSet(FieldSet fieldSet);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChessXiang : ChessEntity
{
public override void ShowChessPath()
{
base.ShowChessPath();
int index_x = (int)chessObj.chess_index_x;
int index_z = (int)chessObj.chess_index_z;
// 自己的相
if (chessObj.chess_owner_player == 1)
{
if(!hasEntity(index_x + 1, index_x - 1))
SetIndexPath(index_x + 2, index_z - 2);
if(!hasEntity(index_x - 1, index_x - 1))
SetIndexPath(index_x - 2, index_z - 2);
if (index_z + 2 <= 4)
{
if(!hasEntity(index_x + 1, index_x + 1))
SetIndexPath(index_x + 2, index_z + 2);
if(!hasEntity(index_x - 1, index_x + 1))
SetIndexPath(index_x - 2, index_z + 2);
}
}
else
{
if(!hasEntity(index_x + 1, index_x + 1))
SetIndexPath(index_x + 2, index_z + 2);
if(!hasEntity(index_x - 1, index_x + 1))
SetIndexPath(index_x - 2, index_z + 2);
if(index_z - 2 <= 5)
{
if(!hasEntity(index_x + 1, index_x - 1))
SetIndexPath(index_x + 2, index_z - 2);
if(!hasEntity(index_x - 1, index_x - 1))
SetIndexPath(index_x - 2, index_z - 2);
}
}
}
public override ChessType GetChessType()
{
return ChessType.ChessTypeXiang;
}
}
|
using DigitalFormsSteamLeak.Business;
using DigitalFormsSteamLeak.Entity.IModels;
using DigitalFormsSteamLeak.Entity.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitalFormsSteamLeak.SteamLeaksAPI.UnitTests
{
[TestClass]
public class LeakDetailsTest
{
protected LeakDetailsFactory ltr { get; set; }
public LeakDetailsTest()
{
ltr = new LeakDetailsFactory();
}
[TestMethod]
public void AddLeakDetails()
{
try
{
ILeakDetails leakDetails = new LeakDetails();
leakDetails.LeakDetailsId = Guid.NewGuid();
leakDetails.UserId = Guid.Parse("57BB12E7-85F1-4612-98BA-215028590D53");
leakDetails.LeakTypeId = Guid.Parse("B9219816-7D18-4534-A29A-50684D47E449");
leakDetails.UnitId = Guid.Parse("D73554EA-A8A6-4779-8C91-051024F488F2");
leakDetails.LeakNumber = 2;
leakDetails.ScoopedDate = DateTime.Now;
leakDetails.NotificationNumber = 123323;
leakDetails.DateNotificationReceived = DateTime.Parse("10/10/2017");
leakDetails.WorkOrderNumber = 1234;
leakDetails.DateWorkOrderReceived = DateTime.Now;
leakDetails.WorkOrderDescription = "the work order is received";
leakDetails.SSTDescription = "The Sst description is received";
leakDetails.IdentifiedBy = "steam";
leakDetails.DecibelReading = 2.2f;
leakDetails.HeightFromGrade = 2.2f;
leakDetails.HeightFromLeak = 2.2f;
leakDetails.ExistingHearingProtection = "single";
leakDetails.Populate ="Y";
leakDetails.PlumeSize =100.0f;
leakDetails.Temperature =100.0f;
leakDetails.OrificeSize =100.0f;
leakDetails.LOCReading =100.0f;
leakDetails.LOCRate = 100.0f;
leakDetails.IsPlanWithProcessReqired ="Y";
leakDetails.IsFEWARequired ="Y";
//leakDetails.IsAttach2Required = "Y";
leakDetails.IsMOCRequired ="Y";
leakDetails.IsRemoveInsulationRequired ="Y";
leakDetails.IsReinstallInsulationRequired ="Y";
leakDetails.IsReScopeRequired ="Y";
leakDetails.JobPackStatus ="NEW";
leakDetails.LeakStatus ="NEW";
leakDetails.LeakComments ="CREATED";
ltr.Create((LeakDetails)leakDetails);
}
catch (Exception ex)
{
throw ex;
}
}
}
} |
using System;
using System.Collections.Generic;
namespace DemoApp.Entities
{
public partial class OfficeTypes
{
public OfficeTypes()
{
Offices = new HashSet<Offices>();
}
public Guid Id { get; set; }
public string Description { get; set; }
public bool? IsActive { get; set; }
public virtual ICollection<Offices> Offices { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class AlarmSignal : MonoBehaviour
{
[SerializeField] private AudioSource _alarmSignal;
[Header("Шаг изменения значения")]
[SerializeField] private float _duration;
private float _requiredValue;
private float _tempVolumeValue;
private bool _inHouse;
private Coroutine _coroutine;
private void Start()
{
_alarmSignal.volume = 0;
_tempVolumeValue = _duration * Time.deltaTime;
}
private void OnTriggerEnter2D(Collider2D collision)
{
_inHouse = true;
_alarmSignal.Play();
_coroutine = StartCoroutine(ChangeSoundVolume());
}
private void OnTriggerExit2D(Collider2D collision)
{
StopCoroutine(_coroutine);
_inHouse = false;
_coroutine = StartCoroutine(ChangeSoundVolume());
}
private IEnumerator ChangeSoundVolume()
{
if (_inHouse)
{
_requiredValue = 1;
}
else
{
_requiredValue = 0;
}
while (_alarmSignal.volume != _requiredValue)
{
_alarmSignal.volume = Mathf.MoveTowards(_alarmSignal.volume, _requiredValue, _tempVolumeValue * Time.deltaTime);
yield return null;
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using SQLite;
namespace WSTower.App
{
public class UsuarioRepository
{
readonly SQLiteAsyncConnection _database;
public UsuarioRepository(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<Usuario>().Wait();
}
public Task<List<Usuario>> GetUsuarioAsync()
{
return _database.Table<Usuario>().ToListAsync();
}
public Task<int> SaveUsuarioAsync(Usuario usuario)
{
return _database.InsertAsync(usuario);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ZombieInfectionFill : MonoBehaviour
{
public Image InfectionFill;
public float Fill;
// Start is called before the first frame update
void Start()
{
Fill = 1.0f;
}
// Update is called once per frame
void Update()
{
if (Fill > 0)
{
Fill -= Time.deltaTime * 0.2f;
}
InfectionFill.fillAmount = Fill;
}
}
|
namespace IKriv.Windows.Async
{
public interface IBusyIndicator
{
bool IsBusy { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Vendas.Util
{
public static class Mensagens
{
public static string REMOVIDO_SUCESSO = "Removido com sucesso.";
}
} |
using System;
using System.Collections.Generic;
using StardewValley;
namespace RemoteFridgeStorage.apis
{
public interface ICookingSkillApi
{
Func<IList<Item>> setFridgeFunction(Func<IList<Item>> func);
}
} |
using System.Threading.Tasks;
namespace gView.Framework.Data
{
public interface IValuesFieldDomain : IFieldDomain
{
Task<object[]> ValuesAsync();
}
/*
public interface IFeatureBuffer
{
IFeature CreateFeature();
bool Store();
}
*/
}
|
using System.Collections.Generic;
using System.Linq;
using HtmlAgilityPack;
using NeuroLinker.Models;
namespace NeuroLinker.Extensions
{
/// <summary>
/// Scrapes character information from the Information page in the anime.
/// This information is not for individual characters but rather basic information for all characters in a show
/// </summary>
public static class CharacterInformationScrapingExtensions
{
#region Public Methods
/// <summary>
/// Populates the Character and Seiyuu information for an anime
/// </summary>
/// <param name="anime">Anime for which the Seiyuu and Characters should be populated</param>
/// <param name="doc">HtmlDocument from which information should be retrieved</param>
/// <returns>Anime populated with the Seiyuu and characters</returns>
public static Anime PopulateCharacterAndSeiyuuInformation(this Anime anime, HtmlDocument doc)
{
var rows = doc.DocumentNode
.SelectNodes("//table")
.SelectMany(table => table.ChildNodes)
.Where(row => row.Name == "tr" && row.ChildNodes.Count(x => x.Name == "td") == 3);
foreach (var row in rows)
{
var columns = row.ChildNodes
.Where(t => t.Name == "td")
.ToList();
var vaDetail = columns[2]
.ChildNodes["table"]
?.ChildNodes.Where(t => t.Name == "tr")
.ToList()
?? Enumerable.Empty<HtmlNode>();
var tmpChar = CreateCharacter(columns)
.PopulateSeiyuu(vaDetail);
if (anime.CharacterInformation.All(t => t.CharacterUrl != tmpChar.CharacterUrl))
{
anime.CharacterInformation.Add(tmpChar);
}
}
return anime;
}
#endregion
#region Private Methods
/// <summary>
/// Create a new Character instance from HtmlNodes
/// </summary>
/// <param name="nodes">HtmlNodes containing the character information</param>
/// <returns>Character instance</returns>
private static CharacterInformation CreateCharacter(IList<HtmlNode> nodes)
{
var picLocation = nodes[0]
.ChildNodes["div"]
.ChildNodes["a"]
.ChildNodes["img"];
var url = nodes[0]
.ChildNodes["div"]
.ChildNodes["a"]
.Attributes["href"]
.Value;
int.TryParse(url.Split('/')[4], out var id);
var name = nodes[1].ChildNodes
.First(x => x.Name == "div" && x.ChildNodes.Any(z => z.Name == "a"))
.ChildNodes["a"]
.ChildNodes["h3"]
.InnerText
.HtmlDecode();
var charType = nodes[1].ChildNodes
.Where(x => x.Name == "div")
.ToList()[3]
.InnerText
.Replace("\r\n", "")
.Replace("\n", "")
.Replace(" ", "")
.HtmlDecode()
.Trim();
var newChar = new CharacterInformation
{
CharacterPicture = (picLocation.Attributes["data-src"] ?? picLocation.Attributes["src"])?.Value,
CharacterName = name,
CharacterUrl = url,
CharacterType = charType,
Id = id
};
return newChar;
}
/// <summary>
/// Populate Seiyuu information for a character
/// </summary>
/// <param name="character">Character to which the Seiyuu information should be added</param>
/// <param name="seiyuuInfoNodes">HtmlNodes containing the Seiyuu information</param>
/// <returns>Character instance</returns>
private static CharacterInformation PopulateSeiyuu(this CharacterInformation character,
IEnumerable<HtmlNode> seiyuuInfoNodes)
{
foreach (var detail in seiyuuInfoNodes)
{
var picNode = detail.ChildNodes[3]
.ChildNodes["div"]
.ChildNodes["a"]
.ChildNodes["img"];
var language = detail.ChildNodes["td"].ChildNodes
.First(x => x.Attributes.Any(z => z.Value == "spaceit_pad js-anime-character-language"))
.InnerText
.Replace("\r\n", "")
.Replace("\n", "")
.Replace(" ", "");
var tmpSeiyuu = new SeiyuuInformation
{
Language = language,
Name = detail.ChildNodes["td"].ChildNodes["div"].ChildNodes["a"].InnerText.HtmlDecode(),
Url = detail.ChildNodes["td"].ChildNodes["div"].ChildNodes["a"].Attributes["href"].Value,
PictureUrl = (picNode.Attributes["data-src"] ?? picNode.Attributes["src"])?.Value
};
if (int.TryParse(tmpSeiyuu.Url.Split('/')[4], out var id))
{
tmpSeiyuu.Id = id;
}
character.Seiyuu.Add(tmpSeiyuu);
}
return character;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
const int LEFT_MOUSE_BUTTON = 0;
const int RIGHT_MOUSE_BUTTON = 1;
public enum Type { MOVE, SELECT, BUTTON1, BUTTON2, BUTTON3, BUTTON4, CHAR1, CHAR2, CHAR3, NONE }
public static Type getPlayerInput()
{
if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
foreach (Touch touch in Input.touches)
{
if (touch.tapCount == 1)
{
return Type.SELECT;
}
if (touch.tapCount == 2)
{
return Type.MOVE;
}
}
}
else
{
if (Input.GetMouseButton(LEFT_MOUSE_BUTTON))
{
return Type.SELECT;
}
else if (Input.GetMouseButton(RIGHT_MOUSE_BUTTON))
{
return Type.MOVE;
}
}
return Type.NONE;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mediator
{
interface IComprobante
{
int Numero { get; set; }
}
}
|
using UnityEngine;
using Zenject;
using Pathfinding;
using UI;
public class PathfindingInstaller : MonoInstaller<PathfindingInstaller>
{
[SerializeField]
private DijkstraPathfinding dijkstraPathfinding;
[SerializeField]
private AStarPathfinding aStarPathfinding;
[SerializeField]
private PathfindingAlgorithmChooser pathfindingAlgorithmChooser;
[SerializeField]
private FinalPathDisplayer finalPathDisplayer;
public override void InstallBindings()
{
DeclareSignals();
BindSignals();
BindTypes();
}
private void BindTypes()
{
Container.Bind<DijkstraPathfinding>().FromInstance(dijkstraPathfinding).NonLazy();
Container.Bind<AStarPathfinding>().FromInstance(aStarPathfinding).NonLazy();
Container.Bind<PathfindingAlgorithmChooser>().FromInstance(pathfindingAlgorithmChooser);
}
private void BindSignals()
{
Container.BindSignal<FindPathSignal>().ToMethod(pathfindingAlgorithmChooser.RunPathfindingAlgorithm);
Container.BindSignal<PathFoundSignal>().ToMethod(finalPathDisplayer.DisplayFinalPath);
}
private void DeclareSignals()
{
Container.DeclareSignal<FindPathSignal>();
Container.DeclareSignal<PathFoundSignal>();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WeponForceTestForDNF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double FORCERATE = 34;
double currentRate = 0;
double myOwnCoins = 60000000;//初始资源
int MaxValue = 100;
int MinValue = 1;
bool humanDisturb = false;
bool useAdvanceC = false;
List<Wepon> InitWeponInfoList = null;
List<Wepon> WeponInfoList = null;//目前拥有的列表
List<Wepon> SucceedWeponInfoList = null;
List<Wepon> DestoryWeponInfoList = null;
Random rnd = new Random();
public int totalFalseCount = 0;
public int totalSucceedCount = 0;
public static int totalTired = 1;//完全失败个数
public static Dictionary<int, string> FStatic = new Dictionary<int, string>();//完全失败个数
private void button1_Click(object sender, EventArgs e)
{
BeginTest();
}
/// <summary>
/// 开始测试
/// </summary>
private InvokeResult BeginTest()
{
var iResult =new InvokeResult();
this.ResultShow.Text += "---------------------------------------------------\n";
InitialBasicParam();
WeponInfoList = WeponInfoList.OrderBy(c => c.Level).ToList();
for (var i = 0; i < WeponInfoList.Count(); )
{
if (i >= WeponInfoList.Count())
{
break;
}
var wepon = WeponInfoList[i];
iResult = CaculateResult(wepon);
this.ResultShow.Text += iResult.message + "\n";
WeponInfoList.Remove(wepon);
if (iResult.success == true)
{
InitialBasicParam();
this.ResultShow.Text += "---------------------------------------------------\n";
return iResult;
}
else
{
}
}
this.ResultShow.Text += "各种爆啊你妹" + "\n\r";
this.ResultShow.Text += "---------------------------------------------------\n";
totalTired++;
if(!FStatic.ContainsKey(totalTired))
{
FStatic.Add(totalTired, iResult.message);
}
MessageBox.Show("死心吧混蛋");
InitialBasicParam();
this.ResultShow.Text += "---------------------------------------------------\n";
this.label1.Text = totalTired.ToString();
return iResult;
//TestRate();
}
/// <summary>
/// 获取装备价值
/// </summary>
/// <returns></returns>
public double GetWeponValue()
{
return WeponInfoList.Where(c=>c.status==1).Select(c => c.curCost).Sum();
}
/// <summary>
/// 测试概率
/// </summary>
public void TestRate()
{
for (var i = 0; i <= 7; i++)
{
var result=GetResult();
if (result.success == true)
{
totalSucceedCount++;
}
else
{
totalFalseCount++;
}
}
MessageBox.Show(string.Format("succeed:{0},false{1} 概率:{2}", totalSucceedCount, totalFalseCount, decimal.Round(decimal.Parse(totalSucceedCount.ToString()) / (totalSucceedCount + totalFalseCount) * 100, 2)));
}
/// <summary>
/// 计算结果
/// </summary>
/// <returns></returns>
public InvokeResult CaculateResult(Wepon wepon)
{
Thread.Sleep(10);
var result = new InvokeResult();
string operateInfo=string.Empty;
wepon.curForceLevel+=1;
myOwnCoins -= wepon.forceCost;
var cresult = GetResult();
if (cresult.success == true)//成功失败
{
result.success = true;
wepon.status = 0;
myOwnCoins+=wepon.nextForceLevelCost;
wepon.curCost = wepon.nextForceLevelCost;
SucceedWeponInfoList.Add(wepon);
var WeponValue = GetWeponValue();
operateInfo += string.Format("【{7}】强化{0} +{1}成功 强化费用{4} 成功赚取{2} 当前拥有{3} 装备{5} 总价值:{6}", wepon.name, wepon.curForceLevel, wepon.nextForceLevelCost, myOwnCoins, wepon.forceCost, WeponValue, WeponValue + myOwnCoins, cresult.value);
}
else
{
result.success = false;
wepon.status=0;
var WeponValue = GetWeponValue();
operateInfo += string.Format("【{6}】强化{0} +{1} 失败 强化费用{2} 当前拥有{3} 装备{4} 总价值:{5}", wepon.name, wepon.curForceLevel, wepon.forceCost, myOwnCoins, WeponValue, WeponValue + myOwnCoins, cresult.value);
DestoryWeponInfoList.Add(wepon);
}
result.message = operateInfo;
return result;
}
/// <summary>
/// 是否成功 ,成功概率为34%
/// </summary>
/// <returns></returns>
public InvokeResult GetResult()
{
InvokeResult result = new InvokeResult();
if (useAdvanceC)
{
currentRate = FORCERATE * 1.1;
}
var getNumber = rnd.Next(MinValue, MaxValue);
result.value = getNumber;
// MessageBox.Show(currentRate.ToString());
if (getNumber <= currentRate)
{
result.success = true;
result.message = (getNumber.ToString() + "成功");
// MessageBox.Show(getNumber.ToString()+"成功");
// this.ResultShow.Text += getNumber.ToString() + "成功";
return result;
}
else
{
result.success = false;
result.message = (getNumber.ToString() + "失败");
// MessageBox.Show(getNumber.ToString() + "失败");
// this.ResultShow.Text += getNumber.ToString() + "失败";
return result;
}
}
/// <summary>
/// 初始化参数
/// </summary>
public void InitialBasicParam()
{
currentRate = FORCERATE;
if (WeponInfoList == null)
{
WeponInfoList = new List<Wepon>();
}
SucceedWeponInfoList = new List<Wepon>();
DestoryWeponInfoList = new List<Wepon>();
if (CanHuamDisturb.Checked)
{
humanDisturb = true;
}
else
{
humanDisturb = false;
}
if (CanUserAdvanceC.Checked)
{
useAdvanceC = true;
}
else
{
useAdvanceC = false;
}
var ownWeponQuery=WeponInfoList.Select(c=>c.name);
var hitQuery = InitWeponInfoList.Where(c => !ownWeponQuery.Contains(c.name));
double totolaCost = 0;
foreach (var wepon in InitWeponInfoList)
{
if (!string.IsNullOrEmpty(wepon.name.Trim()))
{
if (WeponInfoList.Where(c => c.name.Trim() == wepon.name.Trim()).Count() <= 0)
{
var newCopyOne =InitialWepon(wepon.initialStr);
WeponInfoList.Add(newCopyOne);
if (myOwnCoins-wepon.curCost <= 0)
{
this.ResultShow.Text += "弱爆了 你没钱了";
break;
}
myOwnCoins -= wepon.curCost;
totolaCost += wepon.curCost;
this.ResultShow.Text += string.Format("花费{0}买了+{1} {2} 剩余:{3}\r\n", wepon.curCost, wepon.curForceLevel, wepon.name, myOwnCoins);
}
}
}
var weaponValue = GetWeponValue();
this.ResultShow.Text += string.Format("此次花费{0} 余额{1} 目前装备总价:{2} 总计:{3}\n\r", totolaCost, myOwnCoins, weaponValue, weaponValue + myOwnCoins);
}
/// <summary>
/// 名称|等级|价格|下一级价格
/// </summary>
/// <param name="?"></param>
/// <returns></returns>
public Wepon InitialWepon(string weponInfo)
{
var curWepon=new Wepon();
if (string.IsNullOrEmpty(weponInfo))
{
return curWepon;
}
try{
var strArray = weponInfo.Split('|');
if(strArray.Length>=3)
{
curWepon.name=strArray[0];
curWepon.status = 1;
curWepon.curForceLevel = 10;
curWepon.Level = int.Parse(strArray[1]);
curWepon.curCost = double.Parse(strArray[2]);
curWepon.initialStr = weponInfo;
if (strArray.Length >= 4)
{
curWepon.nextForceLevelCost = double.Parse(strArray[3]);
}
else
{
curWepon.nextForceLevelCost = 2 * curWepon.curCost;
}
if (strArray.Length >= 5)
{
curWepon.forceCost = double.Parse(strArray[4]);
}
else
{
if (curWepon.Level <= 10)
{
curWepon.forceCost = curWepon.Level * 300;
}
else if (curWepon.Level > 10 && curWepon.Level <40)
{
curWepon.forceCost = curWepon.Level * 800;
}
else if (curWepon.Level >= 40)
{
curWepon.forceCost = curWepon.Level * 3000;
}
}
}
}
catch (InvalidCastException ex)
{
}
catch (Exception ex)
{
}
return curWepon;
}
/// <summary>
///
/// </summary>
public class Wepon
{
public string name { get; set; }//名称
public double curCost { get; set; }//当前花费
public int curForceLevel { get; set; }//当前force等级
public int Level { get; set; }//wepon等级
public double nextForceLevelCost { get; set; }//下一级价格
public int status { get; set; }//状态
public double forceCost { get; set; }//force费用
public string initialStr { get; set; }
public string order { get; set; }
//public Wepon Copy()
//{
// return new Wepon() { name = name, curCost = curCost, curForceLevel = curForceLevel, forceCost = forceCost, status = status, nextForceLevelCost = nextForceLevelCost, Level=Level };
//}
}
public class InvokeResult
{
public string message { get; set; }
public object value { get; set; }
public bool success { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
totalFalseCount = 0;
totalSucceedCount = 0;
InitWeponInfoList = new List<Wepon>();
if (string.IsNullOrEmpty(this.WeponSourceList.Text))
this.WeponSourceList.Text = "粗布拖鞋|0|120000|240000 \r\n 破旧的太|1|130000|300000 \r\n 蓝太|30|300000|600000 \r\n 锋利的长|40|600000|1200000 \r\n 影虎|45|1200000|2400000 \r\n 55蓝|55|3000000|6000000 \r\n 60紫|60|6000000|12000000 \r\n 65紫|65|12000000|24000000 \r\n 60粉|66|24000000|48000000 ";
var weponStr = this.WeponSourceList.Text.Trim();
var weponStrArray = weponStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var InitWeponInfoQuery= InitWeponInfoList.Select(c=>c.name);
foreach (var weponInfo in weponStrArray)
{
if (!string.IsNullOrEmpty(weponInfo.Trim()))
{
var wepon = InitialWepon(weponInfo);
if (!InitWeponInfoQuery.Contains(wepon.name))
{
InitWeponInfoList.Add(wepon);
}
// myOwnCoins -= wepon.curCost;
//this.ResultShow.Text += string.Format("花费{0}买了+{1} {2} 剩余:{3}\r\n", wepon.curCost, wepon.curForceLevel, wepon.name, myOwnCoins);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
totalTired = 0;
Form1_Load( sender, e);
}
private void button3_Click(object sender, EventArgs e)
{
currentRate = FORCERATE;
if (CanHuamDisturb.Checked)
{
humanDisturb = true;
}
else
{
humanDisturb = false;
}
if (CanUserAdvanceC.Checked)
{
useAdvanceC = true;
}
else
{
useAdvanceC = false;
}
var times = 10;
var sCount = 8;
try
{
times =int.Parse( this.Round.Text.Trim());
sCount = int.Parse(this.securityCount.Text.Trim());
}
catch (Exception ex)
{
}
var testBool=false;
var errorTimes = 0;
for (var i = 0; i < times; i++)
{
var errorStr = string.Empty;
for (var j = 1; j <= sCount; j++)
{
var result=GetResult();
errorStr += result.message;
if (result.success == true)
{
testBool = true;
break;
}
}
if (testBool == false)
{
// this.ResultShow.Text += errorStr;
// this.ResultShow.Text += "\n\r";
errorTimes++;
}
testBool = false;
}
string curShowText = string.Format("总共执行{0}此,完全失败个数{1}概率为{2}% \r\n", times, errorTimes, decimal.Round(decimal.Parse(errorTimes.ToString()) / times * 100, 2));
MessageBox.Show(curShowText);
}
private void button4_Click(object sender, EventArgs e)
{
rnd = new Random();
var resultText = new StringBuilder();
this.ResultShow.Text += "红球区:";
for (var i = 0; i <= 5; i++)
{
var redNumber = ChanceTicke(1,33);
resultText.Append(redNumber);
if (i != 5)
{
resultText.Append(',');
}
}
this.ResultShow.Text += resultText.ToString();
rnd = new Random();
this.ResultShow.Text += "蓝球球区:";
var blueNumber = ChanceTicke(1, 16);
this.ResultShow.Text += blueNumber;
}
public int ChanceTicke(int min,int max)
{
var getNumber = rnd.Next(min, max);
return getNumber;
}
}
}
|
namespace CapaUsuario.Compras.Pedidos_de_reaprovisionamiento
{
public class DetallePedidoReaprov
{
public int CodStock { get; set; }
public string NombreStock { get; set; }
public int Cantidad { get; set; }
public string Marca { get; set; }
public string Medida { get; set; }
}
}
|
namespace Pobs.Domain
{
public enum AgreementRating
{
Disagree = -1,
Agree = 1,
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Hni.TestMVC6.Models;
using Microsoft.Data.Entity;
using Microsoft.AspNet.Http;
using Serilog;
namespace Hni.TestMVC6
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
//20160428 LCJ Modify config based on environment
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
//Add Entity Framework DbContext that points to the existing database
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<SampleInspectionContext>(options => options.UseSqlServer(Configuration["connectionStrings:SampleInspectionContext"]));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//Add Serilog
var log = new Serilog.LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile(
pathFormat: env.MapPath("MvcLibrary-{Date}.log"),
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {SourceContext} [{Level}] {Message}{NewLine}{Exception}")
.CreateLogger();
loggerFactory.AddSerilog(log);
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Project.GameState;
namespace Project.Levels
{
public class Prolog : MonoBehaviour
{
public GameFile gameFile;
private void OnDisable()
{
/*GameState.Level prolog = Array.Find(gameFile.levels, x => x.name == "Prolog");
prolog.completed = true;*/
}
public void Completed()
{
GameState.Level prolog = Array.Find(gameFile.levels, x => x.name == "Prolog");
prolog.completed = true;
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadNextStage : MonoBehaviour {
public int sceneNumber = 1;
private void OnTriggerEnter2D(){
if(SceneManager.GetActiveScene() == SceneManager.GetSceneByBuildIndex(0))// curently on menu
CamTrack.camSize = 3;// set default camera size to 75%
SceneManager.LoadScene(sceneNumber , LoadSceneMode.Single);
//SceneManager.SetActiveScene(SceneManager.GetSceneByName("MudholeMarsh"));
}
float realPos;
void Start(){
realPos = transform.position.x;
}
void Update(){
if(Menu.showLightWarp)
transform.position = new Vector3(realPos + Player.lorentz*Mathf.Abs(realPos-Player.posx) , transform.position.y , transform.position.z);
else
transform.position = new Vector3(realPos , transform.position.y , transform.position.z);
}
}
|
namespace Sentry;
/// <summary>
/// The level of the event sent to Sentry.
/// </summary>
public enum SentryLevel : short
{
/// <summary>
/// Debug.
/// </summary>
[EnumMember(Value = "debug")]
Debug,
/// <summary>
/// Informational.
/// </summary>
[EnumMember(Value = "info")]
Info,
/// <summary>
/// Warning.
/// </summary>
[EnumMember(Value = "warning")]
Warning,
/// <summary>
/// Error.
/// </summary>
[EnumMember(Value = "error")]
Error,
/// <summary>
/// Fatal.
/// </summary>
[EnumMember(Value = "fatal")]
Fatal
} |
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Compression;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
namespace Client.Helpers
{
public class ScreenHelper
{
public static Bitmap GetScreen()
{
var width = Screen.PrimaryScreen.Bounds.Width;
var height = Screen.PrimaryScreen.Bounds.Height;
var bitmap = new Bitmap(width, height);
var graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
return bitmap;
}
public static byte[] GetScreenData()
{
var ms = new MemoryStream();
GetScreen().Save(ms, ImageFormat.Jpeg);
var bytes = ms.ToArray();
return Compress(bytes);
}
public static Image GetImage(byte[] bytes)
{
var tmpBytes = Decompress(bytes);
if (tmpBytes == null)
return null;
try
{
var ms = new MemoryStream(tmpBytes);
return Image.FromStream(ms);
}
catch
{
return null;
}
}
private static byte[] Compress(byte[] bytes)
{
using (var ms = new MemoryStream())
{
var compress = new GZipStream(ms, CompressionMode.Compress);
compress.Write(bytes, 0, bytes.Length);
compress.Close();
return ms.ToArray();
}
}
private static byte[] Decompress(byte[] bytes)
{
try
{
using (var tempMs = new MemoryStream())
{
using (var ms = new MemoryStream(bytes, 0, bytes.Length))
{
var decompress = new GZipStream(ms, CompressionMode.Decompress);
decompress.CopyTo(tempMs);
decompress.Close();
return tempMs.ToArray();
}
}
}
catch
{
return null;
}
}
public static Bitmap GetForm(Form form)
{
var bitmap = new Bitmap(form.Width, form.Height);
form.DrawToBitmap(bitmap, new Rectangle(0, 0, form.Width, form.Height));
return bitmap;
}
public static byte[] GetFormData(Form form)
{
var ms = new MemoryStream();
GetForm(form).Save(ms, ImageFormat.Bmp);
var bytes = ms.ToArray();
return Compress(bytes);
}
/// <summary>
/// 截取屏幕范围内的内容;
/// </summary>
/// <returns>截取的图片</returns>
public static Bitmap GetScreenImage()
{
Bitmap image = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(image);
g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.PrimaryScreen.Bounds.Size);
g.DrawImage(image, new Point(0, 0));
g.Dispose();
return image;
}
public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png); // 坑点:格式选Bmp时,不带透明度
stream.Position = 0;
BitmapImage result = new BitmapImage();
result.BeginInit();
result.CacheOption = BitmapCacheOption.OnLoad;
result.StreamSource = stream;
result.EndInit();
result.Freeze();
return result;
}
}
/// <summary>
/// 截取屏幕范围内的内容;
/// </summary>
/// <returns>截取的图片</returns>
public static Image GetScreenImage(int width, int height)
{
Image image = new Bitmap(width, height);
Graphics g = Graphics.FromImage(image);
g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.PrimaryScreen.Bounds.Size);
g.DrawImage(image, 0, 0, width, height);
g.Dispose();
return image;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class Client
{
[Display(Name = "ФИО")]
public string FIO { get; set; }
[Display(Name = "ИНН")]
public string INN { get; set; }
[Display(Name = "Номер договора")]
public List<int> AgreementId { get; set; }
}
} |
using Alabo.Data.People.PartnerCompanies.Domain.Entities;
using Alabo.Data.People.PartnerCompanies.Domain.Services;
using Alabo.Framework.Core.WebApis.Controller;
using Alabo.Framework.Core.WebApis.Filter;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
namespace Alabo.Data.People.PartnerCompanies.Controllers {
[ApiExceptionFilter]
[Route("Api/PartnerCompany/[action]")]
public class ApiPartnerCompanyController : ApiBaseController<PartnerCompany,ObjectId> {
public ApiPartnerCompanyController() : base()
{
BaseService = Resolve<IPartnerCompanyService>();
}
}
}
|
using Simple.Wpf.Composition.Infrastructure;
namespace Simple.Wpf.Composition.Workspaces.Example
{
public sealed class ExampleViewModel : BaseViewModel
{
}
} |
using System.Collections.Generic;
namespace NBatch.Main.Writers.FileWriter
{
internal interface IFileWriterService
{
void WriteFile(IEnumerable<string> values);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class AdminAddBus : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string con = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Travels;Integrated Security=True;Pooling=False";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = con;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Buses(busID,source,destination,date,time,totalSeats,availableSeats) values(@busID,@source,@destination,@date,@time,@totalSeats,@availableSeats)", conn);
cmd.Parameters.AddWithValue("@busID", TextBox1.Text);
cmd.Parameters.AddWithValue("@source", TextBox3.Text);
cmd.Parameters.AddWithValue("@destination", TextBox4.Text);
cmd.Parameters.AddWithValue("@date", TextBox5.Text);
cmd.Parameters.AddWithValue("@time", TextBox6.Text);
cmd.Parameters.AddWithValue("@totalSeats", TextBox7.Text);
cmd.Parameters.AddWithValue("@availableSeats", TextBox8.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
Response.Redirect("AdminHome.aspx");
}
protected void BackButtonClicked(object sender, EventArgs e)
{
Response.Redirect("~/AdminHome.aspx");
}
} |
using System.IO;
namespace SqlServerRunnerNet.ViewModel
{
public class ScriptViewModel : FileSystemObjectViewModel
{
private string _errorMessage;
public override bool HasError
{
get { return !string.IsNullOrWhiteSpace(ErrorMessage); }
}
public override string DisplayName
{
get { return new FileInfo(Path).Name; }
}
public string ErrorMessage
{
get { return _errorMessage; }
set
{
if (value == _errorMessage) return;
_errorMessage = value;
OnPropertyChanged();
OnPropertyChanged("HasError");
}
}
public FolderViewModel Parent { get; set; }
}
}
|
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 lab14
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Text = "Пример строки состояния";
CenterToScreen();
BackColor = Color.CadetBlue;
currentCheckedItem = toolStripMenuItemTime;
currentCheckedItem.Checked = true;
currentCheckedItemPrimer = primer1ToolStripMenuItem;
currentCheckedItemPrimer.Checked = true;
}
private void Form1_Load(object sender, EventArgs e)
{
toolStripComboBox1.SelectedIndex = 0;
}
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (toolStripComboBox1.Text)
{
case "белый": BackColor = Color.White; break;
case "красный": BackColor = Color.Red; break;
case "черный": BackColor = Color.Black; break;
case "синий": BackColor = Color.Blue; break;
case "желтый": BackColor = Color.Yellow; break;
default: BackColor = SystemColors.Control; break;
}
}
private void toolStripTextBox1_TextChanged(object sender, EventArgs e)
{
try
{
BackColor = Color.FromArgb(
Convert.ToInt32(toolStripTextBox1.Text),
Convert.ToInt32(toolStripTextBox2.Text),
Convert.ToInt32(toolStripTextBox3.Text));
}
catch { MessageBox.Show("Необходимо ввести целое число от 0 до 255", "Ошибка в задании цвета"); }
}
private void toolStripTextBox4_TextChanged(object sender, EventArgs e)
{
try
{
BackColor = Color.FromArgb(
Convert.ToInt32(toolStripTextBox4.Text),
Convert.ToInt32(toolStripTextBox5.Text),
Convert.ToInt32(toolStripTextBox6.Text));
}
catch { MessageBox.Show("Необходимо ввести целое число от 0 до 255", "Ошибка в задании цвета"); }
}
private void toolStripComboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
switch (toolStripComboBox2.Text)
{
case "белый": BackColor = Color.White; break;
case "красный": BackColor = Color.Red; break;
case "черный": BackColor = Color.Black; break;
case "синий": BackColor = Color.Blue; break;
case "желтый": BackColor = Color.Yellow; break;
default: BackColor = SystemColors.Control; break;
}
}
DateTimeFormat dtFormat = DateTimeFormat.ShowTime;
ToolStripMenuItem currentCheckedItem;
public enum DateTimeFormat
{
ShowTime,
ShowDate,
ShowMouse
}
private void timerDateTimeUpdate_Tick(object sender, EventArgs e)
{
string info = "";
if (dtFormat == DateTimeFormat.ShowTime)
info = DateTime.Now.ToLongTimeString();
else if (dtFormat == DateTimeFormat.ShowDate)
info = DateTime.Now.ToLongDateString();
toolStripStatusLabelState.Text = info;
}
private void toolStripMenuItemDate_Click(object sender, EventArgs e)
{
currentCheckedItem.Checked = false;
dtFormat = DateTimeFormat.ShowDate;
currentCheckedItem = toolStripMenuItemDate;
currentCheckedItem.Checked = true;
}
private void toolStripMenuItemTime_Click(object sender, EventArgs e)
{
currentCheckedItem.Checked = false;
dtFormat = DateTimeFormat.ShowTime;
currentCheckedItem = toolStripMenuItemTime;
currentCheckedItem.Checked = true;
}
private void курсорМышиToolStripMenuItem_Click(object sender, EventArgs e)
{
currentCheckedItem.Checked = false;
dtFormat = DateTimeFormat.ShowMouse;
currentCheckedItem = toolStripMenuItemMouse;
currentCheckedItem.Checked = true;
}
int X = 0, Y = 0;
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
X = MousePosition.X;
Y = MousePosition.Y;
if (dtFormat == DateTimeFormat.ShowMouse)
toolStripStatusLabelState.Text = $"X: {X} | Y: {Y}";
toolStripStatusLabel1.Text = Calculate2();
}
public string Calculate()
{
try
{
float answer = 0;
float x = Convert.ToInt32(toolStripTextBox7.Text);
float y = Convert.ToInt32(toolStripTextBox8.Text);
float z = Convert.ToInt32(toolStripTextBox9.Text);
float a = Convert.ToInt32(toolStripComboBox3.Text);
float b = Convert.ToInt32(toolStripComboBox4.Text);
answer = (float)(a * x * (b * y) / Math.Log10(z) + Math.Sin(z) / Math.Cos(y));
return $"Ответ: {answer}";
} catch { return "Значения ненормальные"; }
}
private void CalculatePrimer(object sender, EventArgs e)
{
Text = Calculate();
}
public enum PrimerType
{
Primer1,
Primer2
}
PrimerType primerType = PrimerType.Primer1;
ToolStripMenuItem currentCheckedItemPrimer;
private void primer2ToolStripMenuItem_Click(object sender, EventArgs e)
{
currentCheckedItemPrimer.Checked = false;
primerType = PrimerType.Primer2;
currentCheckedItemPrimer = primer2ToolStripMenuItem;
currentCheckedItemPrimer.Checked = true;
}
private void primer1ToolStripMenuItem_Click(object sender, EventArgs e)
{
currentCheckedItemPrimer.Checked = false;
primerType = PrimerType.Primer1;
currentCheckedItemPrimer = primer1ToolStripMenuItem;
currentCheckedItemPrimer.Checked = true;
}
public string Calculate2()
{
try
{
float answer = 0, answer2 = 0;
if (primerType == PrimerType.Primer1)
{
answer = X / Math.Abs(Y-X*X);
answer2 = (float)Math.Sqrt(Math.Abs(X - Math.Sqrt(Y)));
return $"z = {answer} | f = {answer2}";
}
else
{
answer = (float)(Math.Cos(X) + Math.Sin(Y));
return $"z = {answer}";
}
}
catch { return "Значения ненормальные"; }
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectAction : MonoBehaviour
{
[SerializeField] Transform parent;
[SerializeField] List<GameObject> games = new List<GameObject>();
void Start()
{
// games = new List<GameObject>(GameObject.FindGameObjectsWithTag("Objects"));
// for (int i = 0; i < games.Count; i++)
// {
// // games[i].GetComponent<IComponent>().Action();
// }
// // foreach (Transform Child in parent)
// // {
// // if (Child.tag == "Objects")
// // {
// // for (int i = 0; i < Child.GetComponents<IComponent>().Length; i++)
// // Child.GetComponents<IComponent>()[i].Action();
// // }
// // // if (Child.GetComponents<IComponent>() != null)
// // // for (int i = 0; i < Child.GetComponents<IComponent>().Length; i++)
// // // Child.GetComponents<IComponent>()[i].Action();
// // }
}
}
|
namespace KK.AspNetCore.EasyAuthAuthentication.Services
{
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using KK.AspNetCore.EasyAuthAuthentication.Interfaces;
using KK.AspNetCore.EasyAuthAuthentication.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// A service that can be used to authentificat a user principal in the <see cref="EasyAuthAuthenticationHandler"/>.
/// </summary>
public class EasyAuthWithHeaderService : IEasyAuthAuthentificationService
{
private const string PrincipalObjectHeader = "X-MS-CLIENT-PRINCIPAL";
private const string PrincipalIdpHeaderName = "X-MS-CLIENT-PRINCIPAL-IDP";
private static readonly Func<ClaimsPrincipal, bool> IsContextUserNotAuthenticated =
user => user == null || user.Identity == null || user.Identity.IsAuthenticated == false;
private static readonly Func<IHeaderDictionary, string, bool> IsHeaderSet =
(headers, headerName) => !string.IsNullOrEmpty(headers[headerName].ToString());
private readonly ProviderOptions defaultOptions = new ProviderOptions(typeof(EasyAuthWithHeaderService).Name, ClaimTypes.Email, ClaimTypes.Role);
/// <summary>
/// Initializes a new instance of the <see cref="EasyAuthWithHeaderService"/> class.
/// </summary>
/// <param name="logger">The logger for this service.</param>
public EasyAuthWithHeaderService(
ILogger<EasyAuthWithHeaderService> logger) => this.Logger = logger;
private ILogger Logger { get; }
/// <inheritdoc/>
public bool CanHandleAuthentification(HttpContext httpContext)
{
var headers = httpContext.Request.Headers;
var user = httpContext.User;
return IsContextUserNotAuthenticated(user) &&
IsHeaderSet(headers, AuthTokenHeaderNames.AADIdToken);
}
/// <summary>
/// build up identity from <see cref="PrincipalObjectHeader"/> header set by EasyAuth filters if user openId connect session cookie or oauth bearer token authenticated ...
/// </summary>
/// <param name="context">Http context of the request.</param>
/// <returns>An <see cref="AuthenticateResult" />.</returns>
public AuthenticateResult AuthUser(HttpContext context) => this.AuthUser(context, null);
/// <summary>
/// build up identity from <see cref="PrincipalObjectHeader"/> header set by EasyAuth filters if user openId connect session cookie or oauth bearer token authenticated ...
/// </summary>
/// <param name="context">Http context of the request.</param>
/// <param name="options">The <c>EasyAuthAuthenticationOptions</c> to use.</param>
/// <returns>An <see cref="AuthenticateResult" />.</returns>
public AuthenticateResult AuthUser(HttpContext context, ProviderOptions? options)
{
this.defaultOptions.ChangeModel(options);
var ticket = this.BuildIdentityFromEasyAuthRequestHeaders(context.Request.Headers, this.defaultOptions);
this.Logger.LogInformation("Set identity to user context object.");
context.User = ticket.Principal;
this.Logger.LogInformation("identity build was a success, returning ticket");
return AuthenticateResult.Success(ticket);
}
private AuthenticationTicket BuildIdentityFromEasyAuthRequestHeaders(IHeaderDictionary headers, ProviderOptions options)
{
var providerName = headers[PrincipalIdpHeaderName][0];
this.Logger.LogDebug($"payload was fetched from easyauth me json, provider: {providerName}");
var headerContent = headers[PrincipalObjectHeader][0];
this.Logger.LogInformation("building claims from payload...");
var xMsClientPrincipal = JObject.Parse(
Encoding.UTF8.GetString(
Convert.FromBase64String(headerContent)
)
);
var claims = JsonConvert.DeserializeObject<IEnumerable<AADClaimsModel>>(xMsClientPrincipal["claims"].ToString());
return AuthenticationTicketBuilder.Build(claims, providerName, options);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.