text stringlengths 13 6.01M |
|---|
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Text;
namespace Labyrinth
{
public class Key
{
private Vector2 keyPosA;
private Point keyPosR;
public Key(Vector2 keyPosA, Point keyPosR)
{
this.keyPosA = keyPosA;
this.keyPosR = keyPosR;
}
public Vector2 KeyPosA
{
get { return this.keyPosA; }
}
public Point KeyPosR
{
get { return this.keyPosR; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TY.SPIMS.Controllers;
using TY.SPIMS.Client.Users;
using TY.SPIMS.Utilities;
using ComponentFactory.Krypton.Toolkit;
using TY.SPIMS.POCOs;
using TY.SPIMS.Controllers.Interfaces;
namespace TY.SPIMS.Client.Controls
{
public partial class InventoryUserControl : UserControl, IRefreshable
{
private readonly IInventoryUserController inventoryUserController;
public InventoryUserControl()
{
this.inventoryUserController = IOC.Container.GetInstance<InventoryUserController>();
InitializeComponent();
}
#region Next / Previous
private void NextButton_Click(object sender, EventArgs e)
{
// If nothing is selected
if (dataGridView1.SelectedRows.Count == 0)
{
// If there are rows in the grid
if (dataGridView1.Rows.Count > 0)
{
// Select the first row
dataGridView1.Rows[0].Selected = true;
}
}
else
{
// Find index of next row
int index = dataGridView1.SelectedRows[0].Index + 1;
// If past end of list then go back to the start
if (index >= dataGridView1.Rows.Count)
index = 0;
// Select the row
dataGridView1.Rows[index].Selected = true;
}
dataGridView1.Refresh();
}
private void PreviousButton_Click(object sender, EventArgs e)
{
// If nothing is selected
if (dataGridView1.SelectedRows.Count == 0)
{
// If there are rows in the grid
if (dataGridView1.Rows.Count > 0)
{
// Select the last row
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;
}
}
else
{
// Find index of previous row
int index = dataGridView1.SelectedRows[0].Index - 1;
// If past start of list then go back to the end
if (index < 0)
index = dataGridView1.Rows.Count - 1;
// Select the row
dataGridView1.Rows[index].Selected = true;
}
dataGridView1.Refresh();
}
#endregion
#region Load
private void InventoryUserControl_Load(object sender, EventArgs e)
{
if (!UserInfo.IsAdmin)
DeleteButton.Visible = false;
LoadUsers();
}
private void LoadUsers()
{
inventoryUserDisplayModelBindingSource.DataSource =
this.inventoryUserController.FetchInventoryUserWithSearch(UserTextbox.Text);
}
#endregion
#region Add/Edit
private void AddButton_Click(object sender, EventArgs e)
{
OpenAddForm(0);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
int userId = (int)dataGridView1.Rows[e.RowIndex].Cells["IdColumn"].Value;
OpenAddForm(userId);
}
}
int selectedId = 0;
private void OpenAddForm(int userId)
{
selectedId = userId;
Form addForm = this.ParentForm.OwnedForms.FirstOrDefault(a => a.Name == "AddUserForm");
if (addForm == null)
{
AddUserForm form = new AddUserForm();
form.UserId = userId;
form.Owner = this.ParentForm;
form.UserUpdated += new UserUpdatedEventHandler(form_UserUpdated);
form.Show();
}
else
{
AddUserForm openedForm = (AddUserForm)addForm;
openedForm.UserId = userId;
openedForm.LoadUserDetails();
openedForm.Focus();
}
}
void form_UserUpdated(object sender, EventArgs e)
{
LoadUsers();
var source = (SortableBindingList<InventoryUserDisplayModel>)inventoryUserDisplayModelBindingSource.DataSource;
if (source != null)
{
if (selectedId == 0)
selectedId = source.Max(a => a.Id);
if (selectedId != 0)
{
InventoryUserDisplayModel item = source.FirstOrDefault(a => a.Id == selectedId);
int index = inventoryUserDisplayModelBindingSource.IndexOf(item);
inventoryUserDisplayModelBindingSource.Position = index;
dataGridView1.Rows[index].Selected = true;
}
}
}
#endregion
#region Search
private void SearchButton_Click(object sender, EventArgs e)
{
LoadUsers();
}
private void UserTextbox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
LoadUsers();
}
#endregion
#region Delete
private void DeleteButton_Click(object sender, EventArgs e)
{
if (!UserInfo.IsAdmin)
{
ClientHelper.ShowErrorMessage("You are not authorized to delete this record.");
return;
}
if (ClientHelper.ShowConfirmMessage("Are you sure you want to delete this user?") == DialogResult.Yes)
{
if (dataGridView1.SelectedRows.Count > 0)
{
DataGridViewRow row = dataGridView1.SelectedRows[0];
int id = (int)row.Cells["IdColumn"].Value;
this.inventoryUserController.DeleteInventoryUser(id);
ClientHelper.ShowSuccessMessage("User deleted successfully.");
LoadUsers();
}
}
}
#endregion
#region IRefreshable Members
public void RefreshView()
{
if (tabControl1.SelectedIndex == 0)
LoadUsers();
else
LoadApproval();
}
#endregion
private void kryptonNavigator1_SelectedPageChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedIndex == 0)
LoadUsers();
else
LoadApproval();
}
#region Approval Settings
private void LoadApproval()
{
SystemSettings.RefreshApproval();
List<string> keys = SystemSettings.Approval.Keys.ToList();
foreach (string key in keys)
{
if (kryptonHeaderGroup3.Panel.Controls.Count > 0)
{
Control[] c = kryptonHeaderGroup3.Panel.Controls.Find(key, true);
if (c.Count() > 0)
{
KryptonCheckBox chkBox = (KryptonCheckBox)c[0];
chkBox.Checked = SystemSettings.Approval[key];
}
}
}
}
private void SaveApproval_Click(object sender, EventArgs e)
{
foreach (Control c in tableLayoutPanel1.Controls)
{
if(c.GetType() == typeof(KryptonCheckBox))
{
KryptonCheckBox chk = (KryptonCheckBox)c;
SystemSettings.Approval[c.Name] = chk.Checked;
}
}
SystemSettings.SaveApproval();
ClientHelper.ShowSuccessMessage("Approval setting saved successfully.");
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Zombies3
{
class RectFeature
{
private Rectangle rectangle;
private Texture2D texture;
private string spriteName;
private Color color;
public RectFeature(Rectangle rectangle, Color color, string spriteName)
{
this.rectangle = rectangle;
this.color = color;
this.spriteName = spriteName;
}
public void LoadContent(ContentManager Content)
{
texture = Content.Load<Texture2D>(spriteName);
}
public void Update(GameTime gameTime)
{
}
public void Draw(GameTime gameTime, SpriteBatch sbatch)
{
sbatch.Draw(texture, rectangle, color);
}
public Rectangle Bounds
{
get { return rectangle; }
set { rectangle = value; }
}
}
}
|
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using RimDev.AspNetCore.FeatureFlags.Tests.Testing.ApplicationFactory;
using RimDev.AspNetCore.FeatureFlags.UI;
using Xunit;
namespace RimDev.AspNetCore.FeatureFlags.Tests
{
[Collection(nameof(TestWebApplicationCollection))]
public class FeatureFlagsUIBuilderTests
{
private readonly TestWebApplicationFactory fixture;
public FeatureFlagsUIBuilderTests(TestWebApplicationFactory fixture)
{
this.fixture = fixture;
}
[Fact]
public async Task Get_ReturnsExpectedFeature()
{
var client = fixture.CreateClient();
var uiSettings = fixture.Services.GetRequiredService<FeatureFlagUISettings>();
var request = new FeatureRequest
{
Name = nameof(TestFeature),
Enabled = true
};
await SetValueViaApiAsync(request);
var response = await client.GetAsync(
$"{uiSettings.ApiGetPath}?feature={request.Name}");
response.EnsureSuccessStatusCode();
var feature = await response.Content.ReadAsJson<FeatureResponse>();
Assert.True(feature.Enabled);
Assert.Equal(nameof(TestFeature), feature.Name);
Assert.Equal("Test feature description.", feature.Description);
}
[Fact]
public async Task GetAll_ReturnsExpectedFeatures()
{
var client = fixture.CreateClient();
var testFeature = new FeatureRequest
{
Name = nameof(TestFeature),
Enabled = true
};
var testFeature2 = new FeatureRequest
{
Name = nameof(TestFeature2),
Enabled = true
};
await SetValueViaApiAsync(testFeature);
await SetValueViaApiAsync(testFeature2);
var uiSettings = fixture.Services.GetRequiredService<FeatureFlagUISettings>();
var response = await client.GetAsync(uiSettings.ApiGetAllPath);
response.EnsureSuccessStatusCode();
var features = (await response.Content.ReadAsJson<IEnumerable<FeatureResponse>>()).ToList();
Assert.Equal(2, features.Count);
Assert.All(features, feature => Assert.True(feature.Enabled));
}
private async Task SetValueViaApiAsync(FeatureRequest featureRequest)
{
var client = fixture.CreateClient();
var uiSettings = fixture.Services.GetRequiredService<FeatureFlagUISettings>();
var response = await client.PostAsync(
uiSettings.ApiSetPath,
new StringContent(JsonConvert.SerializeObject(featureRequest))
);
response.EnsureSuccessStatusCode();
}
private async Task<FeatureResponse> GetFeatureFromApiAsync(string featureName)
{
var client = fixture.CreateClient();
var uiSettings = fixture.Services.GetRequiredService<FeatureFlagUISettings>();
var httpResponse = await client.GetAsync(
$"{uiSettings.ApiGetPath}?feature={featureName}"
);
httpResponse.EnsureSuccessStatusCode();
return await httpResponse.Content.ReadAsJson<FeatureResponse>();
}
[Theory]
[InlineData(null)]
[InlineData(false)]
[InlineData(true)]
public async Task Set_SetsExpectedFeature(bool? expected)
{
var request = new FeatureRequest
{
Name = nameof(TestFeature2),
Enabled = expected
};
await SetValueViaApiAsync(request);
var result = await GetFeatureFromApiAsync(nameof(TestFeature2));
Assert.Equal(expected, result.Enabled);
Assert.Equal(nameof(TestFeature2), result.Name);
Assert.Equal("Test feature 2 description.", result.Description);
}
[Fact]
public async Task UIPath_ReturnsExpectedHtml()
{
var client = fixture.CreateClient();
var uiSettings = fixture.Services.GetRequiredService<FeatureFlagUISettings>();
var response = await client.GetAsync(uiSettings.UIPath);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
Assert.StartsWith("<!DOCTYPE html>", responseString);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TitleScreen : MonoBehaviour {
public AudioClip startGame;
private bool escMenu;
private GameObject escButton;
private StatTracker statTracker;
// Use this for initialization
void Start () {
escButton = GameObject.Find ("Quit");
escButton.SetActive(false);
try{statTracker = GameObject.FindGameObjectWithTag("stat_tracker").GetComponent<StatTracker>();}catch{}
}
// Update is called once per frame
void Update () {
if(Input.GetKey (KeyCode.Escape)){
if(Input.GetKeyDown (KeyCode.Escape)){
escMenu = !escMenu;
escButton.SetActive(escMenu);
}
} else if (!escMenu && (Input.anyKey || Input.GetMouseButton (0) || Input.GetMouseButton (1))){
if(Application.loadedLevelName == "Title"){
transform.gameObject.GetComponent<AudioSource>().PlayOneShot(startGame);
Application.LoadLevel ("Terrain");
} else {
Application.LoadLevel ("Title");
}
}
DisplayStats();
}
private void DisplayStats(){
if(GameObject.Find ("Stats") == null || statTracker == null){
return;
} else {
Text UItext = GameObject.Find ("Stats").GetComponent<Text>();
if(UItext.text == ""){
string newText = "Time Elapsed: "+FormatTime()+"\n";
newText = newText + "Food Consumed: "+statTracker.foodConsumed.ToString ("F1")+"\n";
newText = newText + "Dinos Slain: "+statTracker.dinosKilled.ToString ()+"\n";
newText = newText + "Units Lost: "+statTracker.unitsKilled.ToString ()+"\n";
newText = newText + "Largest Population: "+statTracker.maxUnits.ToString ()+"\n";
if(Application.loadedLevelName == "Lose"){
newText = newText + "\nLord of Rex at "+statTracker.LdinoHealth.ToString ("F0")+"%" ;
}
UItext.text = newText;
}
}
}
private string FormatTime(){
int time = Mathf.RoundToInt(statTracker.time);
// hours
string returnVal = (time/3600).ToString ("00");
// minutes
returnVal = returnVal+":"+ ((time%3600)/60).ToString ("00");
// seconds
returnVal = returnVal+":"+ (time % 60).ToString("00");
return returnVal;
}
public void quitGame(){
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
|
namespace Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class PersonRole : DbMigration
{
public override void Up()
{
CreateTable(
"Web.PersonRoles",
c => new
{
PersonRoleId = c.Int(nullable: false, identity: true),
PersonId = c.Int(nullable: false),
RoleDocTypeId = c.Int(nullable: false),
CreatedBy = c.String(),
ModifiedBy = c.String(),
CreatedDate = c.DateTime(nullable: false),
ModifiedDate = c.DateTime(nullable: false),
OMSId = c.String(maxLength: 50),
})
.PrimaryKey(t => t.PersonRoleId)
.ForeignKey("Web.People", t => t.PersonId)
.ForeignKey("Web.DocumentTypes", t => t.RoleDocTypeId)
.Index(t => new { t.PersonId, t.RoleDocTypeId }, unique: true, name: "IX_PersonRole_DocId");
AddColumn("Web.Stocks", "DocLineId", c => c.Int());
AddColumn("Web.BomDetails", "BaseProcessId", c => c.Int());
AddColumn("Web.DocumentTypeSettings", "DealQtyCaption", c => c.String(maxLength: 50));
AddColumn("Web.DocumentTypeSettings", "WeightCaption", c => c.String(maxLength: 50));
AddColumn("Web.MaterialPlanSettings", "isVisiblePurchPlanQty", c => c.Boolean());
AddColumn("Web.PersonSettings", "DefaultProcessId", c => c.Int());
CreateIndex("Web.BomDetails", "BaseProcessId");
CreateIndex("Web.PersonSettings", "DefaultProcessId");
AddForeignKey("Web.BomDetails", "BaseProcessId", "Web.Processes", "ProcessId");
AddForeignKey("Web.PersonSettings", "DefaultProcessId", "Web.Processes", "ProcessId");
}
public override void Down()
{
DropForeignKey("Web.PersonSettings", "DefaultProcessId", "Web.Processes");
DropForeignKey("Web.PersonRoles", "RoleDocTypeId", "Web.DocumentTypes");
DropForeignKey("Web.PersonRoles", "PersonId", "Web.People");
DropForeignKey("Web.BomDetails", "BaseProcessId", "Web.Processes");
DropIndex("Web.PersonSettings", new[] { "DefaultProcessId" });
DropIndex("Web.PersonRoles", "IX_PersonRole_DocId");
DropIndex("Web.BomDetails", new[] { "BaseProcessId" });
DropColumn("Web.PersonSettings", "DefaultProcessId");
DropColumn("Web.MaterialPlanSettings", "isVisiblePurchPlanQty");
DropColumn("Web.DocumentTypeSettings", "WeightCaption");
DropColumn("Web.DocumentTypeSettings", "DealQtyCaption");
DropColumn("Web.BomDetails", "BaseProcessId");
DropColumn("Web.Stocks", "DocLineId");
DropTable("Web.PersonRoles");
}
}
}
|
using Autofac;
using EmberMemory.Components.Collector;
using EmberMemory.Readers;
using EmberMemory.Readers.Windows;
using EmberMemoryReader.Abstract.Data;
using EmberMemoryReader.Abstract.Events;
namespace EmberMemoryReader.Components.Osu
{
public class OsuMemoryDataCollector : MemoryDataCollector<OsuMemoryDataCollector, OsuProcessMatchedEvent, OsuProcessTerminatedEvent>
{
public OsuMemoryDataCollector(ILifetimeScope scope) : base(scope)
{
}
protected override bool BuildCollectScope(CollectorBuilder builder, OsuProcessMatchedEvent @event)
=> builder
.ReadMemoryWith<WindowsReader>()
.UseOsuProcessEvent(@event)
.UseCollectorManager(manager => manager
.Collect<Beatmap>()
.Collect<GameMode>()
.Collect<GameStatus>()
.Collect<GlobalGameModerator>()
.Collect<Playing>()
.Collect<MultiplayerBeatmapId>()
)
.Build();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GMS;
namespace GMSTest
{
[TestClass]
public class CommonLibTests
{
[TestMethod]
public void AddStudentsToClass_Test()
{
/*
* Test Conditions:
* Grade of Class and Student have to be equal for Student to successfully be added to Class.
*/
// CommonLib
var gms = new CommonLib();
// Objects
var classA = new Class()
{
ClassName = "1A",
Grade = "1",
Students = new List<Student>()
};
var student = new Student()
{
StudentName = "Alfred",
Grade = "1"
};
var studentList = new List<Student> {student};
gms.AddStudentsToClass(studentList, classA);
}
[TestMethod]
public void AddStudentsToGroup_Test()
{
/*
* Test Conditions:
* Students.Count() may not exceed Max Students.
* Grade of both Student and Group need to be equal.
* Student may not be part of group if another group already has same subject
*/
// CommonLib
var gms = new CommonLib();
// Objects
var subject = new Subject()
{
SubjectName = "Maths",
Grade = "2"
};
var group = new Group()
{
GroupName = "Maths 1",
MaxStudents = 2,
Students = new List<Student>(),
Subjects = new List<Subject>() {subject},
Grade = "2"
};
var studentA = new Student()
{
StudentName = "Alfred",
Grade = "2",
Groups = new List<Group>() {},
Subjects = new List<Subject>() {subject}
};
var studentB = new Student()
{
StudentName = "James",
Grade = "2",
Groups = new List<Group>(),
Subjects = new List<Subject>()
};
var studentList = new List<Student> {studentA, studentB};
gms.AddStudentsToGroup(studentList, group);
}
[TestMethod]
public void AddSubjectsToStudents_Test()
{
/*
* Test Conditions:
* Grade of Subject has to be equal to Grade of Student to successfully be added.
*
* - This Unit Test intentionally includes a Grade error in Student Alfred.
*/
// CommonLib
var gms = new CommonLib();
// Objects
var subjectA = new Subject()
{
SubjectName = "Maths",
Grade = "1"
};
var student = new Student()
{
StudentName = "Alfred",
Grade = "1",
Subjects = new List<Subject>()
};
var subjectList = new List<Subject> {subjectA};
gms.AddSubjectsToStudent(subjectList, student);
}
[TestMethod]
public void AddSubjectsToGroup_Test()
{
/*
* Test Conditions:
* Grade of Group and Subject has to be equal for Subject to be added to Group.
*/
// CommonLib
var gms = new CommonLib();
// Objects
var subjectA = new Subject()
{
SubjectName = "Maths",
Grade = "1"
};
var subjectList = new List<Subject> {subjectA};
var group = new Group()
{
Grade = "1",
Subjects = new List<Subject>(),
GroupName = "Maths 1"
};
gms.AddSubjectsToGroup(subjectList, group);
}
[TestMethod]
public void PopulateNewGroup_Test()
{
/*
* Test conditions:
* Check maxStudent and minStudent so they work properly.
*/
// CommonLib
var gms = new CommonLib();
// Objects
var subject = new Subject()
{
SubjectName = "Maths 1",
Grade = "1"
};
var studentA = new Student()
{
StudentName = "Alfred",
Grade = "1",
Subjects = new List<Subject> { subject },
Groups = new List<Group>()
};
var classA = new Class()
{
ClassName = "1A",
Grade = "1",
Students = new List<Student> {studentA}
};
// Variables
var subjectList = new List<Subject> {subject};
var classList = new List<Class> {classA};
var teachers = new List<string> {"Maria", "Anna"};
const int minStudents = 0;
const int maxStudents = 0;
const string groupName = "Maths Group";
gms.PopulateNewGroup(subjectList, minStudents, maxStudents, classList, teachers, groupName);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class UIController : MonoBehaviour
{
[SerializeField] TextMeshProUGUI scoreText;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnGodSaysScoreChanged(int newScore){
scoreText.text = newScore.ToString();
}
}
|
using System;
using System.Collections.Generic;
namespace HelloCSharp
{
class Program
{
//유일하게 하나만있는 특별한 함수, 모든 프로그램이 시작할때 가장먼저 시행되는 함수
//운영체제에 의해서 호출되는 유일한 함수
//Program안에 함수가 여러개 있을 수 있는데, 메인 함수만 운영체제가 직접 호출하고 나머지 함수들은 운영체제가 직접 호출하지 않음
//나머지 함수들은 메인함수에서 프로그래머가 직접 호출
static void Main(string[] args)//함수의 프로토타입, 메인함수가 기능을 하기 위해서는 무언가를 받아야 할 경우가 있음 -> 그걸 받는게 string[] args : 필수는 아님
{
//이안에다가 프로그램을 작성
//콘솔에다 hello world 찍기
//도화지 = Console 안에 .Write 이라는 함수
Console.WriteLine("Hello C#");
Console.WriteLine("Hello " + args[0]);
//Console.ReadKey(); //누가 키보드 칠때까지 기다렸다가 받아라->커서가 깜빡거림
}
//메인이 끝나면 프로그램도 종료
}
} |
using Alabo.Domains.Entities;
using Alabo.Domains.Services;
using Alabo.Framework.Basic.Relations.Domain.Entities;
using Alabo.Framework.Core.Reflections.Interfaces;
using System.Collections.Generic;
namespace Alabo.Framework.Basic.Relations.Domain.Services {
public interface IRelationIndexService : IService<RelationIndex, long> {
/// <summary>
/// 批量更新RealtionIndex
/// 批量更新分类、标签等,包括删除、添加、更新操作
/// </summary>
/// <typeparam name="T">级联类型</typeparam>
/// <param name="entityId">实体Id</param>
/// <param name="relationIds">级联ID字符串,多个Id 用逗号隔开,格式:12,13,14,15</param>
ServiceResult AddUpdateOrDelete<T>(long entityId, string relationIds) where T : class, IRelation;
ServiceResult AddUpdateOrDelete(string fullName, long entityId, string relationIds);
/// <summary>
/// 获取Id字符串列表,返回格式逗号隔开
/// 示列数据:12,13,14,15
/// </summary>
/// <typeparam name="T">级联类型</typeparam>
/// <param name="entityId">实体Id</param>
string GetRelationIds<T>(long entityId) where T : class, IRelation;
/// <summary>
/// 获取Id字符串列表,返回格式逗号隔开
/// 示列数据:12,13,14,15
/// </summary>
/// <typeparam name="T">级联类型</typeparam>
/// <param name="ids">Id标识列表</param>
List<RelationIndex> GetEntityIds(string ids);
/// <summary>
/// 获取Id字符串列表,返回格式逗号隔开(营销活动)
/// </summary>
/// <param name="type"></param>
/// <param name="entityId"></param>
string GetRelationIds(string type, long entityId);
/// <summary>
/// 批量更新RealtionIndex
/// 批量更新分类、标签等,包括删除、添加、更新操作(营销活动)
/// </summary>
/// <typeparam name="T">级联类型</typeparam>
/// <param name="entityId">实体Id</param>
/// <param name="relationIds">级联ID字符串,多个Id 用逗号隔开,格式:12,13,14,15</param>
/// <param name="type"></param>
ServiceResult AddUpdateOrDelete(long entityId, string relationIds, string type);
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.ORD
{
[Serializable]
public partial class TransitOrder : EntityBase
{
#region O/R Mapping Properties
public Int32 Id { get; set; }
[Display(Name = "TransitOrder_OrderNo", ResourceType = typeof(Resources.MRP.TransitOrder))]
public string OrderNo { get; set; }
public Int32 OrderDetailId { get; set; }
[Display(Name = "TransitOrder_IpNo", ResourceType = typeof(Resources.MRP.TransitOrder))]
public string IpNo { get; set; }
[Display(Name = "TransitOrder_Flow", ResourceType = typeof(Resources.MRP.TransitOrder))]
public string Flow { get; set; }
[Display(Name = "TransitOrder_OrderType", ResourceType = typeof(Resources.MRP.TransitOrder))]
public com.Sconit.CodeMaster.OrderType OrderType { get; set; }
[Display(Name = "TransitOrder_Location", ResourceType = typeof(Resources.MRP.TransitOrder))]
public string Location { get; set; }
[Display(Name = "TransitOrder_Item", ResourceType = typeof(Resources.MRP.TransitOrder))]
public string Item { get; set; }
[Display(Name = "TransitOrder_ShippedQty", ResourceType = typeof(Resources.MRP.TransitOrder))]
public Double ShippedQty { get; set; }
[Display(Name = "TransitOrder_ReceivedQty", ResourceType = typeof(Resources.MRP.TransitOrder))]
public Double ReceivedQty { get; set; }
[Display(Name = "TransitOrder_StartTime", ResourceType = typeof(Resources.MRP.TransitOrder))]
public DateTime StartTime { get; set; }
[Display(Name = "TransitOrder_WindowTime", ResourceType = typeof(Resources.MRP.TransitOrder))]
public DateTime WindowTime { get; set; }
[Display(Name = "TransitOrder_SnapTime", ResourceType = typeof(Resources.MRP.TransitOrder))]
public DateTime SnapTime { get; set; }
//public string PartyTo { get; set; }
//public string Uom { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
TransitOrder another = obj as TransitOrder;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
public class RewardSystems : Feature
{
public RewardSystems(Contexts contexts, Services services)
{
Add(new RewardEmitterSystem(contexts));
Add(new ExsplosiveRewardEmitterSystem(contexts));
Add(new ComboRewardEmitterSystem(contexts));
Add(new ApplyRewardSystem(contexts));
}
} |
using NUnit.Framework;
using System.Net;
using static System.Net.WebRequestMethods;
using Newtonsoft.Json;
using System.IO;
using System;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System.Threading;
namespace task3_test
{
public class WeatherResponse
{
public TemperatureInfo Main { get; set; }
public string Name { get; set; }
}
public class TemperatureInfo
{
public float Temp { get; set; }
}
public class Tests
{
private const string city = "Йошкар-Ола"; //город у которого проверяем температуру
private const string url = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&units=metric&appid=178f5dad34cc64066f8482f84262c943";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
private IWebDriver driver;
private readonly By search_field = By.XPath("//input[@placeholder = 'Search city']");
private readonly By search_list = By.XPath("//li[@data-v-12f747a3 = ''][1]");
private readonly By search_button = By.XPath("//button[@data-v-12f747a3 = '']");
private readonly By metric_button = By.XPath("//div[@class = 'option'][1]");
private readonly By temper = By.XPath("//span[@class = 'heading']");
private int d; //градусы полученные на сайте
private int d2; //градусы полученные по API
[SetUp]
public void Setup()
{
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string response;
using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
WeatherResponse weatherResponse = JsonConvert.DeserializeObject<WeatherResponse>(response); //получили город и температуру
driver = new OpenQA.Selenium.Chrome.ChromeDriver();
driver.Navigate().GoToUrl(" https://openweathermap.org/");
var login = driver.FindElement(search_field);
login.SendKeys(city);
Thread.Sleep(1000);
var search = driver.FindElement(search_button);
search.Click();
Thread.Sleep(2000);
var search_city = driver.FindElement(search_list);
search_city.Click();
Thread.Sleep(3000);
var metric = driver.FindElement(metric_button);
metric.Click();
Thread.Sleep(2000);
var temperature_c = driver.FindElement(temper).Text;
string ss = ""; //получаем градусы по Цельсию
foreach (char c in temperature_c)
{
if (c >= '0' && c <= '9')
{
ss = string.Concat(ss, c);
}
else
{
break;
}
}
d = int.Parse(ss);
d2 = (int)weatherResponse.Main.Temp;
driver.Quit();
}
[Test]
public void Test1()
{
Assert.AreEqual(d, d2,"temperature is not correct");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
namespace CRL.Category
{
/// <summary>
/// 分类维护
/// </summary>
public class CategoryBusiness<TType,TModel> : BaseProvider<TModel> where TType : class
where TModel : Category,new()
{
public static CategoryBusiness<TType, TModel> Instance
{
get { return new CategoryBusiness<TType, TModel>(); }
}
protected override DBExtend dbHelper
{
get { return GetDbHelper<TType>(); }
}
public IEnumerable<TModel> GetAllCache(int dataType)
{
return AllCache.Where(b => b.DataType == dataType);
}
public string MakeNewCode(string parentSequenceCode, TModel category)
{
DBExtend helper = dbHelper;
string newCode = parentSequenceCode + "";
#region 生成新编码
var list = QueryList(b => b.ParentCode == parentSequenceCode && b.DataType == category.DataType).OrderByDescending(b => b.SequenceCode).ToList();
if (list.Count() == 0)
{
newCode += "01";
}
else
{
int len = !string.IsNullOrEmpty(parentSequenceCode) ? parentSequenceCode.Length : 0;
string max = list[0].SequenceCode;
max = max.Substring(len, 2);
int n = int.Parse(max);
if (n >= 99)
{
throw new Exception("子级分类已到最大级99");
}
newCode += (n + 1).ToString().PadLeft(2, '0');
}
#endregion
return newCode;
}
/// <summary>
/// 指定父级,添加分类
/// 如果父级为空,则为第一级
/// </summary>
/// <param name="parentSequenceCode"></param>
/// <param name="category"></param>
/// <returns></returns>
public TModel Add(string parentSequenceCode, TModel category)
{
DBExtend helper = dbHelper;
string newCode = MakeNewCode(parentSequenceCode, category);
//helper.Clear();
category.SequenceCode = newCode;
category.ParentCode = parentSequenceCode;
int id = helper.InsertFromObj( category);
category.Id = id;
//ClearCache();
return category;
}
/// <summary>
/// 获取一个分类
/// </summary>
/// <param name="sequenceCode"></param>
/// <param name="type"></param>
/// <returns></returns>
public TModel Get(string sequenceCode, int type)
{
return GetAllCache(type).Where(b => b.SequenceCode == sequenceCode).FirstOrDefault();
}
/// <summary>
/// 指定代码和类型删除
/// 会删除下级
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sequenceCode"></param>
/// <param name="type"></param>
public void Delete(string sequenceCode,int type)
{
Delete(b => (b.SequenceCode == sequenceCode || b.ParentCode == sequenceCode) && b.DataType == type);
ClearCache();
}
/// <summary>
/// 获取子分类
/// </summary>
/// <param name="parentSequenceCode"></param>
/// <param name="type"></param>
/// <returns></returns>
public List<TModel> GetChild(string parentSequenceCode, int type)
{
return GetAllCache(type).Where(b => b.ParentCode == parentSequenceCode).OrderByDescending(b => b.Sort).ToList();
}
/// <summary>
/// 获取所有父级串
/// </summary>
/// <param name="sequenceCode"></param>
/// <param name="type"></param>
/// <returns></returns>
public List<TModel> GetParents(string sequenceCode, int type)
{
List<string> list = new List<string>();
List<TModel> list2 = new List<TModel>();
int i = 0;
while (i <= sequenceCode.Length)
{
list.Add(sequenceCode.Substring(0, i));
i += 2;
}
foreach(string s in list)
{
TModel item = Get(s, type);
if (item != null)
{
list2.Add(item);
}
}
return list2;
}
public string GetSelectOption(IEnumerable<TModel> list, string value)
{
string html = "<option value=''>请选择..</option>";
string[] colorArry = new string[] { "#CCCCFF", "#CCCCCC", "#CCCC99", "#CCCC66", "#CCCC33", "#CCCC00", "#33CCFF", "#33CCCC", "#33CC99", "#33CC66", "#33CC33", "#33CC00" };
foreach (var item in list)
{
int n = item.SequenceCode.Length / 2;
int a = Convert.ToInt32(item.SequenceCode.Substring(0, 2));
string color = "";
if (a < colorArry.Length)
{
color = colorArry[a];
}
string padding = "";
for (int i = 1; i < n; i++)
{
padding += " ";
}
string text = string.Format("{0}{1}", padding, item.Name);
html += string.Format("<option style='background-color:" + color + "' value='{0}' {1}>{2}</option>", item.SequenceCode, item.SequenceCode == value ? "selected" : "", text);
}
return html;
}
}
}
|
using Fingo.Auth.Domain.Infrastructure.Interfaces;
using Fingo.Auth.Domain.Projects.Interfaces;
namespace Fingo.Auth.Domain.Projects.Factories.Interfaces
{
public interface IUpdateProjectFactory : IActionFactory
{
IUpdateProject Create();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Library.Model;
namespace Library.Interfaces
{
public interface IRaceRepository
{
Task AddRace(Race race);
Task<Race> GetRaceByID(int id);
Task<List<Race>> GetRaces();
Task<List<Race>> GetRacesByTitle(string title);
Task UpdateRace(Race race);
Task DeleteRace(Race race);
}
}
|
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class SwordAttackFx : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
UnityAction callback;
public void Init(UnityAction FXoverCallBack)
{
callback = FXoverCallBack;
MoveToPlayer();
}
public void OverCallBack()
{
try
{
callback();
}
catch
{
Debug.Log("FX");
}
Destroy(gameObject);
}
void MoveToPlayer()
{
try
{
Vector3 playerPoint = BattleAreaMgr2.instance.nowPlayerInfo.obj.transform.position;
var tweener=gameObject.transform.DOMove(playerPoint+new Vector3(0,4,0), 1f, false);
tweener.onComplete =()=> { callback(); Destroy(this.gameObject); };
}
catch
{
Debug.Log("MoveToPlayer Error");
}
}
}
|
namespace DistCWebSite.Core.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public partial class CC_CornerstoneSO
{
public int ID { get; set; }
[StringLength(50)]
public string DistributorCode { get; set; }
[StringLength(150)]
public string DistributorName { get; set; }
public int? Amount { get; set; }
public DateTime? Month { get; set; }
}
}
|
using System.Runtime.Serialization;
namespace EpisodeRenaming {
[DataContract]
public class TraktTvShowImagesFanArt {
[DataMember( Name = "full" )]
public string Full { get; set; }
[DataMember( Name = "medium" )]
public string Medium { get; set; }
[DataMember( Name = "thumb" )]
public string Thumb { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using WitsmlExplorer.Api.Jobs;
using WitsmlExplorer.Api.Jobs.Common;
using WitsmlExplorer.Api.Services;
using WitsmlExplorer.Api.Workers;
using Xunit;
namespace WitsmlExplorer.IntegrationTests.Api.Workers
{
public class DeleteCurveValuesWorkerTest
{
private readonly DeleteCurveValuesWorker worker;
public DeleteCurveValuesWorkerTest()
{
var configuration = ConfigurationReader.GetConfig();
var witsmlClientProvider = new WitsmlClientProvider(configuration);
worker = new DeleteCurveValuesWorker(witsmlClientProvider);
}
[Fact(Skip = "Should only be run manually")]
public async Task DeleteCurveValues()
{
var wellUid = "<WellUid>";
var wellboreUid = "<WellboreUid";
var logUid = "<LogUid>";
var mnemonics = new List<string> {"BLOCKPOS", "CHOKE_PRESS", "UKNOWN", "DEPTH_HOLE"};
var indexRanges = new List<IndexRange>
{
new IndexRange
{
StartIndex = new DateTime(2019, 11, 20).ToString(CultureInfo.InvariantCulture),
EndIndex = new DateTime(2019, 11, 28).ToString(CultureInfo.InvariantCulture)
}
};
var job = new DeleteCurveValuesJob
{
LogReference = new LogReference
{
WellUid = wellUid,
WellboreUid = wellboreUid,
LogUid = logUid
},
Mnemonics = mnemonics,
IndexRanges = indexRanges
};
var (result, _) = await worker.Execute(job);
Assert.True(result.IsSuccess, result.Reason);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ISE.UILibrary;
using ISE.ClassLibrary;
using ISE.SM.Common.DTO;
using ISE.SM.Client.View;
using ISE.Framework.Utility.Utils;
namespace ISE.SM.Client.UCEntry
{
public partial class UCResourceEntry : IUserControl
{
public DialogResult DialogResult { get; set; }
public SecurityResourceDto SecurityResource { get; set; }
TransMode mode;
public UCResourceEntry()
{
this.DialogResult = System.Windows.Forms.DialogResult.None;
InitializeComponent();
}
public UCResourceEntry(TransMode mode,SecurityResourceDto resource)
{
this.SecurityResource = resource;
InitializeComponent();
this.mode = mode;
this.DialogResult = System.Windows.Forms.DialogResult.None;
if (mode == TransMode.ViewRecord || mode == TransMode.EditRecord)
{
txtDisplayName.Text = resource.DisplayName;
txtResourceName.Text = resource.ResourceName;
txtNameSpace.Text = resource.Namespace;
txtAssemblyName.Text = resource.AssemblyName;
txtTooltip.Text = resource.ToolTip;
txtPrecedence.Text = resource.Precedence.ToString();
chkHasParam.Checked = resource.HasParam;
chkEnabled.Checked = resource.IsEnabled;
}
}
private void iTransToolBar1_Close(object sender, EventArgs e)
{
this.ParentForm.Close();
}
private int GetResourceType()
{
if (rdMenuItem.Checked)
{
return (int)ISE.SM.Client.UC.UCResource.MenuType.MenuItem;
}
return 0;
}
private void iTransToolBar1_SaveRecord_1(object sender, EventArgs e)
{
int precedens = 0;
int.TryParse(txtPrecedence.Text, out precedens);
short hasParam = 0;
if (chkHasParam.Checked)
hasParam = 1;
if (mode == TransMode.EditRecord || mode == TransMode.ViewRecord)
{
if (SecurityResource != null)
{
SecurityResource.DisplayName = txtDisplayName.Text;
SecurityResource.ResourceName = txtResourceName.Text;
SecurityResource.Namespace = txtNameSpace.Text;
SecurityResource.AssemblyName = txtAssemblyName.Text;
SecurityResource.ToolTip = txtTooltip.Text;
SecurityResource.Precedence = precedens;
SecurityResource.HasParam = chkHasParam.Checked;
SecurityResource.IsEnabled = chkEnabled.Checked;
DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
else
{
SecurityResourceDto rec = new SecurityResourceDto()
{
AssemblyName = txtAssemblyName.Text,
DisplayName = txtDisplayName.Text,
IsEnabled = chkEnabled.Checked,
ResourceName = txtResourceName.Text,
Namespace = txtNameSpace.Text,
ToolTip = txtTooltip.Text,
Precedence = precedens,
ResourceTypeId = GetResourceType(),
HasParameter=hasParam
};
SecurityResource = rec;
DialogResult = System.Windows.Forms.DialogResult.OK;
}
this.ParentForm.Close();
}
private void iTransToolBar1_Close_1(object sender, EventArgs e)
{
this.ParentForm.Close();
}
}
}
|
using System;
using IrsMonkeyApi.Models.DAL;
using Microsoft.AspNetCore.Mvc;
namespace IrsMonkeyApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ItemsController : Controller
{
private readonly IProductItemDal _dal;
public ItemsController(IProductItemDal dal)
{
_dal = dal;
}
[Route("GetProduct/{id}"), HttpGet]
public IActionResult Index(int id)
{
try
{
var products = _dal.GetProductItems(id);
return products != null ? (IActionResult) Ok(products) : NoContent();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
} |
using System.Collections.Generic;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace App.Web.AsyncApi
{
public class AsyncApiGenOptions
{
public AsyncApiGeneratorOptions AsyncApiGeneratorOptions { get; set; } = new AsyncApiGeneratorOptions();
public SchemaRegistryOptions SchemaRegistryOptions { get; set; } = new SchemaRegistryOptions();
public List<FilterDescriptor> SchemaFilterDescriptors { get; set; } = new List<FilterDescriptor>();
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace SOLID._2___OCP.Violacao
{
public class DebitoConta
{
public void Debitar(decimal valor, string numeroConta, TipoConta tipoConta)
{
if (tipoConta == TipoConta.Corrente)
{
// Debitar da Conta Corrente
}
if (tipoConta == TipoConta.Poupanca)
{
// Debitar da Conta Poupança
}
}
}
}
|
// Copyright (c) 2020, mParticle, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
namespace MP.Json.Validation
{
/// <summary>
/// Standard schema Keywords recognized by the Schema object
/// </summary>
public static class KeywordUtils
{
#region Variables
private static readonly Dictionary<Keyword, string> keyword2Name
= new Dictionary<Keyword, string>()
{
[Keyword.Metadata] = "<metadata>",
[Keyword.None] = "<none>"
};
private static readonly Dictionary<string, Keyword> name2Keyword
= name2Keyword = new Dictionary<string, Keyword>()
{
["additionalItems"] = Keyword.AdditionalItems,
["additionalProperties"] = Keyword.AdditionalProperties,
["allOf"] = Keyword.AllOf,
["anyOf"] = Keyword.AnyOf,
["$comment"] = Keyword._Comment,
["const"] = Keyword.Const,
["contains"] = Keyword.Contains,
["contentEncoding"] = Keyword.ContentEncoding,
["contentMediaType"] = Keyword.ContentMediaType,
["contentSchema"] = Keyword.ContentSchema,
["default"] = Keyword.Default,
["definitions"] = Keyword.Definitions,
["$defs"] = Keyword._Defs,
["dependencies"] = Keyword.Dependencies,
["dependentRequired"] = Keyword.DependentRequired,
["dependentSchemas"] = Keyword.DependentSchemas,
["deprecated"] = Keyword.Deprecated,
["description"] = Keyword.Description,
["else"] = Keyword.Else,
["enum"] = Keyword.Enum,
["examples"] = Keyword.Examples,
["exclusiveMaximum"] = Keyword.ExclusiveMaximum,
["exclusiveMinimum"] = Keyword.ExclusiveMinimum,
["format"] = Keyword.Format,
["id"] = Keyword.Id,
["$id"] = Keyword._Id,
["if"] = Keyword.If,
["items"] = Keyword.Items,
["maxContains"] = Keyword.MaxContains,
["maximum"] = Keyword.Maximum,
["maxLength"] = Keyword.MaxLength,
["maxProperties"] = Keyword.MaxProperties,
["maxItems"] = Keyword.MaxItems,
["minContains"] = Keyword.MinContains,
["minimum"] = Keyword.Minimum,
["minItems"] = Keyword.MinItems,
["minLength"] = Keyword.MinLength,
["minProperties"] = Keyword.MinProperties,
["multipleOf"] = Keyword.MultipleOf,
["not"] = Keyword.Not,
["oneOf"] = Keyword.OneOf,
["pattern"] = Keyword.Pattern,
["patternProperties"] = Keyword.PatternProperties,
["properties"] = Keyword.Properties,
["propertyNames"] = Keyword.PropertyNames,
["readOnly"] = Keyword.ReadOnly,
["$recursiveAnchor"] = Keyword._RecursiveAnchor,
["$recursiveRef"] = Keyword._RecursiveRef,
["$ref"] = Keyword._Ref,
["required"] = Keyword.Required,
["$schema"] = Keyword._Schema,
["then"] = Keyword.Then,
["title"] = Keyword.Title,
["type"] = Keyword.Type,
["uniqueItems"] = Keyword.UniqueItems,
["writeOnly"] = Keyword.WriteOnly,
};
#endregion
#region Constructor
static KeywordUtils()
{
foreach (var v in name2Keyword)
keyword2Name[v.Value] = v.Key;
}
#endregion
public static string GetText(this Keyword keyword, SchemaVersion draft=0)
{
return GetTextCore(keyword, draft)
?? KeywordCase(keyword.ToString());
}
public static string GetText(this ErrorType keyword, SchemaVersion draft = 0)
{
return GetTextCore((Keyword)keyword, draft)
?? KeywordCase(keyword.ToString());
}
private static string GetTextCore(Keyword keyword, SchemaVersion draft = 0)
{
if (draft == 0)
{
// We default to Draft7,
// since later drafts introduces/replaces a number of keywords
// and might not readable by earlier versions
// but earlier drafts may be readable by later drafts
draft = SchemaVersion.Draft7;
}
switch (keyword)
{
case Keyword.DependentSchemas:
case Keyword.DependentRequired:
if (draft < SchemaVersion.Draft201909)
return "dependencies";
break;
}
keyword2Name.TryGetValue(keyword, out string result);
return result;
}
private static string KeywordCase(string keyword)
{
var sb = new StringBuilder(keyword);
if (sb[0] != '_')
sb[0] = char.ToLower(sb[0]);
else
{
sb[0] = '$';
sb[1] = char.ToLower(sb[1]);
}
return sb.ToString();
}
public static string GetTypeText(JsonType type)
{
switch(type)
{
case JsonType.Array: return "array";
case JsonType.Boolean: return "boolean";
case JsonType.Number: return "number";
case JsonType.Null: return "null";
case JsonType.Object: return "object";
case JsonType.String: return "string";
case JsonType.Undefined: return "undefined";
}
return "unknown";
}
public static Keyword ParseKeyword(string text)
=> name2Keyword.TryGetValue(text, out Keyword result) ? result : Keyword.None;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static TypeFlags SchemaFlagsToTypeFlags(SchemaFlags flags)
{
return (TypeFlags)((long)(flags & SchemaFlags.TypeAll) >> 56);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static SchemaFlags TypeFlagsToSchemaFlags(TypeFlags flags)
{
return (SchemaFlags)((long)(flags) << 56);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DistCWebSite.Core.Entities;
namespace DistCWebSite.Infrastructure
{
public class ActivityConfigRespository
{
#region
public int Add(List<M_ActivityConfig> list)
{
var ctx = new DistCSiteContext();
ctx.M_ActivityConfig.AddRange(list);
return ctx.SaveChanges();
}
public int Delete(M_ActivityConfig entity)
{
var ctx = new DistCSiteContext();
ctx.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
return ctx.SaveChanges();
}
/// <summary>
/// 获取流程审批人状态
/// </summary>
/// <param name="procinstID">流程ID</param>
/// <param name="ret">获取的是否是审批完成的</param>
/// <returns></returns>
public List<M_ActivityConfig> Get(int procinstID,bool ret)
{
var ctx = new DistCSiteContext();
return ctx.M_ActivityConfig.Where(x => x.Active == ret && x.ProcInstID== procinstID).ToList();
}
public List<M_ActivityConfig> Get(int procinstID)
{
var ctx = new DistCSiteContext();
return ctx.M_ActivityConfig.Where(x=>x.ProcInstID == procinstID).ToList();
}
public List<M_ActivityConfig> Get(string originatorLoginID, int procinstID)
{
var ctx = new DistCSiteContext();
return ctx.M_ActivityConfig.Where(x => x.Active == true && x.OriginatorLoginID == originatorLoginID&&x.ProcInstID== procinstID).ToList();
}
public int Update(M_ActivityConfig entity)
{
var ctx = new DistCSiteContext();
ctx.Entry(entity).State = System.Data.Entity.EntityState.Modified;
return ctx.SaveChanges();
}
#endregion
}
}
|
using System.ComponentModel;
namespace Podemski.Musicorum.Core.Enums
{
public enum AlbumVersion
{
[Description("---")]
None,
[Description("Cyfrowa")]
Digital,
[Description("Fizyczna")]
Physical
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SAAS.FrameWork.Util.Common
{
public static class DateTimeHelper
{
public static string TimeDiff(DateTime? DateTime1, DateTime? DateTime2)
{
if (DateTime1 == null || DateTime2 == null) return "";
TimeSpan ts = DateTime2.Value - DateTime1.Value;
return //ts.Days + "天"+
ts.Hours + "小时"
+ ts.Minutes + "分钟"
+ ts.Seconds + "秒";
}
///// <summary>
///// 已重载.计算两个日期的时间间隔,返回的是时间间隔的日期差的绝对值.
///// </summary>
///// <param name="DateTime1">第一个日期和时间</param>
///// <param name="DateTime2">第二个日期和时间</param>
///// <returns></returns>
//public static string DateDiff(DateTime? DateTime1, DateTime? DateTime2)
//{
// string dateDiff = null;
// try
// {
// TimeSpan ts1 = new TimeSpan(DateTime1.Value.Ticks);
// TimeSpan ts2 = new TimeSpan(DateTime2.Value.Ticks);
// TimeSpan ts = ts1.Subtract(ts2).Duration();
// dateDiff = ts.Days.ToString() + "天"
// + ts.Hours.ToString() + "小时"
// + ts.Minutes.ToString() + "分钟"
// + ts.Seconds.ToString() + "秒";
// }
// catch
// {
// }
// return dateDiff;
//}
///// <summary>
///// 已重载.计算两个日期的时间间隔,返回的是时间间隔的日期差的绝对值.
///// </summary>
///// <param name="DateTime1">第一个日期和时间</param>
///// <param name="DateTime2">第二个日期和时间</param>
///// <returns></returns>
//public static string DateDiffHour(DateTime? DateTime1, DateTime? DateTime2)
//{
// string dateDiff = null;
// try
// {
// TimeSpan ts1 = new TimeSpan(DateTime1.Value.Ticks);
// TimeSpan ts2 = new TimeSpan(DateTime1.Value.Ticks);
// TimeSpan ts = ts1.Subtract(ts2).Duration();
// dateDiff = (ts.Hours + ts.Days * 24).ToString() + ":"
// + ts.Minutes.ToString() + ":"
// + ts.Seconds.ToString() + "";
// }
// catch
// {
// }
// return dateDiff;
//}
/// <summary>
/// 返回两个时间的分钟差
/// </summary>
/// <param name="DateTime1">第一个日期和时间</param>
/// <param name="DateTime2">第二个日期和时间</param>
/// <returns></returns>
//public static double DateDiffTotalMin(DateTime DateTime1, DateTime DateTime2)
//{
// double dateDiff = 0;
// try
// {
// TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
// TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
// TimeSpan ts = ts1.Subtract(ts2).Duration();
// dateDiff = ts.TotalMinutes;
// }
// catch
// {
// }
// return dateDiff;
//}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PauseAction : MonoBehaviour
{
public GameObject painelPaused;
public GameObject gameManager;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void Sair()
{
Time.timeScale = 1;
Application.LoadLevel("SampleScene");
}
public void Continuar()
{
gameManager.GetComponent<GameManager>().isPaused = false;
painelPaused.SetActive(false);
Time.timeScale = 1;
}
public void Configuracoes()
{
}
}
|
using UnityEngine;
namespace AtomosZ.Cubeshots.AudioTools
{
public class AudioSpectrum : MonoBehaviour
{
/// <summary>
/// Audio Spectrum
/// Deep Bass: 0Hz to 60Hz
/// Bass: 60Hz to 250Hz
/// Low Midrange: 250Hz to 500Hz
/// Midrange: 500Hz to 2000Hz
/// Upper Midrange: 2000Hz to 4000Hz
/// Presence: 4000Hz to 6000Hz
/// Brilliance: 6000Hz to 20000Hz
/// </summary>
public static float[] spectrumBandValues;
private System.Tuple<int, int> bassBand;
private System.Tuple<int, int> lowMidBand;
private System.Tuple<int, int> midBand;
private System.Tuple<int, int> upperMidBand;
private System.Tuple<int, int> presenceBand;
private System.Tuple<int, int> brillianceBand;
public enum SpectrumBand
{
Bass,
LowMidRange,
MidRange,
UpperMidRange,
Presence,
Brilliance,
}
[Tooltip("Must be a power of 2")]
[Range(64, 8192)]
public int spectrumSize = 128;
public int spectrumMultiplier = 100;
private float[] audioSpectrum;
void Start()
{
audioSpectrum = new float[spectrumSize];
float hertzPerBand = AudioSettings.outputSampleRate * .5f / spectrumSize;
spectrumBandValues = new float[System.Enum.GetNames(typeof(SpectrumBand)).Length];
bassBand = new System.Tuple<int, int>(0, (int)(250 / hertzPerBand));
lowMidBand = new System.Tuple<int, int>((int)(251 / hertzPerBand), (int)(500 / hertzPerBand));
midBand = new System.Tuple<int, int>((int)(501 / hertzPerBand), (int)(2000 / hertzPerBand));
upperMidBand = new System.Tuple<int, int>((int)(2001 / hertzPerBand), (int)(4000 / hertzPerBand));
presenceBand = new System.Tuple<int, int>((int)(4001 / hertzPerBand), (int)(6000 / hertzPerBand));
brillianceBand = new System.Tuple<int, int>((int)(6001 / hertzPerBand),
(int)(AudioSettings.outputSampleRate * .5f / hertzPerBand));
}
private Vector3 dotSize = new Vector3(.1f, .1f);
void OnDrawGizmos()
{
if (audioSpectrum != null)
{
for (int i = 0; i < audioSpectrum.Length; ++i)
{
Gizmos.DrawCube(new Vector3(i * .1f, audioSpectrum[i] * spectrumMultiplier, 0), dotSize);
}
}
}
void Update()
{
AudioListener.GetSpectrumData(audioSpectrum, 0, FFTWindow.Hamming);
if (audioSpectrum != null && audioSpectrum.Length > 0)
{
spectrumBandValues[(int)SpectrumBand.Bass] = GetHighestIn(bassBand) * spectrumMultiplier;
spectrumBandValues[(int)SpectrumBand.LowMidRange] = GetHighestIn(lowMidBand) * spectrumMultiplier;
spectrumBandValues[(int)SpectrumBand.MidRange] = GetHighestIn(midBand) * spectrumMultiplier;
spectrumBandValues[(int)SpectrumBand.UpperMidRange] = GetHighestIn(upperMidBand) * spectrumMultiplier;
spectrumBandValues[(int)SpectrumBand.Presence] = GetHighestIn(presenceBand) * spectrumMultiplier;
spectrumBandValues[(int)SpectrumBand.Brilliance] = GetHighestIn(brillianceBand) * spectrumMultiplier;
}
}
private float GetHighestIn(System.Tuple<int, int> bandLimits)
{
float highest = 0;
for (int i = bandLimits.Item1; i < bandLimits.Item2; ++i)
if (audioSpectrum[i] > highest)
highest = audioSpectrum[i];
return highest;
}
private float GetAverageIn(System.Tuple<int, int> bandLimits)
{
float sum = 0;
for (int i = bandLimits.Item1; i < bandLimits.Item2; ++i)
{
sum += audioSpectrum[i];
}
return sum / (bandLimits.Item2 - bandLimits.Item1 - 1);
}
private void OnValidate()
{
if ((spectrumSize & (spectrumSize - 1)) != 0)
{
spectrumSize = (int)Mathf.Pow(2, Mathf.Round(Mathf.Log(spectrumSize) / Mathf.Log(2)));
}
}
}
} |
namespace LiveCode.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Meteorology")]
public partial class Meteorology
{
[Key]
public int Meteorology_Id { get; set; }
[Column(TypeName = "date")]
public DateTime? DateTimeStart { get; set; }
public double? WindDirection { get; set; }
public double? WindSpeed { get; set; }
public double? Temperature { get; set; }
public double? Humidity { get; set; }
public double? Radiation { get; set; }
public double? Pressure { get; set; }
}
}
|
using UnityEngine;
public class TestCube : MonoBehaviour
{
public float Speed = 1.0f;
void Update()
{
transform.Rotate( Vector3.up, 360.0f * Time.deltaTime * Speed );
}
private void OnMouseDown()
{
Debug.Log( "Cube clicked" );
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplicationBlog_DejanSavanovic.DBModels;
using WebApplicationBlog_DejanSavanovic.Models;
namespace WebApplicationBlog_DejanSavanovic.Controllers
{
public class PocetnaController : Controller
{
public ActionResult Index()
{
using (var context = new BlogContext())
{
var pocetnaViewModel = new PocetnaViewModel()
{
Drzave = context.Drzavas
.Select(d => new SelectListItem()
{
Text = d.Naziv,
Value = "" + d.DrzavaId
}).ToList(),
TopPetBlogova = context.Blogs.Where(b => b.Odobren == true)
.Select(b => new TopPetBlogovaViewModel()
{
Naslov = b.Naslov,
BrojSvidjanja = b.Korisniks.Count()
}).OrderByDescending(p => p.BrojSvidjanja).Take(5).ToList(),
TopPetAutora = context.Korisniks.Where(k => k.Blogs.Count != 0)
.Select(k => new TopPetAutoraViewModel()
{
KorisnickoIme = k.KorisnickoIme,
BrojSvidjanja = k.Blogs.ToList().Where(b => b.Korisniks.Count != 0).Sum(b => b.Korisniks.Count)
}).OrderByDescending(a => a.BrojSvidjanja).Take(5).ToList()
};
pocetnaViewModel.Drzave.Insert(0, new SelectListItem() { Text = "Drzava", Value = "-1" });
return View(pocetnaViewModel);
}
}
public PartialViewResult Pretraga(string tekstPretraga, string drzavaID)
{
using(var context = new BlogContext())
{
var drzavaId = Convert.ToInt32(drzavaID);
var odobreniBlogovi = context.Blogs
.Where(b => b.Odobren == true && (tekstPretraga.Trim() == "" || b.Naslov.Contains(tekstPretraga)) &&
(drzavaId == -1 || b.DrzavaId == drzavaId))
.Select(b => new OdobreniBlogoviViewModel()
{
BlogId = b.BlogId,
DatumKreiranja = b.DatumKreiranja,
Naslov = b.Naslov,
NaslovSlikaLink = b.NaslovnaSlikaLink,
KorisnickoIme = b.Korisnik.KorisnickoIme
}).ToList();
return PartialView("_OdobreniBlogovi", odobreniBlogovi);
}
}
[AllowAnonymous]
public JsonResult PromijeniJezik(string lang)
{
HttpCookie myCookie = new HttpCookie("Jezik");
DateTime now = DateTime.Now;
myCookie.Value = lang;
myCookie.Expires = now.AddMonths(10);
Response.Cookies.Add(myCookie);
return Json(new { Success = true });
}
}
} |
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine.Networking;
[Serializable]
public abstract class AbstractSkill : NetworkBehaviour
{
public SkillProperties properties { get; protected set; }
public bool isUse;
public List<AbstractSkillUse> next { get; protected set; }
public int id { get; protected set; }
public int playerId { get; protected set; }
[NonSerialized]
public GameObject effect;
[NonSerialized]
public GameObject dagameEffect;
[NonSerialized]
public GameObject destroyDagame;
[NonSerialized]
public List<GameObject> players;
public bool destroyOnGamage { get; protected set; }
public Vector3 target { get; set; }
public Vector3 move { get; set; }
public delegate void onGamageCount(int count);
public delegate void onKillCount(int count);
public abstract void Destroy();
public abstract void StartUse(SkillProperties properties, Vector3 target, Vector3 start, int playerId);
}
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Holds a Character's Attributes, is Serializable
/// </summary>
[System.Serializable]
public class CharacterStats{
[SerializeField]
private int maxHealth;
[SerializeField]
private int health;
[SerializeField]
private float movementSpeed;
private bool shield = false;
public bool Shield
{
get { return shield; }
set { shield = value; }
}
public CharacterStats()
{
MaxHealth = 0;
Health = 0;
MovementSpeed = 0;
}
public CharacterStats(int health, int maxHealh, float movementSpeed)
{
MaxHealth = health;
Health = maxHealth;
MovementSpeed = movementSpeed;
}
public int MaxHealth
{
get
{
return maxHealth;
}
set
{
maxHealth = value;
}
}
public int Health
{
get
{
return health;
}
set
{
health = value;
}
}
public float MovementSpeed
{
get
{
return movementSpeed;
}
set
{
movementSpeed = value;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _7DRL_2021
{
public static class LerpHelper
{
public delegate double Delegate(double a, double b, double amt);
public static Delegate Invert(this Delegate lerp)
{
return (a, b, amt) => lerp(b, a, amt);
}
public static Delegate ForwardReverse(float start, float end, Delegate lerpStart, Delegate lerpEnd)
{
return (a, b, amt) => ForwardReverse(a, b, amt, start, end, lerpStart, lerpEnd);
}
public static double ForwardReverse(double a, double b, double amt)
{
if (amt < 0.5)
return Linear(a, b, amt * 2);
else
return Linear(b, a, (amt - 0.5) * 2);
}
public static double ForwardReverse(double a, double b, double amt, float start, float end, Delegate lerpStart, Delegate lerpEnd)
{
if (amt < start)
return lerpStart(a, b, Util.ReverseLerp(amt, 0, start));
else if (amt < end)
return b;
else
return lerpEnd(b, a, Util.ReverseLerp(amt, end, 1));
}
public static double Flick(double a, double b, double amt)
{
if (amt < 1)
return a;
else
return b;
}
public static double Linear(double a, double b, double amt)
{
return a * (1 - amt) + b * amt;
}
public static double QuadraticIn(double a, double b, double amt)
{
return Linear(a, b, amt * amt);
}
public static double QuadraticOut(double a, double b, double amt)
{
return Linear(a, b, 1 - (amt - 1) * (amt - 1));
}
public static double Quadratic(double a, double b, double amt)
{
amt *= 2;
if (amt < 1)
return Linear(a, b, 0.5 * amt * amt);
else
return Linear(a, b, -0.5 * ((amt - 1) * (amt - 3) - 1));
}
public static double CubicIn(double a, double b, double amt)
{
return Linear(a, b, amt * amt * amt);
}
public static double CubicOut(double a, double b, double amt)
{
return Linear(a, b, 1 + (amt - 1) * (amt - 1) * (amt - 1));
}
public static double Cubic(double a, double b, double amt)
{
amt *= 2;
if (amt < 1)
return Linear(a, b, 0.5 * amt * amt * amt);
else
return Linear(a, b, 0.5 * ((amt - 2) * (amt - 2) * (amt - 2) + 2));
}
public static double QuarticIn(double a, double b, double amt)
{
return Linear(a, b, amt * amt * amt * amt);
}
public static double QuarticOut(double a, double b, double amt)
{
return Linear(a, b, 1 - (amt - 1) * (amt - 1) * (amt - 1) * (amt - 1));
}
public static double Quartic(double a, double b, double amt)
{
amt *= 2;
if (amt < 1)
return Linear(a, b, 0.5 * amt * amt * amt * amt);
else
return Linear(a, b, -0.5 * ((amt - 2) * (amt - 2) * (amt - 2) * (amt - 2) - 2));
}
public static double QuinticIn(double a, double b, double amt)
{
return Linear(a, b, amt * amt * amt * amt * amt);
}
public static double QuinticOut(double a, double b, double amt)
{
return Linear(a, b, 1 + (amt - 1) * (amt - 1) * (amt - 1) * (amt - 1) * (amt - 1));
}
public static double Quintic(double a, double b, double amt)
{
amt *= 2;
if (amt < 1)
return Linear(a, b, 0.5 * amt * amt * amt * amt * amt);
else
return Linear(a, b, 0.5 * ((amt - 2) * (amt - 2) * (amt - 2) * (amt - 2) * (amt - 2) + 2));
}
public static double SineIn(double a, double b, double amt)
{
return Linear(a, b, 1 - Math.Cos(amt * Math.PI / 2));
}
public static double SineOut(double a, double b, double amt)
{
return Linear(a, b, Math.Sin(amt * Math.PI / 2));
}
public static double Sine(double a, double b, double amt)
{
return Linear(a, b, 0.5 * (1 - Math.Cos(amt * Math.PI)));
}
public static double ExponentialIn(double a, double b, double amt)
{
if (amt <= 0)
return a;
if (amt >= 1)
return b;
return Linear(a, b, Math.Pow(1024, amt - 1));
}
public static double ExponentialOut(double a, double b, double amt)
{
if (amt <= 0)
return a;
if (amt >= 1)
return b;
return Linear(a, b, 1 - Math.Pow(2, -10 * amt));
}
public static double Exponential(double a, double b, double amt)
{
if (amt <= 0)
return a;
if (amt >= 1)
return b;
amt *= 2;
if (amt < 1)
return Linear(a, b, 0.5 * Math.Pow(1024, amt - 1));
else
return Linear(a, b, -0.5 * Math.Pow(2, -10 * (amt - 1)) + 1);
}
public static double CircularIn(double a, double b, double amt)
{
return Linear(a, b, 1 - Math.Sqrt(1 - amt * amt));
}
public static double CircularOut(double a, double b, double amt)
{
return Linear(a, b, Math.Sqrt(1 - (amt - 1) * (amt - 1)));
}
public static double Circular(double a, double b, double amt)
{
amt *= 2;
if (amt < 1)
return Linear(a, b, -0.5 * (Math.Sqrt(1 - amt * amt) - 1));
else
return Linear(a, b, 0.5 * (Math.Sqrt(1 - (amt - 2) * (amt - 2)) + 1));
}
public static double ElasticIn(double a, double b, double amt)
{
return ElasticInCustom(a, b, 0.1, 0.4, amt);
}
public static double ElasticInCustom(double a, double b, double k, double p, double amt)
{
if (amt <= 0)
return a;
if (amt >= 1)
return b;
double s;
if (k < 1)
{
k = 1;
s = p / 4;
}
else
{
s = p * Math.Asin(1 / k) / (Math.PI * 2);
}
return Linear(a, b, -k * Math.Pow(2, 10 * (amt - 1)) * Math.Sin(((amt - 1) - s) * (2 * Math.PI) / p));
}
public static double ElasticOut(double a, double b, double amt)
{
return ElasticOutCustom(a, b, 0.1, 0.4, amt);
}
public static double ElasticOutCustom(double a, double b, double k, double p, double amt)
{
if (amt <= 0)
return a;
if (amt >= 1)
return b;
double s;
if (k < 1)
{
k = 1;
s = p / 4;
}
else
{
s = p * Math.Asin(1 / k) / (Math.PI * 2);
}
return Linear(a, b, k * Math.Pow(2, -10 * amt) * Math.Sin((amt - s) * (2 * Math.PI) / p) + 1);
}
public static double Elastic(double a, double b, double amt)
{
return ElasticCustom(a, b, 0.1, 0.4, amt);
}
public static double ElasticCustom(double a, double b, double k, double p, double amt)
{
if (amt <= 0)
return a;
if (amt >= 1)
return b;
double s;
if (k < 1)
{
k = 1;
s = p / 4;
}
else
{
s = p * Math.Asin(1 / k) / (Math.PI * 2);
}
amt *= 2;
if (amt < 1)
return Linear(a, b, -0.5 * k * Math.Pow(2, 10 * (amt - 1)) * Math.Sin(((amt - 1) - s) * (2 * Math.PI) / p));
else
return Linear(a, b, 0.5 * k * Math.Pow(2, -10 * (amt - 1)) * Math.Sin(((amt - 1) - s) * (2 * Math.PI) / p) + 1);
}
public static double BackIn(double a, double b, double amt) => BackInCustom(a, b, 1.7f, amt);
public static double BackInCustom(double a, double b, double c, double amt)
{
if (amt <= 0)
return a;
if (amt >= 1)
return b;
return (c + 1) * amt * amt * amt;
}
public static double BackOut(double a, double b, double amt) => BackOutCustom(a, b, 1.7f, amt);
public static double BackOutCustom(double a, double b, double c, double amt)
{
if (amt <= 0)
return a;
if (amt >= 1)
return b;
return 1 + (c + 1) * Math.Pow(amt - 1, 3) + c * Math.Pow(amt - 1, 2);
}
}
}
|
/* Menu.cs
* Author: Easton Bolinger
* Purpose: to implement the static methods listed in the directions
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Collections;
namespace CowboyCafe.Data
{
public static class Menu
{
/// <summary>
/// the method populates the IEnumerable for the entrees
/// </summary>
/// <returns>IEnumerable list full of entrees</returns>
public static IEnumerable<IOrderItem> Entrees()
{
List<Entree> order = new List<Entree>();
order.Add(new AngryChicken());
order.Add(new CowpokeChili());
order.Add(new TrailBurger());
order.Add(new DakotaDoubleBurger());
order.Add(new TexasTripleBurger());
order.Add(new PecosPulledPork());
order.Add(new RustlersRibs());
IEnumerable<IOrderItem> EntreeOrder = order.AsEnumerable();
return EntreeOrder;
}
/// <summary>
/// This method populates the IEnumberable for the sides
/// </summary>
/// <returns>IEnumerable full of sides</returns>
public static IEnumerable<IOrderItem> Sides()
{
List<Side> order = new List<Side>();
order.Add(new BakedBeans());
order.Add(new ChiliCheeseFries());
order.Add(new CornDodgers());
order.Add(new PanDeCampo());
IEnumerable<IOrderItem> SideOrder = order.AsEnumerable();
return SideOrder;
}
/// <summary>
/// This method populates the IEnumerable for the drinks
/// </summary>
/// <returns>IEnumerable full of drinks</returns>
public static IEnumerable<IOrderItem> Drinks()
{
List<Drink> order = new List<Drink>();
order.Add(new CowboyCoffee());
order.Add(new JerkedSoda());
order.Add(new TexasTea());
order.Add(new Water());
IEnumerable<IOrderItem> DrinkOrder = order.AsEnumerable();
return DrinkOrder;
}
/// <summary>
/// this compiles a complete list of all items on the menu
/// </summary>
/// <returns></returns>
public static IEnumerable<IOrderItem> CompleteOrder()
{
List<IEnumerable<IOrderItem>> order = new List<IEnumerable<IOrderItem>>();
order.Add(Entrees());
order.Add(Drinks());
order.Add(Sides());
IEnumerable<IOrderItem> completeOrder = order.AsEnumerable();
return completeOrder;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class ZombieSpawn
{
public Transform SpawnPoint;
public GameObject ZombieToSpawn;
public ZombieSpawn(Transform pSpawnPoint, GameObject pZombieToSpawn)
{
SpawnPoint = pSpawnPoint;
ZombieToSpawn = pZombieToSpawn;
}
}
public enum WaveType
{
TIME_BASED = 0,
PROXIMITY_BASED = 1,
KILL_ALL_ZOMBIES = 2
}
[System.Serializable]
public class ZombieWave
{
public GameObject Waypoints;
public string waveNum;
public List<ZombieSpawn> ZombieSpawns;
public bool PlayInterstitalAfterWave;
public Conversation InterstitalToPlay;
public WaveType WaveType;
[DrawIf("WaveType", WaveType.TIME_BASED)]
public float timeTillNextWave;
}
public class ZombieWavesSpawner : ZombieBaseSpawner
{
private int currentWave = -1;
private List<AIStateController> _deadZombies = new List<AIStateController>();
[SerializeField]
private List<ZombieWave> _zombieWaveInfo = new List<ZombieWave>();
[Header("Events")]
[SerializeField]
private GameEvent _conversationStartEvent;
[SerializeField]
private GameEvent _levelEndEvent;
[SerializeField]
private GameEvent _levelLostEvent;
private bool _levelEnded = false;
private bool _levelLost = false;
private GameObject _playerObj;
private CharacterControls _playerControls;
private void Start()
{
_deadZombies.Add(null);
_playerObj = GameObject.FindWithTag("Player");
if (_playerObj)
_playerControls = _playerObj.GetComponent<CharacterControls>();
}
public void StartNextWave()
{
if (!_levelEnded && !_levelLost)
{
//Increment Current Wave
currentWave += 1;
_deadZombies.Clear();
_allZombies.Clear();
//Debug.Log(currentWave);
//Process next wave
if (currentWave <= _zombieWaveInfo.Count - 1)
{
//Spawn all zombies per wave
for (int i = 0; i < _zombieWaveInfo[currentWave].ZombieSpawns.Count; i++)
{
GameObject _zombie = Instantiate(_zombieWaveInfo[currentWave].ZombieSpawns[i].ZombieToSpawn, _zombieWaveInfo[currentWave].ZombieSpawns[i].SpawnPoint.position, Quaternion.identity) as GameObject;
AIStateController asc = _zombie.GetComponent<AIStateController>();
//asc.wayPoints.Clear();
//for (int j = 0; j < _zombieWaveInfo[currentWave].Waypoints.transform.childCount; j++)
//{
// asc.wayPoints.Add(_zombieWaveInfo[currentWave].Waypoints.transform.GetChild(j));
//}
//asc.wayPoints = _zombieWaveInfo[currentWave].Waypoints;
if (asc != null)
_allZombies.Add(asc);
}
if(_zombieWaveInfo[currentWave].WaveType == WaveType.TIME_BASED)
{
StartCoroutine(WaitAndProcessNextWave());
}
}
//All Waves complete for this level
else
{
_allZombies.Clear();
_deadZombies.Clear();
_levelEndEvent.Raise();
_levelEnded = true;
}
}
}
public void ProcessTriggeredWave()
{
if (_zombieWaveInfo[currentWave].WaveType == WaveType.PROXIMITY_BASED)
{
Debug.Log("New Wave Triggered");
}
}
public IEnumerator WaitAndProcessNextWave()
{
yield return new WaitForSeconds(_zombieWaveInfo[currentWave].timeTillNextWave);
if (_zombieWaveInfo[currentWave].PlayInterstitalAfterWave)
{
if (_zombieWaveInfo[currentWave].InterstitalToPlay != null)
{
_gameData.CurrentConversation.Conversation = _zombieWaveInfo[currentWave].InterstitalToPlay;
_conversationStartEvent.Raise();
}
}
else
StartNextWave();
_deadZombies.Clear();
_deadZombies.Add(null);
}
private void Update()
{
if (!_levelEnded && !_levelLost)
{
for (int i = 0; i < _allZombies.Count; i++)
{
if (!_allZombies[i].IsAlive)
{
if (!_deadZombies.Contains(_allZombies[i]))
_deadZombies.Add(_allZombies[i]);
}
}
if (currentWave > -1 && _zombieWaveInfo[currentWave].WaveType == WaveType.KILL_ALL_ZOMBIES && _deadZombies.Count == _allZombies.Count)
{
if (currentWave <= _zombieWaveInfo.Count - 1)
{
//Change logic
if (_zombieWaveInfo[currentWave].PlayInterstitalAfterWave)
{
if (_zombieWaveInfo[currentWave].InterstitalToPlay != null)
{
_gameData.CurrentConversation.Conversation = _zombieWaveInfo[currentWave].InterstitalToPlay;
_conversationStartEvent.Raise();
}
}
else
StartNextWave();
_deadZombies.Clear();
_deadZombies.Add(null);
}
}
}
if(!_playerControls.IsAlive && !_levelLost)
{
_levelLost = true;
_allZombies.Clear();
_deadZombies.Clear();
_levelLostEvent.Raise();
_levelEnded = true;
}
}
}
|
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using NetEscapades.AspNetCore.SecurityHeaders.Infrastructure;
namespace NetEscapades.AspNetCore.SecurityHeaders.TagHelpers
{
/// <summary>
/// Generates a Hash of the content of the script
/// </summary>
[HtmlTargetElement("script", Attributes = AttributeName)]
[HtmlTargetElement("style", Attributes = AttributeName)]
public class HashTagHelper : TagHelper
{
private const string AttributeName = "asp-add-content-to-csp";
private const string CspHashTypeAttributeName = "csp-hash-type";
/// <summary>
/// Add a <code>nonce</code> attribute to the element
/// </summary>
[HtmlAttributeName(CspHashTypeAttributeName)]
public CSPHashType CSPHashType { get; set; } = CSPHashType.SHA256;
/// <summary>
/// Provides access to the <see cref="ViewContext"/>
/// </summary>
[ViewContext]
public ViewContext? ViewContext { get; set; }
/// <inheritdoc />
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (ViewContext is null)
{
throw new InvalidOperationException("ViewContext was null");
}
using (var sha = CryptographyAlgorithms.Create(CSPHashType))
{
var childContent = await output.GetChildContentAsync();
// the hash is calculated based on unix line endings, not windows endings, so account for that
var content = childContent.GetContent().Replace("\r\n", "\n");
var contentBytes = Encoding.UTF8.GetBytes(content);
var hashedBytes = sha.ComputeHash(contentBytes);
var hash = Convert.ToBase64String(hashedBytes);
output.Attributes.RemoveAll(AttributeName);
output.Attributes.RemoveAll(CspHashTypeAttributeName);
if (context.TagName == "script")
{
ViewContext.HttpContext.SetScriptCSPHash(CSPHashType, hash);
}
else if (context.TagName == "style")
{
ViewContext.HttpContext.SetStylesCSPHash(CSPHashType, hash);
}
else
{
throw new InvalidOperationException("Unexpected tag name: " + context.TagName);
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace MyObserver
{
public interface ILetter
{
}
}
|
using System.IO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;
namespace Notepad
{
public partial class Form1 : Form
{
string file = "";
private DialogResult Save()
{
DialogResult odp = MessageBox.Show("Do you want to save changes", "Notepad", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
if (odp == DialogResult.Yes)
saveToolStripButton_Click(null, null);
return odp;
}
public Form1()
{
InitializeComponent();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (rtbNote.Text != "")
{
DialogResult odp = Save();
if (odp == DialogResult.Cancel)
e.Cancel = true;
}
}
private void helpToolStripButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Advanced Notepad by Krokodyl4", "Advanced Notepad", MessageBoxButtons.OK, MessageBoxIcon.Information); ;
}
private void pasteToolStripButton_Click(object sender, EventArgs e)
{
rtbNote.Paste();
}
private void copyToolStripButton_Click(object sender, EventArgs e)
{
rtbNote.Copy();
}
private void cutToolStripButton_Click(object sender, EventArgs e)
{
rtbNote.Cut();
}
private void printToolStripButton_Click(object sender, EventArgs e)
{
PrintDialog dialog = new PrintDialog();
dialog.ShowDialog();
}
private void saveToolStripButton_Click(object sender, EventArgs e)
{
if (file != "")
{
StreamWriter f = new StreamWriter(file);
f.Write(rtbNote.Text);
f.Close();
}
else saveAs_Click(sender, e);
}
private void saveAs_Click(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Text file (*txt)|*.txt |All files(*.*)|*.*";
dialog.ShowDialog();
if (dialog.FileName != "")
{
file = dialog.FileName;
StreamWriter f = new StreamWriter(file);
f.Write(rtbNote.Text);
f.Close();
}
}
private void openToolStripButton_Click(object sender, EventArgs e)
{
if (rtbNote.Text != "")
{
DialogResult odp = Save();
if (odp == DialogResult.Cancel)
return;
file = "";
rtbNote.Clear();
}
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Text file (*txt)|*.txt |All files(*.*)|*.*";
dialog.Multiselect = false;
dialog.ShowDialog();
if (dialog.FileName != "")
{
file = dialog.FileName;
StreamReader f = new StreamReader(file);
rtbNote.Text = f.ReadToEnd();
f.Close();
}
}
private void newToolStripButton_Click(object sender, EventArgs e)
{
if (rtbNote.Text != "")
{
DialogResult odp = Save();
if (odp == DialogResult.Cancel)
return;
file = "";
rtbNote.Clear();
}
}
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
PrintDialog dialog = new PrintDialog();
dialog.ShowDialog();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Text file (*txt)|*.txt |All files(*.*)|*.*";
dialog.ShowDialog();
if (dialog.FileName != "")
{
file = dialog.FileName;
StreamWriter f = new StreamWriter(file);
f.Write(rtbNote.Text);
f.Close();
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (file != "")
{
StreamWriter f = new StreamWriter(file);
f.Write(rtbNote.Text);
f.Close();
}
else saveAs_Click(sender, e);
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (rtbNote.Text != "")
{
DialogResult odp = Save();
if (odp == DialogResult.Cancel)
return;
file = "";
rtbNote.Clear();
}
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Text file (*txt)|*.txt |All files(*.*)|*.*";
dialog.Multiselect = false;
dialog.ShowDialog();
if (dialog.FileName != "")
{
file = dialog.FileName;
StreamReader f = new StreamReader(file);
rtbNote.Text = f.ReadToEnd();
f.Close();
}
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (rtbNote.Text != "")
{
DialogResult odp = Save();
if (odp == DialogResult.Cancel)
return;
file = "";
rtbNote.Clear();
}
}
private void Form1_Load(object sender, EventArgs e)
{
menuStrip1.Hide();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
shortcutsToolStripMenuItem_Click(null, null);
}
private void shortcutsToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(
" Shortcuts:\n\n" +
" Ctrl + N - New File\n" +
" Ctrl + O - Open File\n" +
" Ctrl + S - Save\n" +
" Ctrl + Shift + S - Save As\n" +
" Ctrl + P - Print\n" +
" Ctrl + C - Copy\n" +
" Ctrl + V - Paste\n" +
" Ctrl + X - Cut\n" +
" Ctrl + Shift + A - About\n" +
" Alt + F4 - Exit\n" +
" Ctrl + Alt + Shift - This List",
"Shortcuts",
MessageBoxButtons.OK,
MessageBoxIcon.None
);
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
pasteToolStripButton_Click(null, null);
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
cutToolStripButton_Click(null, null);
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
copyToolStripButton_Click(null, null);
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Advanced Notepad by Krokodyl4", "Advanced Notepad", MessageBoxButtons.OK, MessageBoxIcon.Information); ;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
toolStripButton2_Click(null, null);
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
|
#if UNITY_2019_1_OR_NEWER
using UnityEditor;
using UnityAtoms.Editor;
namespace UnityAtoms.BaseAtoms.Editor
{
/// <summary>
/// Value List property drawer of type `Vector3`. Inherits from `AtomDrawer<Vector3ValueList>`. Only availble in `UNITY_2019_1_OR_NEWER`.
/// </summary>
[CustomPropertyDrawer(typeof(Vector3ValueList))]
public class Vector3ValueListDrawer : AtomDrawer<Vector3ValueList> { }
}
#endif
|
using CarsIsland.Infrastructure.Configuration.Interfaces;
using Microsoft.Extensions.Options;
namespace CarsIsland.Infrastructure.Configuration
{
public class MessagingServiceConfiguration : IMessagingServiceConfiguration
{
public string QueueName { get; set; }
public string ListenAndSendConnectionString { get; set; }
}
public class MessagingServiceConfigurationValidation : IValidateOptions<MessagingServiceConfiguration>
{
public ValidateOptionsResult Validate(string name, MessagingServiceConfiguration options)
{
if (string.IsNullOrEmpty(options.ListenAndSendConnectionString))
{
return ValidateOptionsResult.Fail($"{nameof(options.ListenAndSendConnectionString)} configuration parameter for the Azure Service Bus is required");
}
if (string.IsNullOrEmpty(options.QueueName))
{
return ValidateOptionsResult.Fail($"{nameof(options.QueueName)} configuration parameter for the Azure Service Bus is required");
}
return ValidateOptionsResult.Success;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ghostpunch.OnlyDown.Common;
using Ghostpunch.OnlyDown.Common.Views;
using Ghostpunch.OnlyDown.Menu.ViewModels;
using strange.extensions.mediation.impl;
using strange.extensions.signal.impl;
using UnityEngine;
using UnityEngine.UI;
namespace Ghostpunch.OnlyDown.Menu.Views
{
public class MainMenuView : View
{
public Button _startButton, _quitButton;
[Inject]
public MainMenuViewModel VM { get; set; }
protected override void Start()
{
base.Start();
if (_startButton != null)
_startButton.onClick.AddListener(OnStartClick);
if (_quitButton != null)
_quitButton.onClick.AddListener(OnQuit);
}
private void OnStartClick()
{
VM.StartButtonPressedCommand.Execute(null);
}
private void OnQuit()
{
VM.QuitButtonPressedCommand.Execute(null);
}
}
}
|
//Name: CameraTrigger.cs
//Project: Spectral: The Silicon Domain
//Author(s) Conor Hughes - conormpkhughes@yahoo.com
//Description: A trigger which overwrites the cameracontrollers current target position once it is entered.
using UnityEngine;
using System.Collections;
public class CameraTrigger : MonoBehaviour {
private CameraController cController; //instance of camera controller
public bool lookAtPlayer = true; //determines if camera controller can look at player
// Use this for initialization
void Start () {
cController = Camera.main.GetComponent<CameraController>();
GetComponent<Renderer>().enabled = false;
}
//When trigger is entered, overwrite current camera target
void OnTriggerEnter(Collider c){
if(c.tag == "Player"){
if(transform.Find("CameraPosRot(Clone)")) cController.targetCamera = transform.Find("CameraPosRot(Clone)").transform;
else cController.targetCamera = transform.Find("CameraPosRot").transform;
cController.target = c.transform;
}
}
}
|
namespace DesignPatterns.Decorator.Example1
{
/// <summary>
/// Concrete Decorators call the wrapped object and alter its result in some way.
/// </summary>
public class ConcreteDecoratorA : Decorator
{
public ConcreteDecoratorA(Component comp) : base(comp)
{
}
/// <summary>
/// Decorators may call parent implementation of the operation, instead of calling the wrapped object directly.
/// This approach simplifies extension of decorator classes.
/// </summary>
/// <returns></returns>
public override string Operation()
{
return $"ConcreteDecoratorA({base.Operation()})";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace EmployeeTaskMonitor.Core.Exceptions
{
public class NotFoundException: Exception
{
//public NotFoundException(string name, object key):base($"Resource \"{name}\" ({key}) was not found.")
//{
//}
public NotFoundException(string message) : base(message)
{
}
}
}
|
using System.Collections.Generic;
using Properties.Core.Objects;
namespace Properties.Core.Interfaces
{
public interface IFactory<T>
{
List<T> GetAll();
}
}
|
using System;
using System.Collections.Generic;
using App.Core.Interfaces.Dto;
using App.Core.Interfaces.Dto.Responses;
using App.Core.Interfaces.Extensions;
using Newtonsoft.Json;
namespace App.Core.Interfaces.Json
{
public class RequestDtoPaginationJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<Type, PaginationDto>);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var tValue = (Dictionary<Type, PaginationDto>) value;
var dict = new Dictionary<string, PaginationDto>();
foreach (var pair in tValue)
{
dict[pair.Key.GetEntityListName()] = pair.Value;
}
serializer.Serialize(writer, dict);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var dict = (Dictionary<string, PaginationDto>) serializer.Deserialize(reader,
typeof(Dictionary<string, PaginationDto>));
var result = new Dictionary<Type, PaginationDto>();
foreach (var pair in dict)
{
result[pair.Key.GetEntityTypeByListName()] = pair.Value;
}
return result;
}
}
} |
namespace Simulator.Compile {
internal enum CpuTokenType {
// ReSharper disable once UnusedMember.Global
None,
Instruction,
Value,
Label,
Data
}
} |
using UnityEngine;
using System.Collections;
public class TrapDamage : MonoBehaviour {
public int damage = 25;
private Movement movement;
void OnCollisionEnter2D(Collision2D collision) {
Movement movement = collision.gameObject.GetComponent<Movement>();
Health health = collision.gameObject.GetComponent<Health>();
if (health != null) {
if (!health.isDead)
if (movement != null)
movement.Jump();
health.RemoveHealth(damage);
}
}
}
|
using UnityEngine;
using System.Collections;
public class TurretEmitter : MonoBehaviour { //This controls the projectiles that emit from the turret
public GameObject projectile; //projectile to be instantiated by the turret
public Transform start;//this is the start pos for raycast
public Transform end; //this is the end pos for raycast
public bool spotted = false; //this checks if player is in view of raycast
private float nextFire = 0f;//controls first instance of instantiated object
void Update () {
Raycast();
GetComponentInParent<Animator>().SetBool("Spotted",spotted);//trigger barrel recoil
if (spotted){//once the raycast spots you, start the following firing sequence
float fireRate = 1f;//1 sec fire rate
if ( Time.time > nextFire){
nextFire = Time.time + fireRate;
Vector2 position = transform.position;
Instantiate(projectile, position, transform.rotation);//makes copies of projectile based on position
}
}
}
void Raycast(){
Debug.DrawLine(start.position, end.position, Color.red);//use to see raycast in scene view
spotted = Physics2D.Linecast (start.position, end.position, 1 << LayerMask.NameToLayer("Player"));
//above sets the spotted bool to true to false accordingly
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Gruzer.Models.Consignments
{
/// <summary>
/// Водитель
/// </summary>
public class Driver : BaseEntity
{
/// <summary>
/// Имя
/// </summary>
public string Name { get; set; }
/// <summary>
/// Телефон
/// </summary>
public string Phone { get; set; }
/// <summary>
/// Паспорт
/// </summary>
public byte[] Pasport { get; set; }
/// <summary>
/// Права на вождение
/// </summary>
public byte[] DrivingLicence { get; set; }
/// <summary>
/// Медицинская книжка
/// </summary>
public byte[] MedicalRecord { get; set; }
/// <summary>
/// Документ на управление транспортом
/// </summary>
public byte[] TransportDocument { get; set; }
/// <summary>
/// Документ убеждающий регистрацию на водителя
/// </summary>
public byte[] TransportRegistration { get; set; }
/// <summary>
/// Санитарные нормы
/// </summary>
public string SanilaryRegulations { get; set; }
/// <summary>
/// Стаж вождения (лет)
/// </summary>
public int Experience { get; set; }
//relations
/// <summary>
/// Компания в которой работает водитель
/// </summary>
public virtual Company Company { get; set; }
public int? CompanyId { get; set; }
/// <summary>
/// Транспорт на котором в данный момент находится водитель
/// </summary>
public virtual Transport Transport { get; set; }
public int? TransportId { get; set; }
}
}
|
using Hyprsoft.Dns.Monitor.Providers;
using Hyprsoft.Logging.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
namespace Hyprsoft.Dns.Monitor
{
class Program
{
#region Methods
static void Main(string[] args) => CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSystemd()
.ConfigureLogging(builder => builder.AddSimpleFileLogger())
.ConfigureAppConfiguration(builder => builder.AddJsonFile(Path.Combine(AppContext.BaseDirectory, "appsettings.json"), true))
.ConfigureServices((hostContext, services) =>
{
var monitorSettings = new MonitorSettings();
hostContext.Configuration.GetSection(nameof(MonitorSettings)).Bind(monitorSettings);
services.AddSingleton(monitorSettings);
services.AddDnsMonitor(settings =>
{
settings.Domains = monitorSettings.Domains;
settings.DnsProviderApiCredentials = monitorSettings.DnsProviderApiCredentials;
settings.PublicIpProviderApiCredentials = monitorSettings.PublicIpProviderApiCredentials;
services.AddHostedService<Worker>();
});
});
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inimigo : MonoBehaviour
{
public float vel = 2.4f;
Rigidbody2D rb;
public Transform Player;
Transform inimigoLocal;
bool face;
public Animator anima;
bool andar = false;
public float distancia;
//ataque
float proximoataque;
void Start()
{
rb = GetComponent<Rigidbody2D>();
inimigoLocal = GetComponent<Transform>();
anima = GetComponent<Animator>();
}
void Update()
{
distancia = Vector2.Distance(this.inimigoLocal.position, Player.position);
if ((Player.transform.position.x > this.inimigoLocal.position.x) && !face)
{
Flip();
}
else if ((Player.transform.position.x < this.inimigoLocal.position.x) && face)
{
Flip();
}
Bater();
}
private void FixedUpdate()
{
if ((andar) && distancia > 2.8f)
{
if (Player.transform.position.x < this.inimigoLocal.position.x)
{
rb.velocity = new Vector2(-vel, rb.velocity.y);
}
if (Player.transform.position.x > this.inimigoLocal.position.x)
{
rb.velocity = new Vector2(vel, rb.velocity.y);
}
}
}
void Flip()
{
face = !face;
Vector3 scala = this.inimigoLocal.localScale;
scala.x *= -1;
this.inimigoLocal.localScale = scala;
}
private void OnTriggerEnter2D(Collider2D outro)
{
if (outro.gameObject.CompareTag("Player"))
{
andar = true;
}
}
private void OnTriggerExit2D(Collider2D outro)
{
if (outro.gameObject.CompareTag("Player"))
{
andar = false;
}
}
void Bater()
{
if (distancia <= 2 && Time.time > proximoataque)
{
proximoataque = Time.time + 1;
}
}
}
|
using AutoMapper;
using LearningSystem.Models.EntityModels;
using LearningSystem.Models.ViewModels.Courses;
using LearningSystem.Services.Interfaces;
namespace LearningSystem.Services
{
public class CourseService : Service, ICourseService
{
public CourseDetailsVm GetDetailsById(int id)
{
Course course = this.Contex.Courses.Find(id);
if (course == null)
{
return null;
}
CourseDetailsVm vm = Mapper.Map<Course, CourseDetailsVm>(course);
return vm;
}
}
} |
// <copyright file="TypefaceReader.cs" company="WaterTrans">
// © 2020 WaterTrans and Contributors
// </copyright>
using System;
using System.Text;
namespace WaterTrans.GlyphLoader.Internal
{
/// <summary>
/// Internal processing class for accessing font data.
/// </summary>
internal sealed class TypefaceReader
{
private byte[] _byteArray;
/// <summary>
/// Initializes a new instance of the <see cref="TypefaceReader"/> class.
/// </summary>
/// <param name="byteArray">The font file byte array.</param>
/// <param name="position">The byte array position.</param>
internal TypefaceReader(byte[] byteArray, long position)
{
_byteArray = byteArray;
Position = position;
}
/// <summary>
/// Gets or sets the stream position.
/// </summary>
public long Position { get; set; }
/// <summary>
/// Read string.
/// </summary>
/// <param name="len">Number of length.</param>
/// <param name="encoding">Encoding.</param>
/// <returns>Read result.</returns>
public string ReadString(int len, Encoding encoding)
{
var buf = ReadBytes(len);
return encoding.GetString(buf);
}
/// <summary>
/// Read char array.
/// </summary>
/// <param name="len">Number of length.</param>
/// <returns>Read result.</returns>
public string ReadCharArray(int len)
{
var sb = new StringBuilder();
for (int i = 0; i < len; i++)
{
sb.Append(ReadChar());
}
return sb.ToString();
}
/// <summary>
/// Read byte array.
/// </summary>
/// <param name="len">Number of length.</param>
/// <returns>Read result.</returns>
public byte[] ReadBytes(int len)
{
byte[] result = new byte[len];
Array.Copy(_byteArray, Position, result, 0, len);
Position += len;
return result;
}
/// <summary>
/// Read specified (1-4) length.
/// </summary>
/// <param name="size">The value is element size.</param>
/// <returns>Read result.</returns>
public uint ReadOffset(byte size)
{
switch (size)
{
case 1:
return ReadByte();
case 2:
return ReadUInt16();
case 3:
return ReadUInt24();
case 4:
return ReadUInt32();
}
throw new ArgumentOutOfRangeException(nameof(size));
}
/// <summary>
/// Read char.
/// </summary>
/// <returns>Read result.</returns>
public char ReadChar()
{
return (char)ReadByte();
}
/// <summary>
/// Read sbyte.
/// </summary>
/// <returns>Read result.</returns>
public sbyte ReadSByte()
{
return unchecked((sbyte)ReadByte());
}
/// <summary>
/// Read byte.
/// </summary>
/// <returns>Read result.</returns>
public byte ReadByte()
{
byte result = _byteArray[Position];
Position += 1;
return result;
}
/// <summary>
/// Read 255UInt16.
/// </summary>
/// <returns>Read result.</returns>
public ushort Read255UInt16()
{
byte code;
ushort value, value2;
const byte oneMoreByteCode1 = 255;
const byte oneMoreByteCode2 = 254;
const byte wordCode = 253;
const byte lowestUCode = 253;
code = ReadByte();
if (code == wordCode)
{
value = ReadByte();
value <<= 8;
value2 = ReadByte();
value = (ushort)(value | value2);
}
else if (code == oneMoreByteCode1)
{
value = ReadByte();
value += lowestUCode;
}
else if (code == oneMoreByteCode2)
{
value = ReadByte();
value += lowestUCode * 2;
}
else
{
value = code;
}
return value;
}
/// <summary>
/// Read UIntBase128.
/// </summary>
/// <returns>Read result.</returns>
public uint ReadUIntBase128()
{
uint accum = 0;
for (int i = 0; i < 5; i++)
{
byte data_byte = ReadByte();
// No leading 0's
if (i == 0 && data_byte == 0x80)
{
throw new FormatException("Encountered a UintBase128-encoded value with leading zeros.");
}
// If any of top 7 bits are set then << 7 would overflow
if ((accum & 0xFE000000) != 0)
{
throw new FormatException("Encountered a UintBase128-encoded value with overflow.");
}
accum = (uint)(accum << 7) | (uint)(data_byte & 0x7F);
// Spin until most significant bit of data byte is false
if ((data_byte & 0x80) == 0)
{
return accum;
}
}
// UIntBase128 sequence exceeds 5 bytes
throw new FormatException("Encountered a UintBase128-encoded value with sequence exceeds 5 bytes.");
}
/// <summary>
/// Read UInt16.
/// </summary>
/// <returns>Read result.</returns>
public ushort ReadUInt16()
{
return BitConverter.ToUInt16(ReadBytesInternal(2), 0);
}
/// <summary>
/// Read Int16.
/// </summary>
/// <returns>Read result.</returns>
public short ReadInt16()
{
return BitConverter.ToInt16(ReadBytesInternal(2), 0);
}
/// <summary>
/// Read UInt24.
/// </summary>
/// <returns>Read result.</returns>
public uint ReadUInt24()
{
byte[] buf = ReadBytesInternal(3);
return (uint)(buf[0] | (buf[1] << 8) | (buf[2] << 16));
}
/// <summary>
/// Read UInt32.
/// </summary>
/// <returns>Read result.</returns>
public uint ReadUInt32()
{
return BitConverter.ToUInt32(ReadBytesInternal(4), 0);
}
/// <summary>
/// Read Int32.
/// </summary>
/// <returns>Read result.</returns>
public int ReadInt32()
{
return BitConverter.ToInt32(ReadBytesInternal(4), 0);
}
/// <summary>
/// Read UInt64.
/// </summary>
/// <returns>Read result.</returns>
public ulong ReadUInt64()
{
return BitConverter.ToUInt64(ReadBytesInternal(8), 0);
}
/// <summary>
/// Read Int64.
/// </summary>
/// <returns>Read result.</returns>
public long ReadInt64()
{
return BitConverter.ToInt64(ReadBytesInternal(8), 0);
}
/// <summary>
/// Read Fixed.
/// </summary>
/// <returns>Read result.</returns>
public float ReadFixed()
{
return ReadInt32() / 65536F;
}
/// <summary>
/// Read Fword.
/// </summary>
/// <returns>Read result.</returns>
public short ReadFword()
{
return ReadInt16();
}
/// <summary>
/// Read F2Dot14.
/// </summary>
/// <returns>Read result.</returns>
public float ReadF2Dot14()
{
return (float)ReadInt16() / 16384;
}
private byte[] ReadBytesInternal(int count)
{
byte[] buff = ReadBytes(count);
Array.Reverse(buff);
return buff;
}
}
}
|
using PhotonInMaze.Common.Model;
using System.Collections.Generic;
namespace PhotonInMaze.Common.Controller {
public interface IPathToGoalManager {
LinkedListNode<IMazeCell> GetFirstFromPath();
int GetPathToGoalSize();
void RemoveFirst();
void AddFirst(IMazeCell value);
int IndexInPath(IMazeCell value);
IMazeCell FindPathToGoalFrom(IMazeCell value);
}
}
|
using Framework.Core.Common;
using OpenQA.Selenium;
namespace Tests.Pages.Drupal.Forms
{
public class PetitionForm : FormBase
{
#region Elements
#endregion
public PetitionForm(Driver driver) : base(driver) { }
#region Methods
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ACNADailyPrayer
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
[ContentProperty(nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
{
return null;
}
// Do your translation lookup here, using whatever method you require
var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);
return imageSource;
}
}
public partial class MainPage : ContentPage
{
public DateTime todaysDate = DateTime.Today;
public DateTime dateChoice = DateTime.Today;
public string headerImage = "";
public MainPage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
}
string getDate()
{
string weekday = dateChoice.DayOfWeek.ToString();
string month = dateChoice.ToString("MMMM");
string day = dateChoice.Day.ToString();
string year = dateChoice.Year.ToString();
return weekday + " " + month + " " + day + " " + year;
}
async void MorningPrayer_Clicked(object sender, System.EventArgs e)
{
loadingIndicator.IsRunning = true;
this.IsEnabled = false;
try
{
Page1 servicePage = null;
await Task.Run(() =>
{
servicePage = new Page1(new Service(Service.Office.MorningPrayer, getDate()));
});
await Navigation.PushAsync(servicePage);
}
catch(Exception ex)
{
await Navigation.PopAsync();
await DisplayAlert("ERROR", ex.Message + "\n\n" + "Unable to load service - please check your Internet Connection", "OK");
}
finally
{
this.IsEnabled = true;
loadingIndicator.IsRunning = false;
}
}
async void EveningPrayer_Clicked(object sender, System.EventArgs e)
{
loadingIndicator.IsRunning = true;
this.IsEnabled = false;
try
{
Page1 servicePage = null;
await Task.Run(() =>
{
servicePage = new Page1(new Service(Service.Office.EveningPrayer, getDate()));
});
await Navigation.PushAsync(servicePage);
}
catch (Exception ex)
{
await Navigation.PopAsync();
await DisplayAlert("ERROR", ex.Message + "\n\n" + "Unable to load service - please check your Internet Connection", "OK");
}
finally
{
this.IsEnabled = true;
loadingIndicator.IsRunning = false;
}
}
void DateSelected(object sender, DateChangedEventArgs e)
{
dateChoice = e.NewDate;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems.LeetCode {
public class Problem006 : LeetCodeBase {
public override string ProblemName => "Leet Code 6: Zigzag Conversion";
public override string GetAnswer() {
Check(Convert("PAYPALISHIRING", 3), "PAHNAPLSIIGYIR");
Check(Convert("PAYPALISHIRING", 4), "PINALSIGYAHRPI");
Check("AB", Convert("AB", 1));
return "";
}
public string Convert(string s, int numRows) {
var text = new StringBuilder[numRows];
for (int index = 0; index < numRows; index++) {
text[index] = new StringBuilder();
}
int digitIndex = 0;
int x = 0;
int direction = -1;
while (digitIndex < s.Length) {
text[x].Append(s[digitIndex]);
if (x == 0 || x == numRows - 1) direction *= -1;
if (numRows > 1) x += direction;
digitIndex++;
}
var final = new StringBuilder();
foreach (var sub in text) {
final.Append(sub.ToString());
}
return final.ToString();
}
}
}
|
using Euler_Logic.Helpers;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem700 : ProblemBase {
/*
I used an online calculator to find the moduler inverse between 1504170715041707 and 4503599627370517, which is 3451657199285664. Given this, we know that
3451657199285664 * 1504170715041707 % 4503599627370517 = 1. We can continue adding the inverse until we find a number less than 1504170715041707, and then
again and again. It would take too long to solve the problem this way though, so FindReasonable will continue to do this until we get some number that's
reasonable, then we just bruteforce up to that number.
*/
public override string ProblemName {
get { return "700: Eulercoin"; }
}
public override string GetAnswer() {
var x = FindReasonable(3451657199285664, 4503599627370517, 100000000);
var y = FindRest(1504170715041707, 4503599627370517, x.Item2);
return (x.Item1 + y).ToString();
}
private BigInteger FindRest(BigInteger num, BigInteger mod, ulong max) {
BigInteger sum = num;
BigInteger best = num;
var current = num;
for (ulong count = 2; count < max; count++) {
current = (current + num) % mod;
if (current < best) {
best = current;
sum += current;
}
}
return sum;
}
private Tuple<ulong, ulong> FindReasonable(ulong inverse, ulong mod, ulong threshold) {
ulong last = inverse;
ulong num = inverse;
ulong n = 1;
ulong sum = 1;
do {
num += inverse;
n++;
if (num > mod) {
num %= mod;
if (num < last) {
sum += n;
if (num < threshold) return new Tuple<ulong, ulong>(sum, num);
last = num;
}
}
} while (true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _10_Group_by_Group
{
public class _10_Group_by_Group
{
public static void Main()
{
var students = new List<Student>();
var input = Console.ReadLine();
while (input != "END")
{
var line = input.Split();
var name = string.Join(" ", line.Take(2));
var group = int.Parse(line.Last());
var currentStudent = new Student() { Name = name, Group = group };
students.Add(currentStudent);
input = Console.ReadLine();
}
var grouped = students.GroupBy(x => x.Group).OrderBy(x => x.Key);
foreach (var group in grouped)
{
Console.Write(group.Key + " - ");
var sb = new StringBuilder();
foreach (var names in group)
{
sb.Append(names.Name).Append(", ");
}
Console.WriteLine(sb.ToString().TrimEnd(new[] { ',', ' ' }));
}
}
public class Student
{
public string Name { get; set; }
public int Group { get; set; }
}
}
}
|
using UnityEngine;
public class Destructible : MonoBehaviour
{
// Destruimos el elemento destructible si colisiona con una bala
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Bala") {
Destroy (this.gameObject);
}
}
}
|
using System;
using PokerHandShowdown;
namespace PokerHandShowdownTests
{
public class GameSessionCommun
{
public PokerGameSession _pokerGameSession = new PokerGameSession();
public void ProcessGameSession_Success_Pair_Score_Data()
{
_pokerGameSession.AddPlayer("hicham");
_pokerGameSession.AddPlayer("amber");
_pokerGameSession.DispatchCardsToPlayer("hicham", new Card(PokerSuit.Club, PokerRank.Ace));
_pokerGameSession.DispatchCardsToPlayer("hicham",
new Card[]
{
new Card(PokerSuit.Heart,PokerRank.Eight),
new Card(PokerSuit.Diamond,PokerRank.Eight),
new Card(PokerSuit.Spades,PokerRank.Nine),
new Card(PokerSuit.Club,PokerRank.Jack),
});
_pokerGameSession.DispatchCardsToPlayer("amber",
new Card[]
{
new Card(PokerSuit.Spades,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Ten),
new Card(PokerSuit.Spades,PokerRank.King),
new Card(PokerSuit.Diamond,PokerRank.Ace),
new Card(PokerSuit.Club,PokerRank.Seven),
});
_pokerGameSession.AddPlayer("kid",
new Card[]
{
new Card(PokerSuit.Diamond,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Eight),
new Card(PokerSuit.Club,PokerRank.Eight),
new Card(PokerSuit.Heart,PokerRank.Ace),
new Card(PokerSuit.Heart,PokerRank.Seven),
});
_pokerGameSession.PreparePlayersHands();
}
public void ProcessGameSession_Success_Flush_Data()
{
_pokerGameSession.AddPlayer("hicham");
_pokerGameSession.AddPlayer("amber");
_pokerGameSession.DispatchCardsToPlayer("hicham", new Card(PokerSuit.Club, PokerRank.Ace));
_pokerGameSession.DispatchCardsToPlayer("hicham",
new Card[]
{
new Card(PokerSuit.Club,PokerRank.Four),
new Card(PokerSuit.Diamond,PokerRank.Four),
new Card(PokerSuit.Spades,PokerRank.Four),
new Card(PokerSuit.Club,PokerRank.Jack),
});
_pokerGameSession.DispatchCardsToPlayer("amber",
new Card[]
{
new Card(PokerSuit.Spades,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Ten),
new Card(PokerSuit.Spades,PokerRank.King),
new Card(PokerSuit.Spades,PokerRank.Ace),
new Card(PokerSuit.Spades,PokerRank.Seven),
});
_pokerGameSession.AddPlayer("kid",
new Card[]
{
new Card(PokerSuit.Diamond,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Eight),
new Card(PokerSuit.Club,PokerRank.Eight),
new Card(PokerSuit.Heart,PokerRank.Ace),
new Card(PokerSuit.Heart,PokerRank.Seven),
});
_pokerGameSession.PreparePlayersHands();
}
public void ProcessGameSession_Success_Flush_Score_Data()
{
_pokerGameSession.AddPlayer("hicham");
_pokerGameSession.AddPlayer("amber");
_pokerGameSession.DispatchCardsToPlayer("hicham", new Card(PokerSuit.Club, PokerRank.Ace));
_pokerGameSession.DispatchCardsToPlayer("hicham",
new Card[]
{
new Card(PokerSuit.Club,PokerRank.Four),
new Card(PokerSuit.Diamond,PokerRank.Four),
new Card(PokerSuit.Spades,PokerRank.Four),
new Card(PokerSuit.Club,PokerRank.Jack),
});
_pokerGameSession.DispatchCardsToPlayer("amber",
new Card[]
{
new Card(PokerSuit.Spades,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Ten),
new Card(PokerSuit.Spades,PokerRank.King),
new Card(PokerSuit.Spades,PokerRank.Ace),
new Card(PokerSuit.Spades,PokerRank.Seven),
});
_pokerGameSession.AddPlayer("kid",
new Card[]
{
new Card(PokerSuit.Heart,PokerRank.Jack),
new Card(PokerSuit.Heart,PokerRank.Eight),
new Card(PokerSuit.Heart,PokerRank.Nine),
new Card(PokerSuit.Heart,PokerRank.Ace),
new Card(PokerSuit.Heart,PokerRank.Seven),
});
_pokerGameSession.PreparePlayersHands();
}
public void ProcessGameSession_Success_Flush_Tie_Data()
{
_pokerGameSession.AddPlayer("hicham");
_pokerGameSession.AddPlayer("amber");
_pokerGameSession.DispatchCardsToPlayer("hicham", new Card(PokerSuit.Club, PokerRank.Ace));
_pokerGameSession.DispatchCardsToPlayer("hicham",
new Card[]
{
new Card(PokerSuit.Club,PokerRank.Jack),
new Card(PokerSuit.Club,PokerRank.Ten),
new Card(PokerSuit.Club,PokerRank.King),
new Card(PokerSuit.Club,PokerRank.Seven),
});
_pokerGameSession.DispatchCardsToPlayer("amber",
new Card[]
{
new Card(PokerSuit.Spades,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Ten),
new Card(PokerSuit.Spades,PokerRank.King),
new Card(PokerSuit.Spades,PokerRank.Ace),
new Card(PokerSuit.Spades,PokerRank.Seven),
});
_pokerGameSession.AddPlayer("kid",
new Card[]
{
new Card(PokerSuit.Heart,PokerRank.Jack),
new Card(PokerSuit.Heart,PokerRank.Eight),
new Card(PokerSuit.Heart,PokerRank.Nine),
new Card(PokerSuit.Heart,PokerRank.Ace),
new Card(PokerSuit.Heart,PokerRank.Seven),
});
_pokerGameSession.PreparePlayersHands();
}
public void ProcessGameSession_Success_ThreeOfKind_Data()
{
_pokerGameSession.AddPlayer("hicham");
_pokerGameSession.AddPlayer("amber");
_pokerGameSession.DispatchCardsToPlayer("hicham", new Card(PokerSuit.Club, PokerRank.Ace));
_pokerGameSession.DispatchCardsToPlayer("hicham",
new Card[]
{
new Card(PokerSuit.Club,PokerRank.Four),
new Card(PokerSuit.Diamond,PokerRank.Four),
new Card(PokerSuit.Spades,PokerRank.Four),
new Card(PokerSuit.Club,PokerRank.Jack),
});
_pokerGameSession.DispatchCardsToPlayer("amber",
new Card[]
{
new Card(PokerSuit.Spades,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Ten),
new Card(PokerSuit.Spades,PokerRank.King),
new Card(PokerSuit.Diamond,PokerRank.Ace),
new Card(PokerSuit.Club,PokerRank.Seven),
});
_pokerGameSession.AddPlayer("kid",
new Card[]
{
new Card(PokerSuit.Diamond,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Eight),
new Card(PokerSuit.Club,PokerRank.Eight),
new Card(PokerSuit.Heart,PokerRank.Ace),
new Card(PokerSuit.Heart,PokerRank.Seven),
});
_pokerGameSession.PreparePlayersHands();
}
public void ProcessGameSession_Success_ThreeOfKind_Score_Data()
{
_pokerGameSession.AddPlayer("hicham");
_pokerGameSession.AddPlayer("amber");
_pokerGameSession.DispatchCardsToPlayer("hicham", new Card(PokerSuit.Club, PokerRank.Ace));
_pokerGameSession.DispatchCardsToPlayer("hicham",
new Card[]
{
new Card(PokerSuit.Club,PokerRank.Four),
new Card(PokerSuit.Diamond,PokerRank.Four),
new Card(PokerSuit.Spades,PokerRank.Four),
new Card(PokerSuit.Club,PokerRank.Jack),
});
_pokerGameSession.DispatchCardsToPlayer("amber",
new Card[]
{
new Card(PokerSuit.Spades,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Ten),
new Card(PokerSuit.Spades,PokerRank.King),
new Card(PokerSuit.Diamond,PokerRank.Ace),
new Card(PokerSuit.Club,PokerRank.Seven),
});
_pokerGameSession.AddPlayer("kid",
new Card[]
{
new Card(PokerSuit.Diamond,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Eight),
new Card(PokerSuit.Club,PokerRank.Eight),
new Card(PokerSuit.Heart,PokerRank.Eight),
new Card(PokerSuit.Heart,PokerRank.Seven),
});
_pokerGameSession.PreparePlayersHands();
}
public void ProcessGameSession_Success_Pair_Data()
{
_pokerGameSession.AddPlayer("hicham");
_pokerGameSession.AddPlayer("amber");
_pokerGameSession.DispatchCardsToPlayer("hicham", new Card(PokerSuit.Club, PokerRank.Ace));
_pokerGameSession.DispatchCardsToPlayer("hicham",
new Card[]
{
new Card(PokerSuit.Club,PokerRank.Four),
new Card(PokerSuit.Diamond,PokerRank.Four),
new Card(PokerSuit.Spades,PokerRank.Nine),
new Card(PokerSuit.Club,PokerRank.Jack),
});
_pokerGameSession.DispatchCardsToPlayer("amber",
new Card[]
{
new Card(PokerSuit.Spades,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Ten),
new Card(PokerSuit.Spades,PokerRank.King),
new Card(PokerSuit.Diamond,PokerRank.Ace),
new Card(PokerSuit.Club,PokerRank.Seven),
});
_pokerGameSession.AddPlayer("kid",
new Card[]
{
new Card(PokerSuit.Diamond,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Eight),
new Card(PokerSuit.Club,PokerRank.Eight),
new Card(PokerSuit.Heart,PokerRank.Ace),
new Card(PokerSuit.Heart,PokerRank.Seven),
});
_pokerGameSession.PreparePlayersHands();
}
public void ProcessGameSession_Success_Score_Data()
{
_pokerGameSession.AddPlayer("hicham");
_pokerGameSession.AddPlayer("amber");
_pokerGameSession.DispatchCardsToPlayer("hicham", new Card(PokerSuit.Club, PokerRank.Ace));
_pokerGameSession.DispatchCardsToPlayer("hicham",
new Card[]
{
new Card(PokerSuit.Heart,PokerRank.Eight),
new Card(PokerSuit.Diamond,PokerRank.Five),
new Card(PokerSuit.Spades,PokerRank.Nine),
new Card(PokerSuit.Club,PokerRank.Jack),
});
_pokerGameSession.DispatchCardsToPlayer("amber",
new Card[]
{
new Card(PokerSuit.Spades,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Ten),
new Card(PokerSuit.Spades,PokerRank.King),
new Card(PokerSuit.Diamond,PokerRank.Ace),
new Card(PokerSuit.Club,PokerRank.Seven),
});
_pokerGameSession.AddPlayer("kid",
new Card[]
{
new Card(PokerSuit.Diamond,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Eight),
new Card(PokerSuit.Club,PokerRank.Four),
new Card(PokerSuit.Heart,PokerRank.Ace),
new Card(PokerSuit.Heart,PokerRank.Seven),
});
_pokerGameSession.PreparePlayersHands();
}
public void ProcessGameSession_Success_Score_Tie_Data()
{
_pokerGameSession.AddPlayer("hicham");
_pokerGameSession.AddPlayer("amber");
_pokerGameSession.DispatchCardsToPlayer("hicham", new Card(PokerSuit.Club, PokerRank.Ace));
_pokerGameSession.DispatchCardsToPlayer("hicham",
new Card[]
{
new Card(PokerSuit.Heart,PokerRank.Eight),
new Card(PokerSuit.Diamond,PokerRank.Five),
new Card(PokerSuit.Spades,PokerRank.Nine),
new Card(PokerSuit.Club,PokerRank.Jack),
});
_pokerGameSession.DispatchCardsToPlayer("amber",
new Card[]
{
new Card(PokerSuit.Spades,PokerRank.Jack),
new Card(PokerSuit.Spades,PokerRank.Ten),
new Card(PokerSuit.Spades,PokerRank.King),
new Card(PokerSuit.Diamond,PokerRank.Ace),
new Card(PokerSuit.Club,PokerRank.Seven),
});
_pokerGameSession.AddPlayer("kid",
new Card[]
{
new Card(PokerSuit.Diamond,PokerRank.Jack),
new Card(PokerSuit.Heart,PokerRank.Ten),
new Card(PokerSuit.Club,PokerRank.King),
new Card(PokerSuit.Heart,PokerRank.Ace),
new Card(PokerSuit.Heart,PokerRank.Seven),
});
_pokerGameSession.PreparePlayersHands();
}
}
}
|
using System;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
namespace XH.Infrastructure.Extensions
{
public static class EnumExtensions
{
public static string GetDescription(this Enum enumValue)
{
var attribute = enumValue.GetType().GetField(enumValue.ToString())?.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
var description = attribute != null ? attribute.Description : String.Empty;
if (description.IsNullOrEmpty())
{
description = enumValue.ToString();
}
return description;
}
}
public static class EnumHelper
{
public static IEnumerable<T> GetEnumValues<T>()
{
var type = typeof(T);
if (!type.IsEnum)
{
throw new InvalidOperationException();
}
return Enum.GetValues(type).Cast<T>().ToList();
}
public static IEnumerable<EnumItem> GetEnumItems<T>()
{
return GetEnumItems(typeof(T));
}
public static IEnumerable<EnumItem> GetEnumItems(Type enumType)
{
if (!enumType.IsEnum)
{
throw new InvalidOperationException();
}
var list = new List<EnumItem>();
foreach (var item in Enum.GetValues(enumType))
{
var attribute = enumType.GetField(item.ToString())?.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
var description = attribute != null ? attribute.Description : item.ToString();
list.Add(new EnumItem
{
Label = description,
Value = item.ToString(),
IntValue = (int)item
});
}
return list;
}
}
public class EnumItem
{
public string Label { get; set; }
public string Value { get; set; }
public int IntValue { get; set; }
}
}
|
using UnityEngine;
namespace AudioVisualizer
{
public class FrequencyBandVisualator : MonoBehaviour
{
public const int Bands = 8;
[SerializeField]
private SpectrumDataProvider m_Provider;
[SerializeField]
private GameObject m_CubePrefab;
[SerializeField]
private float m_MaxScale;
[SerializeField]
private bool m_UseBuffer = true;
[SerializeField]
private float m_BaseDecrease = 0.00001f;
[SerializeField]
private float m_DecreaseMultiple = 1.1f;
private void Start()
{
if (m_CubePrefab == null) return;
for (int i = 0; i < Bands; ++i)
{
var inst = Instantiate(m_CubePrefab, this.transform, false);
inst.name = "Band_" + i;
inst.transform.position = this.transform.position + Vector3.right * 2 * i;
m_SmpleCubes[i] = inst;
}
}
private void Update()
{
if (m_Provider == null) return;
_MakeFrequencyBands();
for (int i = 0; i < Bands; ++i)
{
if (m_SmpleCubes[i] == null) continue;
if (m_UseBuffer)
{
if (m_FrequencyBands[i] > m_BandBuffers[i])
{
m_BandBuffers[i] = m_FrequencyBands[i];
m_BandDecreases[i] = m_BaseDecrease;
}
else if (m_FrequencyBands[i] < m_BandBuffers[i])
{
m_BandBuffers[i] -= m_BandDecreases[i];
m_BandDecreases[i] *= m_DecreaseMultiple;
if (m_BandBuffers[i] < 0f)
m_BandBuffers[i] = 0f;
}
m_SmpleCubes[i].transform.localScale = new Vector3(1, (m_BandBuffers[i] * m_MaxScale) + 1, 1);
}
else
{
m_SmpleCubes[i].transform.localScale = new Vector3(1, (m_FrequencyBands[i] * m_MaxScale) + 1, 1);
}
}
}
private void _MakeFrequencyBands()
{
// Unity可以通過靜態成員 AudioSettings.outputSampleRate 告訴我們混音器的赫茲(Hz)音頻採樣率。
// 這將爲我們提供Unity播放音頻的採樣率,通常爲48000或44100。
// 我們還可以使用AudioClip.frequency獲取單個AudioClip的採樣率。
// FFT的最大支持頻率,這將是採樣率的一半,
// 此時,我們可以除以我們的頻譜長度,以瞭解每個bin(索引)代表的頻率。
/*
* EX:
* Audio clip of frequency is 44100,
* so the FFT max support frequency is 22050(44100/2).
* And the sample is 512,
* so the hertz per sample is 43(22050/512).
*
* Separate to 8 bands
* Sub Bass 20 - 60 Hz
* Bass 60 - 250 Hz
* Low Midrange 250 - 500 Hz
* Midrange 500 - 2k Hz
* Upper Midrange 2k - 4k Hz
* Persence 4k - 6k Hz
* Brilliance 6k - 20k Hz
*
* [0] - 2 = 86 Hz cover( 0 ~ 86)
* [1] - 4 = 172 Hz cover( 87 ~ 258)
* [2] - 8 = 334 Hz cover( 259 ~ 602)
* [3] - 16 = 688 Hz cover( 603 ~ 1290)
* [4] - 32 = 1376 Hz cover( 1291 ~ 2666)
* [5] - 64 = 2752 Hz cover( 2667 ~ 5418)
* [6] - 128 = 5504 Hz cover( 5419 ~ 10922)
* [7] - 256 = 11008 Hz cover(10923 ~ 21930)
* total cover the 510 samples
*/
if (m_Provider == null) return;
int sampleCount = 0;
for (int i = 1; i <= Bands; ++i)
{
int coverSampleCount = (int)Mathf.Pow(2, i);
// Add last 2 samples
if (i == Bands)
coverSampleCount += 2;
float average = 0;
for (int j = 0; j < coverSampleCount; ++j)
{
// Why does he multiply each sample by (Count+1)
// I think this increases the values of high frequencies. If you delete this, it will be too low(as in the 3rd part of the tutorial)
average += m_Provider.SpectrumData[sampleCount];// * (sampleCount +1);
++sampleCount;
}
average /= coverSampleCount;
m_FrequencyBands[i - 1] = average;
}
}
private GameObject[] m_SmpleCubes = new GameObject[Bands];
private float[] m_FrequencyBands = new float[Bands];
private float[] m_BandBuffers = new float[Bands];
private float[] m_BandDecreases = new float[Bands];
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using Dapper;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Embraer_Backend.Models;
namespace Embraer_Backend.Models
{
public class LimpezaParametros
{
public long IdCadParametroLimpeza{get;set;}
public string DescOQue {get;set;}
public string DescMetodoLimpeza {get;set;}
public string TipoControle {get;set;}
public DateTime? DtUltAtlz {get;set;}
public string Status {get;set;}
}
public class LimpezaParametrosModel
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(LimpezaParametrosModel));
public IEnumerable<LimpezaParametros> SelectParametros(IConfiguration _configuration,string TipoControle,string Status)
{
try
{
string sSql = string.Empty;
sSql = "SELECT IdCadParametroLimpeza,DescOQue,DescMetodoLimpeza,TipoControle,DtUltAtlz,Status";
sSql += " FROM TB_CADASTRO_PARAMETROS_LIMPEZA";
sSql += " WHERE 1=1";
if(TipoControle!="" && TipoControle!=null)
sSql = sSql + " AND TipoControle='" + TipoControle + "'";
if(Status!="" && Status!=null)
sSql = sSql + " AND Status='" + Status +"'";
IEnumerable <LimpezaParametros> parametros;
using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa")))
{
parametros = db.Query<LimpezaParametros>(sSql,commandTimeout:0);
}
return parametros;
}
catch (Exception ex)
{
log.Error("Erro LimpezaParametrosModel-SelectParametros:" + ex.Message.ToString());
return null;
}
}
public bool UpdateParametros (IConfiguration _configuration,LimpezaParametros _parametros)
{
try{
string sSql = string.Empty;
sSql = "UPDATE TB_CADASTRO_PARAMETROS_LIMPEZA SET";
sSql+= " DescOQue='"+ _parametros.DescOQue + "'";
sSql+= ",DescMetodoLimpeza='"+ _parametros.DescMetodoLimpeza + "'";
sSql+= ",TipoControle='"+ _parametros.TipoControle + "'";
sSql+= ",Status='"+ _parametros.Status + "'";
sSql+= ",DtUltAtlz=GETDATE()";
sSql+= " WHERE IdCadParametroLimpeza=" + _parametros.IdCadParametroLimpeza;
long update = 0;
using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa")))
{
update = db.Execute(sSql,commandTimeout:0);
}
if(update>0)
{
return true;
}
return false;
}
catch(Exception ex)
{
log.Error("Erro LimpezaParametrosModel-UpdateParametros:" + ex.Message.ToString());
return false;
}
}
public bool InsertParametros(IConfiguration _configuration,LimpezaParametros _prt)
{
string sSql = string.Empty;
try
{
sSql= "INSERT INTO TB_CADASTRO_PARAMETROS_LIMPEZA (DescOQue,DescMetodoLimpeza,TipoControle,DtUltAtlz)";
sSql +=" VALUES ";
sSql +="('" + _prt.DescOQue + "'";
sSql +=",'" + _prt.DescMetodoLimpeza + "'";
sSql +=",'" + _prt.TipoControle + "'";
sSql +=", GETDATE())";
sSql +=" SELECT @@IDENTITY";
long insertId=0;
using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa")))
{
insertId =db.QueryFirstOrDefault<long>(sSql,commandTimeout:0);
}
if(insertId>0)
{
_prt.IdCadParametroLimpeza=insertId;
return true;
}
return false;
}
catch(Exception ex)
{
log.Error("Erro LimpezaParametrosModel-InsertParametros:" + ex.Message.ToString());
return false;
}
}
}
} |
using UnityEngine;
using System;
public partial class Sway : MonoBehaviour
{
public interface IMoveTo
{
bool CanSetup { get; }
IMoveTo Delay(float value);
IMoveTo IgnoreTimeScale(bool value);
IMoveTo Space(Space space);
IMoveTo EaseType(AnimationCurve curve);
IMoveTo Forward(AnimationCurve curve);
IMoveTo Up(AnimationCurve curve);
IMoveTo OnStart(Action action);
IMoveTo OnUpdate(Action action);
IMoveTo OnComplete(Action<float> action);
}
private class MoveToTween : Base<IMoveTo>, IMoveTo
{
private static MoveToTween s_defaultSetup = new MoveToTween(s_singleton.transform, Vector3.zero, 0);
public static IMoveTo DefaultSetup
{
get
{
s_defaultSetup.Stop();
return s_defaultSetup;
}
}
private static readonly Quaternion s_rotation = Quaternion.Euler(0, 270, 0);
private Vector3 m_startPosition = Vector3.zero;
private Vector3 m_endPosition = Vector3.zero;
private float m_distance = 0;
private Space m_space = UnityEngine.Space.World;
private Vector3 m_forward = Vector3.forward;
private Vector3 m_up = Vector3.up;
private AnimationCurve m_moveForwardCurve = PathType.Linear;
private AnimationCurve m_moveUpCurve = PathType.Linear;
public MoveToTween(Transform target, Vector3 position, float time)
: base(target, time)
{
m_endPosition = position;
Space(m_space);
}
protected override void OnUpdate(float currentTime, float easeTypeCurveValue)
{
float moveForwardCurveValue = m_distance * m_moveForwardCurve.Evaluate(easeTypeCurveValue);
float moveUpCurveValue = m_distance * m_moveUpCurve.Evaluate(easeTypeCurveValue);
// Calculate current position
Vector3 currentPosition = m_startPosition + (m_endPosition - m_startPosition) * easeTypeCurveValue + m_forward * moveForwardCurveValue + m_up * moveUpCurveValue;
//
if (m_space == UnityEngine.Space.World)
m_target.position = currentPosition;
else
m_target.localPosition = currentPosition;
}
#region --- Setup Function ---
/// <summary> Default - World </summary>
public IMoveTo Space(Space space)
{
if (!CanSetup)
return this;
m_space = space;
if (m_target != null)
{
m_startPosition = (m_space == UnityEngine.Space.World) ? (m_target.position) : (m_target.localPosition);
m_distance = Vector3.Distance(m_startPosition, m_endPosition);
// Get Forward and Up Vector
Quaternion currentRotation = m_target.rotation;
m_target.rotation = (m_endPosition - m_startPosition != Vector3.zero)
? Quaternion.LookRotation(m_endPosition - m_startPosition) * s_rotation
: m_target.rotation;
m_forward = m_target.forward;
m_up = m_target.up;
m_target.rotation = currentRotation;
}
return this;
}
/// <summary> Default - Linear </summary>
public IMoveTo Forward(AnimationCurve curve)
{
if (CanSetup)
m_moveForwardCurve = (curve != null) ? (curve) : (PathType.Linear);
return this;
}
/// <summary> Default - Linear </summary>
public IMoveTo Up(AnimationCurve curve)
{
if (CanSetup)
m_moveUpCurve = (curve != null) ? (curve) : (PathType.Linear);
return this;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Capstone.Classes
{
//Drink inherits from IProduct
public class Drink : IProduct
{
/// <summary>
/// Constructor for product with shared characteristics
/// </summary>
/// <param name="name">Name of product as a string</param>
/// <param name="price">Price of product as a decimal</param>
/// <param name="slot">Slot of product as a string</param>
/// <param name="inventoryCount">Amount of product as an int</param>
public Drink(string name, decimal price, string slot, int inventoryCount)
{
if (name == null)
{
Name = "Invalid Product Name";
} else
{
Name = name;
}
if (price < 0)
{
Price = 0M;
} else
{
Price = price;
}
if (slot == null)
{
Slot = "Invalid Slot";
} else
{
Slot = slot;
}
if (inventoryCount < 0)
{
InventoryCount = 0;
} else
{
InventoryCount = inventoryCount;
}
}
/// <summary>
/// The name of the product
/// </summary>
public string Name { get; }
/// <summary>
/// The price of the product
/// </summary>
public decimal Price { get; }
/// <summary>
/// The slot in the machine at which the product is stored
/// </summary>
public string Slot { get; }
/// <summary>
/// The amount of the product in the machine
/// </summary>
public int InventoryCount { get; set; }
/// <summary>
/// Method that creates specific return message for Chips
/// </summary>
/// <returns>Product's output message</returns>
public string ProductOutputMessage()
{
return "Glug Glug, Yum!";
}
}
}
|
using EPI.BinaryTree;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EPI.UnitTests.BinaryTree
{
[TestClass]
public class FindSuccessorInorderTraversalUnitTest
{
[TestMethod]
public void FindInorderSuccessor()
{
BinaryTree<char> tree = new BinaryTree<char>()
{
Root = new BinaryTreeNode<char>('A')
{
Left = new BinaryTreeNode<char>('B')
{
Left = new BinaryTreeNode<char>('C')
{
Right = new BinaryTreeNode<char>('D')
},
Right = new BinaryTreeNode<char>('E')
{
Left = new BinaryTreeNode<char>('F')
}
},
Right = new BinaryTreeNode<char>('G')
{
Left = new BinaryTreeNode<char>('H')
{
Right = new BinaryTreeNode<char>('I')
{
Left = new BinaryTreeNode<char>('J')
}
}
}
}
};
FindSuccessorInorderTraversal<char>.FindSuccessor(tree.Root).Value.Should().Be('H');
FindSuccessorInorderTraversal<char>.FindSuccessor(tree.Root.Left).Value.Should().Be('F');
FindSuccessorInorderTraversal<char>.FindSuccessor(tree.Root.Right).Should().BeNull();
FindSuccessorInorderTraversal<char>.FindSuccessor(tree.Root.Left.Left).Value.Should().Be('D');
FindSuccessorInorderTraversal<char>.FindSuccessor(tree.Root.Left.Left.Right).Value.Should().Be('B');
FindSuccessorInorderTraversal<char>.FindSuccessor(tree.Root.Left.Right).Value.Should().Be('A');
FindSuccessorInorderTraversal<char>.FindSuccessor(tree.Root.Left.Right.Left).Value.Should().Be('E');
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ObjectDetect.Models;
using TensorFlow;
namespace ObjectDetect
{
/// <summary>
/// Get the Tensor values as json object
/// </summary>
public class GetTensorObject
{
private static IEnumerable<CatalogItem> _catalog;
//private static string _input = "input.jpg";
private static string _catalogPath = "mscoco_label_map_nl.pbtxt";
private static string _modelPath = "ssd_mobilenet_v1_coco_2017_11_17.pb";
private static double MIN_SCORE_FOR_OBJECT_HIGHLIGHTING = 0.65;
/// <summary>
/// Get the TensorFlow object detection data
/// </summary>
/// <param name="input">path of source file</param>
/// <returns>Returns a ImageHolder object with all object data</returns>
public static ImageHolder GetJsonFormat(string input)
{
var orientationValue = ImageRotation.GetExifRotate(input);
ImageRotation.RotateImageByExifOrientationData(input, input);
// A Catalog is a indexed file which descried the names of the objects
_catalog = CatalogUtil.ReadCatalogItems(_catalogPath);
string modelFile = _modelPath;
// Load the model into the memory in place of the empty `TFGraph()`.
using (var graph = new TFGraph())
{
var model = File.ReadAllBytes(modelFile);
graph.Import(new TFBuffer(model));
// Start a new session to do a numerical computation.
using (var session = new TFSession(graph))
{
// The variable input is a string with the path of the file.
// This is imported as a multidimensional array, this is also called a Tensor.
var tensor = ImageUtil.CreateTensorFromImageFile(input, TFDataType.UInt8);
// Use the runner class to easily configure inputs,
// outputs and targets to be passed to the session runner.
var runner = session.GetRunner();
runner
.AddInput(graph["image_tensor"][0], tensor)
.Fetch(
graph["detection_boxes"][0],
graph["detection_scores"][0],
graph["detection_classes"][0],
graph["num_detections"][0]);
var output = runner.Run();
// ReSharper disable once ArgumentsStyleLiteral
// ReSharper disable once RedundantArgumentDefaultValue
var boxes = (float[,,])output[0].GetValue(jagged: false);
// ReSharper disable once ArgumentsStyleLiteral
// ReSharper disable once RedundantArgumentDefaultValue
var scores = (float[,])output[1].GetValue(jagged: false);
// ReSharper disable once ArgumentsStyleLiteral
// ReSharper disable once RedundantArgumentDefaultValue
var classes = (float[,])output[2].GetValue(jagged: false);
//var num = (float[])output[3].GetValue(jagged: false);
// The boxes, scores and classes are arrays.
// I use GetBoxes to get the values of the objects from these arrays.
// Program.DrawBoxes(boxes, scores, classes, input, "test.jpg", MIN_SCORE_FOR_OBJECT_HIGHLIGHTING);
var getBoxes = GetBoxes(boxes, scores, classes, input, MIN_SCORE_FOR_OBJECT_HIGHLIGHTING);
getBoxes.Orientation = orientationValue;
getBoxes.Results = getBoxes.Data.Count;
return getBoxes;
}
}
}
/// <summary>
/// Get the ImageHolder object with the width and height of the image and the boxes
/// </summary>
/// <param name="boxes">boxes tensor</param>
/// <param name="scores">scores tensor</param>
/// <param name="classes">classes tensor</param>
/// <param name="inputFile">path of source file</param>
/// <param name="minScore">min score 0-1</param>
/// <returns>Returns a ImageHolder object with all object data</returns>
private static ImageHolder GetBoxes(float[,,] boxes, float[,] scores, float[,] classes, string inputFile, double minScore)
{
//var boxesList = new List<ImageHolder>();
var boxesList = new ImageHolder();
boxesList.Dimensions = ImageMeta.GetJpegDimensions(inputFile);
var x = boxes.GetLength(0);
var y = boxes.GetLength(1);
var z = boxes.GetLength(2);
float ymin = 0, xmin = 0, ymax = 0, xmax = 0;
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (scores[i, j] < minScore) continue; // <
int value = Convert.ToInt32(classes[i, j]);
Console.WriteLine(value);
for (int k = 0; k < z; k++)
{
var box = boxes[i, j, k];
switch (k)
{
case 0:
ymin = box;
break;
case 1:
xmin = box;
break;
case 2:
ymax = box;
break;
case 3:
xmax = box;
break;
}
}
CatalogItem catalogItem = _catalog.FirstOrDefault(item => item.Id == value);
//Console.WriteLine(xmax);
//Console.WriteLine(ymax);
//Console.WriteLine(boxesList.Dimensions.Width);
//Console.WriteLine(boxesList.Dimensions.Height);
if (!string.IsNullOrEmpty(catalogItem?.DisplayName))
{
// Calculate the absolute width and height of a object
float left;
float right;
float top;
float bottom;
(left, right, top, bottom) =
(xmin * boxesList.Dimensions.Width, xmax * boxesList.Dimensions.Width,
ymin * boxesList.Dimensions.Height, ymax * boxesList.Dimensions.Height);
var boxesItem = new ImageMetaData
{
Keyword = catalogItem.DisplayName,
Class = catalogItem.Id,
Left = left,
Right = right,
Bottom = bottom,
Top = top,
Height = bottom - top,
Width = bottom - top,
Score = scores[i, j]
};
boxesList.Data.Add(boxesItem);
boxesList.KeywordList.Add(catalogItem.DisplayName);
}
}
}
return boxesList;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrintDirection : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 forward = transform.forward;
//print(forward);
}
}
|
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Web.ViewModels;
namespace Web.Interfaces
{
public interface IHomeIndexViewModelService
{
Task<HomeIndexViewModel> GetHomeIndexViewModel(int pageIndex,int itemsPerPage, int? categoryId,int? brandId);
Task<List<SelectListItem>> GetSCategories();
Task<List<SelectListItem>> GetSBrans();
}
}
|
using UnityEngine;
using System.Collections;
public class MoveScroll : MonoBehaviour {
public float speed;
public float speedLimit;
public AccelerationFunction acceleration;
public Animator playerAnimator;
public Transform movementLimit;
private float currentDistance;
private float currentCooldown;
private bool loadedAnimationEvents;
// Use this for initialization
void Start () {
acceleration = new ConstantAcceleration (4, 1);
currentCooldown = 0;
loadedAnimationEvents = false;
}
// Update is called once per frame
void Update () {
if (!loadedAnimationEvents)
{
// add animation events
Animator animator = playerAnimator;
AnimationInfo[] clips = animator.GetCurrentAnimationClipState(0);
if (clips.Length != 0)
{
//AnimationClip clip = clips[0].clip;
//AnimationEvent animationEvent = new AnimationEvent();
//animationEvent.functionName = "Step";
//animationEvent.time = clip.length;
//clip.AddEvent(animationEvent);
loadedAnimationEvents = true;
}
}
if (currentCooldown > 0) {
audio.Stop();
currentCooldown -= Time.deltaTime;
if (currentCooldown == 0) {
currentCooldown = -1;
}
return;
}
if (currentCooldown < 0) {
currentCooldown = 0;
BroadcastMessage("ReleaseControls");
audio.Play();
}
if (movementLimit != null && transform.position.x >= movementLimit.position.x)
{
gameObject.transform.parent.BroadcastMessage("FinishGame", true);
speed *= 0.975f;
if (speed <= 0.1f)
{
speed = 0.0f;
GameObject.Find("Game").SendMessage("YouWin");
}
transform.position += new Vector3(speed * Time.deltaTime, 0.0f, 0.0f);
playerAnimator.SetFloat("Speed", speed / speedLimit);
return;
}
Vector3 newPosition = transform.position;
newPosition.x += speed * Time.deltaTime;
transform.position = newPosition;
// Solo actualizo la velocidad si estoy por debajo del limite
if (speed < speedLimit) {
speed = acceleration.Accelerate (speed, Time.deltaTime);
// Compruebo que no me haya pasado del limite
if (speed > speedLimit) {
speed = speedLimit;
}
}
currentDistance += speed * Time.deltaTime;
playerAnimator.SetFloat("Speed", speed / speedLimit);
}
public void SetCooldown(float cooldown) {
currentCooldown = cooldown;
}
void FinishGame(bool win) {
audio.Stop();
if (!win) {
speed = 0.0f;
acceleration = new ConstantAcceleration(0, 0);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Models
{
public class Register
{
public int Id { get; set; }
public string OpeningUsername { get; set; }
public string ClosingUsername { get; set; }
public DateTime CreateDate { get; set; }
public DateTime OpeningTime { get; set; }
public DateTime? ClosingTime { get; set; }
public int HundredBillsOpening { get; set; }
public int FiftyBillsOpening { get; set; }
public int TwentyBillsOpening { get; set; }
public int TenBillsOpening { get; set; }
public int FiveBillsOpening { get; set; }
public int OneBillsOpening { get; set; }
public int OneCoinsOpening { get; set; }
public int FiftyCentsCoinsOpening { get; set; }
public int QuarterCoinsOpening { get; set; }
public int TenCentsCoinsOpening { get; set; }
public int FiveCentsCoinsOpening { get; set; }
public int OneCentCoinsOpening { get; set; }
public int HundredBillsClosing { get; set; }
public int FiftyBillsClosing { get; set; }
public int TwentyBillsClosing { get; set; }
public int TenBillsClosing { get; set; }
public int FiveBillsClosing { get; set; }
public int OneBillsClosing { get; set; }
public int OneCoinsClosing { get; set; }
public int FiftyCentsCoinsClosing { get; set; }
public int QuarterCoinsClosing { get; set; }
public int TenCentsCoinsClosing { get; set; }
public int FiveCentsCoinsClosing { get; set; }
public int OneCentCoinsClosing { get; set; }
public int CashTransactionCount { get; set; }
public decimal CashTransactionAmount { get; set; }
public int DebitTransactionCount { get; set; }
public decimal DebitTransactionAmount { get; set; }
public int CreditTransactionCount { get; set; }
public decimal CreditTransactionAmount { get; set; }
public int CheckTransactionCount { get; set; }
public decimal CheckTransactionAmount { get; set; }
public int TransferTransactionCount { get; set; }
public decimal TransferTransactionAmount { get; set; }
public virtual IList<RegisterCashExit> RegisterCashExits { get; set; }
public virtual Store Store { get; set; }
public int StoreId { get; set; }
public Register()
{
CreateDate = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
OpeningTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
CashTransactionCount = 0;
CashTransactionAmount = 0m;
DebitTransactionCount = 0;
DebitTransactionAmount = 0m;
}
public decimal GetActualAmount()
{
var existsCash = RegisterCashExits.Where(r => !r.CashEntering).Sum(r => r.Amount);
var entersCash = RegisterCashExits.Where(r => r.CashEntering).Sum(r => r.Amount);
var opening = GetOpeningAmount();
return opening + (entersCash - existsCash);
}
public decimal GetOpeningAmount()
{
var totalAmount = 0m;
totalAmount += HundredBillsOpening * 100;
totalAmount += FiftyBillsOpening * 50;
totalAmount += TwentyBillsOpening * 20;
totalAmount += TenBillsOpening * 10;
totalAmount += FiveBillsOpening * 5;
totalAmount += OneBillsOpening * 1;
totalAmount += OneCoinsOpening * 1;
totalAmount += FiftyCentsCoinsOpening * 0.5m;
totalAmount += QuarterCoinsOpening * 0.25m;
totalAmount += TenCentsCoinsOpening * 0.1m;
totalAmount += FiveCentsCoinsOpening * 0.05m;
totalAmount += OneCentCoinsOpening * 0.01m;
return totalAmount;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IcePath_Waka : MonoBehaviour {
// How long until the next leap?
[Header("Leap time")]
[SerializeField]
private float leapTime;
float leapAlarm;
// How long in the air?
[Header("Air time")]
[SerializeField]
private float airTime;
float airAlarm;
// Tile info
Vector2[] tilePos = new Vector2[2];
int tileCurrent;
public static bool isPassable = true;
// Use this for initialization
void Start () {
// The tiles
tilePos[0] = IcePath_Generate.globalWakaStart;
tilePos[1] = IcePath_Generate.globalWakaEnd;
tileCurrent = 0;
airAlarm = airTime;
}
// Update is called once per frame
void Update () {
// Leap timing
if (leapAlarm > 0) {
leapAlarm -= Time.deltaTime;
} else {
// Prepare the variables
int start = tileCurrent;
int finish = tileCurrent == 0 ? 1 : 0;
Vector2 startTile = tilePos[start];
Vector2 finishTile = tilePos[finish];
Vector2 direction = (finishTile - startTile).normalized;
float dist = (finishTile - startTile).magnitude;
float speed = dist / airTime;
// Leap into the air
if ((((Vector2)transform.position) - finishTile).magnitude > 0.33f) {
transform.position = (Vector2)transform.position + (direction * speed * Time.deltaTime);
isPassable = isWithin(airAlarm, 0.2f * airTime, 0.4f * airTime);
airAlarm -= Time.deltaTime;
} else {
transform.position = finishTile;
tileCurrent = finish;
isPassable = true;
airAlarm = airTime;
leapAlarm = leapTime;
}
}
}
bool isWithin(float input, float min, float max) {
// Is the value within this range?
return (input >= min &&
input <= max);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Jetpack : MonoBehaviour
{
public GameObject[] particle;
public AudioSource audioSource;
// Start is called before the first frame update
void Start()
{
particle[0].SetActive(false);
particle[1].SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && UIController.IsPlaying)
{
audioSource.Play();
}
else if (Input.GetMouseButton(0) && UIController.IsPlaying)
{
particle[0].SetActive(true);
particle[1].SetActive(true);
}
else if (Input.GetMouseButtonUp(0))
{
particle[0].SetActive(false);
particle[1].SetActive(false);
audioSource.Stop();
}
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began && UIController.IsPlaying)
{
audioSource.Play();
}
else if (touch.phase == TouchPhase.Moved && UIController.IsPlaying)
{
particle[0].SetActive(true);
particle[1].SetActive(true);
}
else if (touch.phase == TouchPhase.Ended)
{
particle[0].SetActive(false);
particle[1].SetActive(false);
audioSource.Stop();
}
}
}
}
|
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using QuizApplication.Models;
using ColorConverter = System.Windows.Media.ColorConverter;
using FontFamily = System.Windows.Media.FontFamily;
using Color = System.Windows.Media.Color;
namespace QuizApplication {
public partial class SecondWindow : Window {
public SecondWindow() {
InitializeComponent();
this.KeyDown += CommonMethods.KeyEvents;
Settings.Theme.ApplyConfiguration(this);
BtnClose.Click += CommonMethods.CloseWindow_OnClick;
BtnMaxMin.Click += CommonMethods.MaxMin_Click;
Label_CategoryName.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Settings.Theme.TextColor));
Label_CategoryName.FontFamily = new FontFamily(Settings.Theme.TextFontFamily);
ConfigurationButtons();
}
private void ConfigurationButtons() {
SolidColorBrush color = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Settings.Theme.ButtonBackgroundColor)) {
Opacity = Settings.Theme.ButtonTransparency / 100.0
};
var buttonStyle = Resources["btnStyle"] as Style;
buttonStyle?.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString(Settings.Theme.ButtonTextColor))));
buttonStyle?.Setters.Add(new Setter(FontFamilyProperty, new FontFamily(Settings.Theme.ButtonFontFamily)));
buttonStyle?.Setters.Add(new Setter(BackgroundProperty, color));
foreach (var button in Grid_Buttons.Children.OfType<Button>()) {
button.Content = Settings.Game.CategoriesList[ Convert.ToInt32(button.Tag) - 1 ];
button.Style = buttonStyle;
button.Click += Buttons_Click;
button.MouseEnter += Buttons_MouseEnter;
button.MouseLeave += Buttons_MouseLeave;
}
}
private void Buttons_Click(object sender, RoutedEventArgs e) {
Settings.Game.ActiveCategoryId = Convert.ToInt32(((Button)sender).Tag);
var window = new ThirdWindow();
window.Show();
if (WindowState == WindowState.Maximized)
window.WindowState = WindowState.Maximized;
((Button)sender).Visibility = Visibility.Hidden;
}
private static void Buttons_MouseEnter(object sender, MouseEventArgs e)
=> ((Button)sender).Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Settings.Theme.ButtonBackgroundColor)) {
Opacity = Settings.Theme.ButtonTransparency > 90 ? (Settings.Theme.ButtonTransparency - 10) / 100.0 : (Settings.Theme.ButtonTransparency + 10) / 100.0
};
private static void Buttons_MouseLeave(object sender, MouseEventArgs e)
=> ((Button)sender).Background = new SolidColorBrush((Color) ColorConverter.ConvertFromString(Settings.Theme.ButtonBackgroundColor)) {
Opacity = Settings.Theme.ButtonTransparency / 100.0
};
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Pokemon_Internal_Blades_CSharp.Items
{
/// <summary>
/// Evolution Item class
/// </summary>
public class EvolutionItem : Item
{
const int I_FIRE_STONE = 28;
const int I_WATER_STONE = 29;
const int I_THUNDERSTONE = 30;
const int I_LEAF_STONE = 31;
const int I_MOON_STONE = 32;
const int I_SUN_STONE = 33;
const int I_DAWN_STONE = 34;
const int I_DUSK_STONE = 35;
const int I_SHINY_STONE = 36;
/// <summary>
/// Default Constructor.
/// </summary>
public EvolutionItem()
{
base.SetName("Fire Stone");
SetStone();
base.SetHoldable(true);
base.SetValue(5000);
}
/// <summary>
/// Constructor for an Evolution Item
/// </summary>
/// <param name="name">Name of the Evolution Item</param>
/// <param name="value">Value of the Evolution Item</param>
public EvolutionItem(string name, long value)
{
base.SetName(name);
SetStone();
base.SetHoldable(true);
base.SetValue(Math.Abs(value));
}
private int m_stone;
/// <summary>
/// Evolves the Target. This should check to see if it can evolve the target first using target.CanEvolve();
/// </summary>
/// <param name="target">The target of the Evolution Item.</param>
public void EvolveTarget(Pokemon target)
{
base.SetTarget(target);
if (target.CanEvolve())
{
if (target.MethodOfEvolution() == m_stone)
{
target.Evolve();
}
}
}
/// <summary>
/// Sets the Stone Type for the Method EvolveTarget(Pokemon target);
/// </summary>
private void SetStone()
{
switch (base.GetName())
{
case "Water Stone":
m_stone = I_WATER_STONE;
break;
case "Fire Stone":
m_stone = I_FIRE_STONE;
break;
case "Thunderstone":
m_stone = I_THUNDERSTONE;
break;
case "Leaf Stone":
m_stone = I_LEAF_STONE;
break;
case "Moon Stone":
m_stone = I_MOON_STONE;
break;
case "Sun Stone":
m_stone = I_SUN_STONE;
break;
case "Shiny Stone":
m_stone = I_SHINY_STONE;
break;
case "Dawn Stone":
m_stone = I_DAWN_STONE;
break;
case "Dusk Stone":
m_stone = I_DUSK_STONE;
break;
default:
m_stone = I_FIRE_STONE;
break;
}
}
}
}
|
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Astral.Extensions.Cqrs.Abstractions.Handlers;
using Microsoft.AspNetCore.Hosting;
using SocketTraining.Server.FileService.Commands;
namespace SocketTraining.Server.FileService.Handlers
{
/// <summary>
/// Обработчик команды загрузки файла на сервер
/// </summary>
public class AddFileCommandHandler : ICommandHandler<AddFileCommand,string>
{
private readonly IWebHostEnvironment _appEnvironment;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="appEnvironment"></param>
public AddFileCommandHandler(IWebHostEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
/// <inheritdoc />
public async Task<string> Handle(AddFileCommand request, CancellationToken cancellationToken)
{
if (request.File == null)
return "empty file request(wrong filename?";
var path = _appEnvironment.WebRootPath + "\\" + request.File.FileName;
await using var fileStream = new FileStream(path, FileMode.Create);
await request.File.CopyToAsync(fileStream, cancellationToken);
return $"File { request.File.FileName} added";
}
}
}
|
using MetodosAbstratosCsharp.Entities;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace MetodosAbstratosCsharp
{
class Program
{
public static List<Pessoa> pessoas = new List<Pessoa>();
static void Main(string[] args)
{
Console.WriteLine("Entre com a quantidade de contribuintes: ");
int n = int.Parse(Console.ReadLine());
for(int i = 1; i<=n; i++)
{
Console.WriteLine($"Entre com os dados do #{i} contrinuinte");
Console.Write("Pessoa Física ou Jurídia? F/J ");
string resposta = Console.ReadLine();
if (resposta == "F" || resposta == "f")
{
Console.Write("Nome: ");
string nome = Console.ReadLine();
Console.Write("Renda anual declarada: ");
double renda = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Console.Write("Valor com gastos em saúde: ");
double gastos = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
pessoas.Add(new PessoaFisica(nome, renda, gastos));
}
else if(resposta == "J" || resposta == "j")
{
Console.Write("Nome: ");
string nome = Console.ReadLine();
Console.Write("Renda anual declarada: ");
double renda = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Console.Write("Quantidade de funcionários: ");
int funcionarios = int.Parse(Console.ReadLine());
pessoas.Add(new PessoaJuridica(nome, renda, funcionarios));
}
else
{
Console.WriteLine("Dado inserido incorretamente, favor refazer solicitação deste contribuinte");
}
}
Console.WriteLine(" ");
Console.WriteLine("Contrinuintes: ");
double soma = 0;
foreach (Pessoa pessoa in pessoas)
{
Console.WriteLine(pessoa.Nome +" $"+ pessoa.ValorPago().ToString("F2", CultureInfo.InvariantCulture));
soma += pessoa.ValorPago();
}
Console.WriteLine("Total de valor arrecadado: "+ soma.ToString("F2", CultureInfo.InvariantCulture));
}
}
}
|
/*
* Created by: Andrew Kuekam
* Created on: 2020-04-01
* Created for: ICS3U Programming
* Daily Assignment – Day #12 - Pizza Cost
* This program...
*/
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 PizzaCostAndrew
{
public partial class frmPizzaCost : Form
{
public frmPizzaCost()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//declare local variables
double Diameter, costAfterTax;
//convert the diameter to a double
Diameter = double.Parse(txtDiameter.Text);
//calculate the cost before and after tax
costAfterTax = 0.50 * Diameter + 0.99 + 0.75;
//display the cost in the label, rounded to 2 decimal places
lblcostAfterTax.Text = String.Format("$(8:76)", costAfterTax);
//show Cost Answer
this.lblcostAfterTax.Show();
this.lblcost.Show();
}
private void frmPizzaCost_Load(object sender, EventArgs e)
{
//hide Cost Answer
this.lblcostAfterTax.Hide();
this.lblcost.Hide();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
//this close the program
this.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Blazor_AppForTest.Pages
{
public interface ILoginLogic
{
bool SignIn(string email,string password);
}
}
|
using Project.Object;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project.Interface
{
interface IMainPage
{
UserInfObject userInfo { get; set; }
DataGridView subjectList { get; set; }
DataGridView eventList { get; set; }
Label lblSubjectsEnrolled { get; set; }
int minuteRange { get; set; }
int minuteNotifyEvery { get; set; }
NotifyIcon notifyIcon { get; set; }
Form mainpageForm { get; }
ContextMenuStrip contextMenu { get; set; }
}
}
|
using gView.Desktop.Wpf.Controls;
using gView.Framework.UI;
using System;
using System.Windows;
namespace gView.Win.DataExplorer.Items
{
internal class DropDownToolButton : Fluent.DropDownButton
{
private IExToolMenu _tool;
private bool _checked = false;
public DropDownToolButton(IExToolMenu tool)
{
_tool = tool;
if (_tool == null || _tool.DropDownTools == null)
{
return;
}
if (_tool != null && _tool.SelectedTool != null)
{
base.Icon = base.LargeIcon = ImageFactory.FromBitmap(_tool.SelectedTool.Image as global::System.Drawing.Image);
base.Header = _tool.SelectedTool.Name;
}
foreach (IExTool t in _tool.DropDownTools)
{
DropDownToolButtonItem item = new DropDownToolButtonItem(this, t);
item.Click += new RoutedEventHandler(button_Click);
base.Items.Add(item);
}
}
void button_Click(object sender, EventArgs e)
{
if (!(sender is DropDownToolButtonItem))
{
return;
}
_tool.SelectedTool = ((DropDownToolButtonItem)sender).Tool;
base.Icon = base.LargeIcon = ImageFactory.FromBitmap(_tool.SelectedTool.Image as global::System.Drawing.Image);
base.Header = _tool.SelectedTool.Name;
this.OnClick();
}
public IExTool Tool
{
get { return _tool.SelectedTool; }
}
#region ICheckAbleButton Member
public bool Checked
{
get
{
return _checked;
}
set
{
_checked = value;
}
}
#endregion
#region Events
public event RoutedEventHandler Click = null;
public void OnClick()
{
if (Click != null)
{
Click(this, new RoutedEventArgs());
}
}
#endregion
}
internal class DropDownToolButtonItem : Fluent.Button
{
private IExTool _tool;
private DropDownToolButton _parent;
public DropDownToolButtonItem(DropDownToolButton parent, IExTool tool)
{
_parent = parent;
_tool = tool;
base.Icon = base.LargeIcon = ImageFactory.FromBitmap(tool.Image as global::System.Drawing.Image);
base.Header = tool.Name;
base.SizeDefinition = "Middle";
}
public IExTool Tool
{
get { return _tool; }
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
using FiiiChain.Messages;
using System;
using System.Collections.Generic;
using System.Text;
namespace FiiiChain.DataAgent
{
[Serializable]
public class TransactionPoolItem
{
public TransactionPoolItem(long feeRate, TransactionMsg transaction)
{
this.FeeRate = feeRate;
this.Transaction = transaction;
}
public TransactionMsg Transaction { get; set; }
/// <summary>
/// 费率 fiii/KB
/// </summary>
public long FeeRate { get; set; }
public bool Isolate { get; set; }
}
}
|
using System;
using SQLite;
using System.ComponentModel;
namespace iPadPos
{
public class Settings : BaseModel
{
public const string LastPostedChangeKey = "LastPostedChange";
public const string LastPostedInvoiceKey = "LastPostedInvoice";
public const string HasDataKey = "HadData";
static Settings shared;
public static Settings Shared {
get {
return shared ?? (shared = new Settings());
}
}
public Settings ()
{
Database.Main.CreateTable<Setting> ();
}
public string CurrentServerUrl
{
get{ return TestMode ? TestServerUrl : ServerUrl; }
}
public string CurrentCCAcountKey
{
get{ return TestMode ? TestCCAccountKey : CCAcountKey; }
}
public CreditCardProcessorType CreditCardProcessor {
get {
return (CreditCardProcessorType)GetInt("CreditCardProcessor");
}
set {
SetValue("CreditCardProcessor",(int)value);
iPadPos.CreditCardProcessor.Shared = null;
}
}
public string PaypalId {
get {
return GetStringValue("PaypalId");
}
set {
SetValue("PaypalId",value);
ProcPropertyChanged ("PaypalId");
}
}
#region PayAnywhere
public string PayAnywhereLogin
{
get{ return GetStringValue ("PayAnywhereLogin") ?? "603612"; }
set {
SetValue("PayAnywhereLogin",value);
ProcPropertyChanged ("PayAnywhereLogin");
}
}
public string PayAnywhereMerchantId
{
get{ return GetStringValue ("PayAnywhereMerchantId") ?? "8788292185463"; }
set {
SetValue("PayAnywhereMerchantId",value);
ProcPropertyChanged ("PayAnywhereMerchantId");
}
}
public string PayAnywhereUserId
{
get{ return GetStringValue ("PayAnywhereUserId") ?? "mkpa789279"; }
set {
SetValue("PayAnywhereUserId",value);
ProcPropertyChanged ("PayAnywhereUserId");
}
}
public string PayAnywherePw
{
get{ return GetStringValue ("PayAnywherePw") ?? "B6XVmeBA"; }
set {
SetValue("PayAnywherePw",value);
ProcPropertyChanged ("PayAnywherePw");
}
}
#endregion // PayAnywhere
public string CCAcountKey
{
get{
string apiUri = GetStringValue("CCAcountKey");
return apiUri ?? "acc_1dae92cb8808e3ce";
}
set{
SetValue ("CCAcountKey", value);
ProcPropertyChanged ("CCAcountKey");
}
}
public string TestCCAccountKey
{
get{
string apiUri = GetStringValue("TestCCAccountKey");
return apiUri ?? "acc_1dae92cb8808e3ce";
}
set{
SetValue ("TestCCAccountKey", value);
ProcPropertyChanged ("CCAcountKey");
}
}
public string ServerUrl
{
get{
string apiUri = GetStringValue("Server");
if (!string.IsNullOrEmpty (apiUri) && !apiUri.EndsWith ("/"))
apiUri += "/";
return apiUri ?? "http://clancey.dyndns.org:32021/api/";
}
set{
SetValue ("Server", value);
ProcPropertyChanged ("ServerUrl");
}
}
public string TestServerUrl
{
get{
string apiUri = GetStringValue("TestServer");
if (!string.IsNullOrEmpty (apiUri) && !apiUri.EndsWith ("/"))
apiUri += "/";
return apiUri ?? "http://clancey.dyndns.org:32021/api/";
}
set{
SetValue ("TestServer", value);
ProcPropertyChanged ("TestServer");
}
}
public bool TestMode
{
get{return GetBool ("TestMode");}
set{
SetValue ("TestMode", value);
ProcPropertyChanged ("TestMode");
}
}
public double LastPostedChange {
get { return GetDouble (LastPostedChangeKey); }
set {
SetValue (LastPostedChangeKey, value);
ProcPropertyChanged ("LastPostedChangeString");
}
}
public string LastPostedInvoice {
get { return GetStringValue (LastPostedInvoiceKey); }
set {
SetValue (LastPostedInvoiceKey, value);
}
}
public string LastPostedChangeString
{
get{ return LastPostedChange.ToString ("C"); }
set{ LastPostedChange = string.IsNullOrEmpty(value) ? 0 : double.Parse (value, System.Globalization.NumberStyles.Currency); }
}
public bool HasData
{
get{ return GetBool (HasDataKey); }
set{ SetValue (HasDataKey, value); }
}
public int CurrentInvoice {
get {
return GetInt ("CurrentInvoice"); }
set {
SetValue ("CurrentInvoice", value);
}
}
public string CashCustomer
{
get { return GetStringValue ("CashCustomerId") ?? "CASH"; }
set {
SetValue ("CashCustomerId", value);
}
}
public int RegisterId
{
get{ return Math.Max(GetInt ("RegisterId"),1); }
set{ SetValue ("RegisterId", value); }
}
public string GetStringValue(string key)
{
var setting = Database.Main.Table<Setting> ().Where (x => x.Key == key).FirstOrDefault ();
return setting == null ? null : setting.Value;
}
public double GetDouble(string key)
{
double value;
return double.TryParse (GetStringValue (key), out value) ? value : 0;
}
public int GetInt(string key)
{
int value;
return int.TryParse (GetStringValue (key), out value) ? value : 0;
}
public bool GetBool(string key)
{
bool value;
return bool.TryParse (GetStringValue (key), out value) && value;
}
public void SetValue(string key, string value)
{
var oldValue = GetStringValue (key);
Database.Main.InsertOrReplace (new Setting{ Key = key, Value = value });
if (oldValue != value)
ProcPropertyChanged (key);
}
public void SetValue(string key, int value)
{
SetValue (key, value.ToString ());
}
public void SetValue(string key, object value)
{
SetValue (key, value.ToString ());
}
// public void SetValue(string key, bool value)
// {
// SetValue (key, value.ToString ());
// }
class Setting
{
[PrimaryKey]
public string Key {get;set;}
public string Value {get;set;}
}
}
}
|
namespace MasterDetail
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class TraceabilityWorkShift
{
[JsonProperty("ID")]
public int Id { get; set; }
[JsonProperty("ActualState")]
public string ActualState { get; set; }
[JsonProperty("EffectiveQuantity")]
public int EffectiveQuantity { get; set; }
[JsonProperty("UserID")]
public int UserID { get; set; }
[JsonProperty("Id_Wor")]
public int Id_Wor { get; set; }
}
public partial class TraceabilityWorkShift
{
public static List<TraceabilityWorkShift> FromJson(string json) => JsonConvert.DeserializeObject<List<TraceabilityWorkShift>>(json, MasterDetail.Converter.Settings);
}
public static class Serializea
{
public static string ToJson(this List<TraceabilityWorkShift> self) => JsonConvert.SerializeObject(self, MasterDetail.Converter.Settings);
}
internal static class Convertera
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
internal class ParseStringConvertera : JsonConverter
{
public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);
public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) return null;
var value = serializer.Deserialize<string>(reader);
long l;
if (Int64.TryParse(value, out l))
{
return l;
}
throw new Exception("Cannot unmarshal type long");
}
public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
{
if (untypedValue == null)
{
serializer.Serialize(writer, null);
return;
}
var value = (long)untypedValue;
serializer.Serialize(writer, value.ToString());
return;
}
public static readonly ParseStringConverter Singleton = new ParseStringConverter();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Wee.Common.Contracts;
using Wee.Common;
[assembly: DefaultNamespace("Wee.Core.Theme")]
namespace Wee.Core.Theme
{
public class PackageDefinition : IWeeTheme
{
private readonly IServiceCollection _services;
public PackageDefinition(IServiceCollection services)
{
_services = services;
}
public string Description { get { return "Core theme description"; } }
public string Name { get { return "Core Theme"; } }
public int? Order
{
get
{
return 0;
}
}
public void RegisterServices()
{
}
}
}
|
using ArquiteturaLimpaMVC.Aplicacao.Produtos.Commands;
using ArquiteturaLimpaMVC.Dominio.Entidades;
using ArquiteturaLimpaMVC.Dominio.Interfaces;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ArquiteturaLimpaMVC.Aplicacao.Produtos.Handlers
{
public class AtualizarProdutoCommandHandler : IRequestHandler<AtualizarProdutoCommand, Produto>
{
private readonly IProdutoRepository _produtoRepository;
public AtualizarProdutoCommandHandler(IProdutoRepository produtoRepository)
{
_produtoRepository = produtoRepository;
}
public async Task<Produto> Handle(AtualizarProdutoCommand request, CancellationToken cancellationToken)
{
var produto = await _produtoRepository.ProdutoPorIdAsync(request.Id);
if (produto is null)
throw new ApplicationException("A entidade não foi encontrada!");
produto.Atualizar(request.Nome,
request.Descricao,
request.Preco,
request.Estoque,
request.Imagem,
request.CategoriaId);
return await _produtoRepository.AtualizarAsync(produto);
}
}
} |
using PL.Integritas.Application.Interfaces;
using PL.Integritas.Application.ViewModels;
using PL.Integritas.Domain.Entities;
using PL.Integritas.Domain.Interfaces.Services;
using PL.Integritas.Infra.Data.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
namespace PL.Integritas.Application
{
public class PurchaseAppService : AppService, IPurchaseAppService
{
private readonly IPurchaseService _purchaseService;
private readonly IShoppingCartService _shoppingCartService;
public PurchaseAppService(IPurchaseService purchaseService,
IShoppingCartService shoppingCartService,
IUnityOfWork uow)
: base(uow)
{
_purchaseService = purchaseService;
_shoppingCartService = shoppingCartService;
}
public PurchaseViewModel Add(PurchaseViewModel purchaseViewModel)
{
ShoppingCart shoppingCart = _shoppingCartService.Search(x => x.Number == purchaseViewModel.CartNumber).FirstOrDefault();
if (shoppingCart == null)
{
throw new Exception("Shopping Cart doesn't exists.");
}
var purchase = new Purchase
{
Id = purchaseViewModel.Id,
Active = purchaseViewModel.Active,
CardHolderName = purchaseViewModel.CardHolderName,
CardNumber = purchaseViewModel.CardNumber,
CardExpiryMonth = purchaseViewModel.CardExpiryMonth,
CardExpiryYear = purchaseViewModel.CardExpiryYear,
CVV = purchaseViewModel.CVV,
Adress = purchaseViewModel.Adress,
Country = purchaseViewModel.Country,
State = purchaseViewModel.State,
City = purchaseViewModel.City,
ZipPostalCode = purchaseViewModel.ZipPostalCode,
ShoppingCartId = shoppingCart.Id
};
BeginTransaction();
_purchaseService.Add(purchase);
Commit();
return purchaseViewModel;
}
public PurchaseViewModel Update(PurchaseViewModel purchaseViewModel)
{
var purchase = new Purchase
{
Id = purchaseViewModel.Id,
Active = purchaseViewModel.Active,
CardHolderName = purchaseViewModel.CardHolderName,
CardNumber = purchaseViewModel.CardNumber,
CardExpiryMonth = purchaseViewModel.CardExpiryMonth,
CardExpiryYear = purchaseViewModel.CardExpiryYear,
CVV = purchaseViewModel.CVV,
Adress = purchaseViewModel.Adress,
Country = purchaseViewModel.Country,
State = purchaseViewModel.State,
City = purchaseViewModel.City,
ZipPostalCode = purchaseViewModel.ZipPostalCode,
ShoppingCartId = purchaseViewModel.Id
};
BeginTransaction();
_purchaseService.Update(purchase);
Commit();
return purchaseViewModel;
}
public void Remove(Int64 id)
{
BeginTransaction();
var purchase = _purchaseService.GetById(id);
purchase.Active = false;
_purchaseService.Update(purchase);
Commit();
}
public PurchaseViewModel GetById(Int64 id)
{
return new PurchaseViewModel(_purchaseService.GetById(id));
}
public IEnumerable<PurchaseViewModel> GetAll()
{
IEnumerable<Purchase> purchases = _purchaseService.Search(x => x.Active == true);
List<PurchaseViewModel> purchaseViewModels = new List<PurchaseViewModel>();
if (purchases != null)
{
foreach (var purchase in purchases)
{
purchaseViewModels.Add(new PurchaseViewModel(purchase));
}
}
foreach (var purchaseViewModel in purchaseViewModels.ToList())
{
purchaseViewModel.CartNumber = _shoppingCartService.GetById(purchaseViewModel.ShoppingCartId).Number;
}
return purchaseViewModels;
}
public IEnumerable<PurchaseViewModel> GetRange(int skip, int take)
{
IEnumerable<Purchase> purchases = _purchaseService.GetRange(skip, take);
List<PurchaseViewModel> purchaseViewModels = new List<PurchaseViewModel>();
if (purchases != null)
{
foreach (var purchase in purchases)
{
purchaseViewModels.Add(new PurchaseViewModel(purchase));
}
}
foreach (var purchaseViewModel in purchaseViewModels.ToList())
{
purchaseViewModel.CartNumber = _shoppingCartService.GetById(purchaseViewModel.ShoppingCartId).Number;
}
return purchaseViewModels;
}
public void Dispose()
{
_purchaseService.Dispose();
GC.SuppressFinalize(this);
}
}
}
|
namespace SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Responses
{
public class AddDraftApprenticeshipResponse
{
public long DraftApprenticeshipId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FSWatcher.Models;
namespace FSWatcher.Services {
public interface ILoggerService {
bool LogFileEvent(FileEvent f);
bool LogFileEvents(List<FileEvent> data);
List<FileEvent> GetFileEvents();
List<FileEvent> GetFileEvents(List<string> extensions);
List<FileEvent> GetFileEvents(DateTime start, DateTime end, List<string> extensions);
void DeleteFileEvent(FileEvent f);
bool EraseData();
}
}
|
using FluentAssertions;
using NUnit.Framework;
#pragma warning disable 649
namespace Hatchet.Tests.HatchetConvertTests.DeserializeTests
{
[TestFixture]
public class ObjectWithSingleFieldTests
{
private class TestClass
{
public string StringField;
}
[Test]
public void Deserialize_WithAnObjectWithOneStringPropertySingleWord_ThePropertyShouldBePopulated()
{
// Arrange
var input = "{ stringField Hello }";
// Act
var result = HatchetConvert.Deserialize<TestClass>(input);
// Assert
result.Should().NotBeNull();
result.StringField.Should().Be("Hello");
}
[Test]
public void Deserialize_WithAnObjectWithOneStringPropertyLongString_ThePropertyShouldBePopulated()
{
// Arrange
var input = "{ stringField \"Hello World.\" }";
// Act
var result = HatchetConvert.Deserialize<TestClass>(input);
// Assert
result.Should().NotBeNull();
result.StringField.Should().Be("Hello World.");
}
[Test]
public void Deserialize_WithAnObjectWithOneStringPropertyEmptyString_ThePropertyShouldBePopulated()
{
// Arrange
var input = "{ stringField \"\" }";
// Act
var result = HatchetConvert.Deserialize<TestClass>(input);
// Assert
result.Should().NotBeNull();
result.StringField.Should().Be(string.Empty);
}
[Test]
public void Deserialize_WithAnObjectWithOneStringPropertyContainingParenthesesString_ThePropertyShouldBePopulated()
{
// Arrange
var input = "{ stringField \"{ Nasty String { Very Nasty String } }\" }";
// Act
var result = HatchetConvert.Deserialize<TestClass>(input);
// Assert
result.Should().NotBeNull();
result.StringField.Should().Be("{ Nasty String { Very Nasty String } }");
}
}
} |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Input;
namespace CODE.Framework.Wpf.Utilities
{
/// <summary>
/// Helper class used for handling global keyboard hooks
/// </summary>
/// <seealso cref="System.IDisposable" />
public class GlobalKeyboardHookHelper : IDisposable
{
/// <summary>
/// Initializes static members of the <see cref="GlobalKeyboardHookHelper"/> class.
/// </summary>
public GlobalKeyboardHookHelper()
{
_hookId = InterceptKeys.SetHook(HookCallback);
}
private readonly IntPtr _hookId;
[MethodImpl(MethodImplOptions.NoInlining)]
private IntPtr HookCallback(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0) return InterceptKeys.CallNextHookEx(_hookId, code, wParam, lParam);
const int WM_KEYDOWN = 0x0100;
if (wParam != (IntPtr) WM_KEYDOWN) return InterceptKeys.CallNextHookEx(_hookId, code, wParam, lParam);
var vkCode = Marshal.ReadInt32(lParam);
var keyDownEvent = KeyDown;
if (keyDownEvent != null)
keyDownEvent(null, new RawKeyEventArgs(vkCode, false));
return InterceptKeys.CallNextHookEx(_hookId, code, wParam, lParam);
}
/// <summary>
/// Occurs when a key is pressed.
/// </summary>
public event RawKeyEventHandler KeyDown;
/// <summary>
/// Finalizes an instance of the <see cref="GlobalKeyboardHookHelper"/> class.
/// </summary>
~GlobalKeyboardHookHelper()
{
Dispose();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
InterceptKeys.UnhookWindowsHookEx(_hookId);
}
}
/// <summary>
/// This class provides functionality related to keyboard features
/// </summary>
public static class KeyboardHelper
{
[DllImport("user32.dll")]
private static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)] StringBuilder pwszBuff, int cchBuff, uint wFlags);
[DllImport("user32.dll")]
private static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
private static extern uint MapVirtualKey(uint uCode, MapType uMapType);
private enum MapType : uint
{
MAPVK_VK_TO_VSC = 0x0,
MAPVK_VSC_TO_VK = 0x1,
MAPVK_VK_TO_CHAR = 0x2,
MAPVK_VSC_TO_VK_EX = 0x3,
}
/// <summary>
/// Returns a char value from a Key structure
/// </summary>
/// <param name="key">The key.</param>
/// <returns>System.Char.</returns>
public static char GetCharFromKey(Key key)
{
var ch = ' ';
var virtualKey = KeyInterop.VirtualKeyFromKey(key);
var keyboardState = new byte[256];
GetKeyboardState(keyboardState);
var scanCode = MapVirtualKey((uint)virtualKey, MapType.MAPVK_VK_TO_VSC);
var stringBuilder = new StringBuilder(2);
var result = ToUnicode((uint)virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0);
switch (result)
{
case -1:
break;
case 0:
break;
case 1:
{
ch = stringBuilder[0];
break;
}
default:
{
ch = stringBuilder[0];
break;
}
}
return ch;
}
}
internal static class InterceptKeys
{
private static LowLevelKeyboardProc _proc;
public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
public static IntPtr SetHook(LowLevelKeyboardProc proc)
{
_proc = proc;
using (var curProcess = Process.GetCurrentProcess())
using (var curModule = curProcess.MainModule)
return SetWindowsHookEx(13, _proc, GetModuleHandle(curModule.ModuleName), 0);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
}
/// <summary>
/// Raw Keyboard Event Args
/// </summary>
/// <seealso cref="System.EventArgs" />
public class RawKeyEventArgs : EventArgs
{
/// <summary>
/// Raw Key Code
/// </summary>
/// <value>The vk code.</value>
public int VKCode { get; }
/// <summary>
/// Key.
/// </summary>
/// <value>The key.</value>
public Key Key { get; }
/// <summary>
/// Gets a value indicating whether this instance is system key.
/// </summary>
/// <value><c>true</c> if this instance is system key; otherwise, <c>false</c>.</value>
public bool IsSystemKey { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RawKeyEventArgs"/> class.
/// </summary>
/// <param name="vkCode">The vk code.</param>
/// <param name="isSystemKey">if set to <c>true</c> [is system key].</param>
public RawKeyEventArgs(int vkCode, bool isSystemKey)
{
VKCode = vkCode;
IsSystemKey = isSystemKey;
Key = KeyInterop.KeyFromVirtualKey(vkCode);
}
}
/// <summary>
/// Event handler signature for global key hook event
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="RawKeyEventArgs"/> instance containing the event data.</param>
public delegate void RawKeyEventHandler(object sender, RawKeyEventArgs args);
}
|
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 learn_180317
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请输入内容");
}
else
{
listView1.Items.Add(textBox1.Text.Trim());
textBox1.Text = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 0)
{
MessageBox.Show("请选择要移除的项");
}
else
{
for (int i= listView1.SelectedItems.Count; i >0 ; i--)
{
listView1.Items.Remove(listView1.SelectedItems[i-1]);
}
}
}
}
}
|
using System;
using Microsoft.Practices.Unity;
namespace FtpProxy.Core.Dependency
{
public static class DependencyResolver
{
private static readonly Lazy<UnityContainer> ContainerLazy =
new Lazy<UnityContainer>(GetUnityContainer);
public static UnityContainer Container
{
get { return ContainerLazy.Value; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification =
"Resolver живет до конца жизни приложения, поэтому освобождать его не нужно, он освободится автоматически с помощью GC"
)]
private static UnityContainer GetUnityContainer()
{
UnityContainer container = new UnityContainer();
return DependencyRegistrator.Register(container);
}
}
} |
using UnityEngine;
using System.Collections;
public class TweakableParams : MonoBehaviour {
// Boost params.
public const float fastPawsPauseMultiplier = 0.001f;
public const float fastPawsSwipeSpeedMultiplier = 3f;
public const float goodEyesAngleMultiplier = 1.6666f;
public const float normalPawRadius = 0.4f;
public const float bigPawsMultiplier = 2.0f;
public const float fartSlothMultiplier = 0.3f;
public const int miceKilledPerPoison = 1;
// Player swipe params.
public const float oldSwipeInitialPause = 0.5f;
public const float oldSwipeExtendSpeed = 14.0f;
public const float oldSwipeExtendedPause = 0.4f;
public const float newSwipeInitialPause = 0.001f;
public const float newSwipeExtendSpeed = 5.5f;
public const float newSwipeExtendedPause = 0.4f;
public const float swipeRetractSpeed = 20f;
public const float swipeRadius = 4.6f;
// Player view params.
public const float baseSwipeAngleRange = 90.0f;
// Player Turn params
public const float turnVelocityDegrees = 180f;
// Mouse track params.
public const int numTracks = 3;
// Mouse hole params.
public const int initialTrapsPerHole = 1;
// Initial money and boosts.
public const int initialMoney = 1;
public const int initialBoosts = 0;
public const int debugInitialMoney = 100;
public const int debugInitialBoosts = 5;
public const int debugInitialTrapsPerHole = 6;
public const float fastPawsBoostTime = 15.0f;
public const float goodEyesBoostTime = 15.0f;
public const float bigPawsBoostTime = 15.0f;
public const float fartBoostTime = 7.0f;
public const float poisonPawsBoostTime = 7.0f;
// Camera effects
public const float cameraZoomInPause = 0.3f;
public const float cameraZoomInTime = 0.7f;
public const float totalCameraZoomInTime = (cameraZoomInPause + cameraZoomInTime);
public const float cameraZoomOutPause = 0.5f;
public const float cameraZoomOutTime = 1.4f;
public const float totalCameraZoomOutTime = (cameraZoomOutPause + cameraZoomOutTime);
// Timing issues
public const float playOverPendingPause = totalCameraZoomOutTime + 0.3f;
public const float playStartMousePause = totalCameraZoomInTime + 0.3f;
public const float flyingAnimationTime = 1.0f;
public const float deadMouseAnimationTime = 0.3f;
public const float realAngusSelectionFadeTime = 0.6f;
public const float realAngusSelectionMoveTime = realAngusSelectionFadeTime - 0.2f;
public const float realAngusCardMoveTime = realAngusSelectionFadeTime - 0.1f;
// Real Angus sizing/layout stuff;
public const float realAngusImageAspectRatio = 1.33333f;
public const float realAngusElementButtonFrameWidth = 5;
public const float realAngusElementButtonWidth = 300f;
public static int GetInitialMoney() {
if (DebugConfig.instance.useDebugValues) {
return debugInitialMoney;
} else {
return initialMoney;
}
}
public static int GetInitialBoosts ()
{
if (DebugConfig.instance.useDebugValues) {
return debugInitialBoosts;
} else {
return initialBoosts;
}
}
public static int GetInitialTrapsPerHole ()
{
if (DebugConfig.instance.useDebugValues) {
return debugInitialTrapsPerHole;
} else {
return initialTrapsPerHole;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.