text stringlengths 13 6.01M |
|---|
namespace HáziKöltségNyilvántartó.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Categories",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Item_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Items", t => t.Item_Id)
.Index(t => t.Item_Id);
CreateTable(
"dbo.Items",
c => new
{
Id = c.Int(nullable: false, identity: true),
csvId = c.Int(),
Name = c.String(),
CategoryId = c.Int(nullable: false),
LastValue = c.Int(nullable: false),
IsIncome = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Transactions",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.Int(nullable: false),
ItemId = c.Int(nullable: false),
Value = c.Int(nullable: false),
CreatedTime = c.DateTime(nullable: false),
IsIncome = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Items", t => t.ItemId, cascadeDelete: true)
.ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.ItemId);
CreateTable(
"dbo.Users",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserName = c.String(),
Password = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropForeignKey("dbo.Transactions", "UserId", "dbo.Users");
DropForeignKey("dbo.Transactions", "ItemId", "dbo.Items");
DropForeignKey("dbo.Categories", "Item_Id", "dbo.Items");
DropIndex("dbo.Transactions", new[] { "ItemId" });
DropIndex("dbo.Transactions", new[] { "UserId" });
DropIndex("dbo.Categories", new[] { "Item_Id" });
DropTable("dbo.Users");
DropTable("dbo.Transactions");
DropTable("dbo.Items");
DropTable("dbo.Categories");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using POG.Forum;
namespace WerewolfTest
{
[TestFixture]
public class HTTPTest
{
ConnectionSettings _settings;
[TestFixtureSetUp]
public void Setup()
{
_settings = new ConnectionSettings("http://forumserver.twoplustwo.com");
}
[TestFixtureTearDown]
public void Teardown()
{
}
[Test]
public void TestUnicode()
{
ConnectionSettings settings = _settings.Clone();
settings.Url = "http://forumserver.twoplustwo.com/showpost.php?p=43345708&postcount=854";
string rc = HtmlHelper.GetUrlResponseString(settings);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Diagnostics;
using MyResources;
using TeaseAI_CE.Scripting.Events;
namespace TeaseAI_CE.Scripting
{
/// <summary>
/// Controllers are the part that figures out what the personality is going to say next.
/// </summary>
public class Controller : IKeyed
{
public string Id { get; private set; }
public Contacts Personalities;
public readonly VM VM;
/// <summary>
/// Time in between ticks.
/// </summary>
public int Interval;
private Stopwatch timmer = new Stopwatch(); // ToDo : Stopwatch is not optimal.
public Action<Personality, string> OnOutput;
private Stack<Context> stack = new Stack<Context>();
private List<Context> queue = new List<Context>();
public bool AutoFill = false;
private Variable startQuery = new Variable();
private Variable emptyQuery = new Variable();
// ToDo : A shorter list of enabled(or disabled) scripts, based off of the personalities list.
private Queue<IEvent> events = new Queue<IEvent>();
private StringBuilder output = new StringBuilder();
internal Controller(VM vm, string id)
{
VM = vm;
Id = VM.KeyClean(id);
Personalities = new Contacts(VM);
}
public bool Contains(Personality p)
{
return Personalities.Contains(p);
}
internal void stop()
{
timmer.Stop();
}
internal void tick_internal()
{
if (!timmer.IsRunning)
timmer.Start();
if (timmer.ElapsedMilliseconds > Interval)
{
timmer.Stop();
timmer.Reset();
timmer.Start();
Tick();
}
}
public void Tick()
{
// Wait for all events to finish.
while (events.Count > 0)
{
if (!events.Peek().Finished())
return;
events.Dequeue();
}
Personality personality;
while (next(out personality, output) && output.Length == 0)
{ }
if (output.Length == 0)
return;
events.Enqueue(new Timed(new TimeSpan(0, 0, 0, 0, output.Length * 80), false, () =>
{
OnOutput?.Invoke(personality, output.ToString());
output.Clear();
}));
}
/// <summary>
/// Executes the next line on the stack.
/// </summary>
/// <param name="output"></param>
/// <returns>false if there was nothing to do.</returns>
internal bool next(out Personality personality, StringBuilder output)
{
personality = Personalities.GetActive();
if (personality == null)
return false;
if (AutoFill && stack.Count == 0 && queue.Count == 0 && emptyQuery.IsSet)
{
AddFromEmptyQuery(new Logger("Controller." + Id));
}
// populate stack with items in the queue.
if (queue.Count > 0)
{
lock (queue)
{
foreach (Context item in queue)
stack.Push(item);
queue.Clear();
}
}
if (stack.Count == 0)
return false;
// try to execute top item.
var scope = stack.Peek();
if (scope.Line >= scope.Block.Lines.Length)
{
stack.Pop();
return next(out personality, output);
}
else
{
scope.Root.Log.SetId(scope.Block.Lines[scope.Line].LineNumber);
// exec current line
Line line = scope.Block.Lines[scope.Line];
VM.ExecLine(scope, line.Data, output);
if (scope.ExitLine)
scope.Repeat = false;
// always continue when validating.
if (scope.Root.Valid == BlockBase.Validation.Running)
{
scope.Exit = false;
scope.Return = false;
}
// advance to next line, if repeat is false.
if (scope.Repeat == false)
++scope.Line;
else
scope.Repeat = false;
if (scope.Exit)
stack.Clear();
else if (scope.Return)
stack.Pop();
// push sub block if exists
else if (line.Lines != null && scope.ExitLine == false)
{
stack.Push(new Context(this, scope.Root, line, 0, new Dictionary<string, Variable>(scope.Variables)));
if (stack.Count > 128)
{
scope.Root.Log.ErrorF(StringsScripting.Formatted_Stack_too_big, 128);
stack.Clear();
}
}
// pop off stack, if no lines left.
else if (scope.Line >= scope.Block.Lines.Length)
stack.Pop();
scope.ExitLine = false;
return true;
}
}
/// <summary>
/// Enqueue a root block to be added to the stack.
/// </summary>
public void Add(BlockBase root)
{
if (root == null)
{
Logger.Log(null, Logger.Level.Error, StringsScripting.Script_null_add_stack);
return;
}
lock (queue)
{
queue.Add(new Context(this, root, root, 0, new Dictionary<string, Variable>()));
if (queue.Count > 128)
{
root.Log.ErrorF(StringsScripting.Formatted_Queue_too_big, 128);
queue.Clear();
}
}
}
public bool AddFromStartQuery(Logger log)
{
if (startQuery == null || !startQuery.IsSet)
return false;
Add(VM.QueryScript(startQuery, log));
return true;
}
public bool AddFromEmptyQuery(Logger log)
{
if (emptyQuery == null || !emptyQuery.IsSet)
return false;
Add(VM.QueryScript(emptyQuery, log));
return true;
}
public void Add(IEvent e)
{
// ToDo : Not thread safe
events.Enqueue(e);
}
public void Input(Personality p, string text)
{
var shorthand = VM.InputToShorthand(text);
// ToDo 8: If Debugging
//OnOutput?.Invoke(p, shorthand);
// else
OnOutput?.Invoke(p, text);
var script = VM.GetScriptResponse(shorthand);
if (script != null)
Add(script);
}
public void WriteValues(string prefix, StringBuilder sb)
{
writeValue(prefix, sb, "startQuery", startQuery);
writeValue(prefix, sb, "emptyQuery", emptyQuery);
}
private void writeValue(string prefix, StringBuilder sb, string key, Variable v)
{
if (v == null || !v.CanWriteValue())
return;
sb.Append(prefix);
sb.Append("#(.");
sb.Append(key);
sb.Append("=");
v.WriteValue(sb);
sb.AppendLine(")");
}
#region IKeyed
public Variable Get(Key key, Logger log = null)
{
if (key.AtEnd)
{
// ToDo : Error
return null;
}
if (key.NextIf("startquery"))
return startQuery.Get(key, log);
if (key.NextIf("emptyquery"))
return emptyQuery.Get(key, log);
var p = Personalities.GetActive();
if (key.NextIf("contact"))
{
int i;
if (!int.TryParse(key.Next(), out i))
// ToDo : Error
return null;
p = Personalities.Get(i, log);
}
if (p == null)
return null;
return p.Get(key, log);
}
#endregion
}
}
|
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var welcome = "Hello World!";
Console.WriteLine(welcome);
}
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("VarsInternal")]
public class VarsInternal : MonoClass
{
public VarsInternal(IntPtr address) : this(address, "VarsInternal")
{
}
public VarsInternal(IntPtr address, string className) : base(address, className)
{
}
public bool Contains(string key)
{
object[] objArray1 = new object[] { key };
return base.method_11<bool>("Contains", objArray1);
}
public static VarsInternal Get()
{
return MonoClass.smethod_15<VarsInternal>(TritonHs.MainAssemblyPath, "", "VarsInternal", "Get", Array.Empty<object>());
}
public bool LoadConfig(string path)
{
object[] objArray1 = new object[] { path };
return base.method_11<bool>("LoadConfig", objArray1);
}
public static void RefreshVars()
{
MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "VarsInternal", "RefreshVars");
}
public void Set(string key, string value)
{
object[] objArray1 = new object[] { key, value };
base.method_8("Set", objArray1);
}
public string Value(string key)
{
object[] objArray1 = new object[] { key };
return base.method_13("Value", objArray1);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TimerManager : MonoBehaviour
{
[SerializeField]
private Text sureText;
int kalanSure;
bool sureSaysinmi = true;
GameManager gameManager;
private void Awake()
{
gameManager = Object.FindObjectOfType<GameManager>();
}
void Start()
{
kalanSure = 90;
sureSaysinmi = true;
}
public void SureyiBaslat()
{
StartCoroutine(SureTimerRoutine());
}
IEnumerator SureTimerRoutine()
{
while (sureSaysinmi)
{
yield return new WaitForSeconds(1f);
if (kalanSure < 10)
{
sureText.text = "0" + kalanSure.ToString();
}
else
{
sureText.text = kalanSure.ToString();
}
if(kalanSure<=0)
{
sureSaysinmi = false;
sureText.text = "";
gameManager.OyunuBitir();
}
kalanSure--;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Data.SqlClient;
namespace RSMS
{
public partial class DriverInforFilter : MySubDialogBase
{
public FrmDriverInfor parentFrm;
public Dictionary<int, object> lastValues;
private void historyDataRestore()
{
if (lastValues != null)
{
foreach (KeyValuePair<int, object> v in lastValues)
{
if (Controls[v.Key] is TextBox)
{
Controls[v.Key].Text = v.Value.ToString();
}
else if (Controls[v.Key] is ComboBox)
{
((ComboBox)Controls[v.Key]).SelectedIndex = (int)v.Value;
}
else if (Controls[v.Key] is DateTimePicker)
{
((DateTimePicker)Controls[v.Key]).Value = (DateTime)v.Value;
}
}
}
}
public DriverInforFilter()
{
InitializeComponent();
st.Value = DateTime.Now;
et.Value = DateTime.Now;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
et.Checked = st.Checked;
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
st.Checked = et.Checked;
}
private void button4_Click(object sender, EventArgs e)
{
//所有条件合成传递
ArrayList al = new ArrayList();
lastValues = new Dictionary<int, object>();
int i = 1;
string sqlWhere = "";
string whereSplit = "";
//身份证号
if (TB1.Text != "" && TB2.Text != "")
{
al.Add(new SqlParameter("@v" + i.ToString(), TB1.Text));
sqlWhere +=whereSplit+ " [cPersonID] between @v" + i.ToString();
lastValues.Add(Controls.IndexOf(TB1), TB1.Text);
i++;
al.Add(new SqlParameter("@v" + i.ToString(), TB2.Text));
sqlWhere += " and @v" + i.ToString();
lastValues.Add(Controls.IndexOf(TB2), TB1.Text);
whereSplit = " and ";
i++;
}
//有效期
if (TB3.Text != "")
{
object svrDateTime= myHelper.getFirst("select getdate()");
DateTime dt = svrDateTime == null ? DateTime.Now : (DateTime)svrDateTime;
switch (TB3.Text)
{
case "未过期":
sqlWhere += whereSplit + " [dBeginDate]<=@v" + i.ToString();
al.Add(new SqlParameter("@v" + i.ToString(), dt.ToString("yyyy-MM-dd")));
i++;
al.Add(new SqlParameter("@v" + i.ToString(), dt.ToString("yyyy-MM-dd")));
sqlWhere += " and [dEndDate]>=@v" + i.ToString();
whereSplit = " and ";
i++;
break;
case "已过期":
sqlWhere += whereSplit + " ([dBeginDate]>=@v" + i.ToString();
al.Add(new SqlParameter("@v" + i.ToString(), dt.ToString("yyyy-MM-dd")));
i++;
al.Add(new SqlParameter("@v" + i.ToString(), dt.ToString("yyyy-MM-dd")));
sqlWhere += " or [dEndDate]<=@v ) " + i.ToString();
whereSplit = " and ";
i++;
break;
}
lastValues.Add(Controls.IndexOf(TB3), TB3.SelectedIndex);
}
//司机
if (TB4.Text != "")
{
switch (TB4.Text)
{
case "男":
sqlWhere += whereSplit + " [bSex]=@v" + i.ToString();
al.Add(new SqlParameter("@v" + i.ToString(), true));
i++;
whereSplit = " and ";
break;
case "女":
sqlWhere += whereSplit + " [bSex]=@v" + i.ToString();
al.Add(new SqlParameter("@v" + i.ToString(), false));
i++;
whereSplit = " and ";
break;
}
lastValues.Add(Controls.IndexOf(TB4), TB4.SelectedIndex);
}
//民族
if (TB5.Text != "")
{
//cBillNo
sqlWhere += whereSplit + " [cPersonNation]=@v" + i.ToString();
al.Add(new SqlParameter("@v" + i.ToString(), TB5.Text));
lastValues.Add(Controls.IndexOf(TB5), TB5.Text);
i++;
whereSplit = " and ";
}
//住址
if (TB6.Text != "")
{
sqlWhere += whereSplit + " [cHomeAdd] like @v" + i.ToString();
al.Add(new SqlParameter("@v" + i.ToString(), "%"+TB6.Text+"%"));
lastValues.Add(Controls.IndexOf(TB6), TB6.Text);
i++;
whereSplit = " and ";
}
//电话
if (TB8.Text != "")
{
sqlWhere += whereSplit + " cTelephone=@v" + i.ToString();
al.Add(new SqlParameter("@v" + i.ToString(), TB8.Text));
lastValues.Add(Controls.IndexOf(TB8), TB8.Text);
i++;
whereSplit = " and ";
}
//指纹状态
if (TB7.Text != "")
{
switch (TB7.Text)
{
case "未采集":
sqlWhere += whereSplit + " [cPersonID] not in ( select [cPersonID] from [FGTemplateLib]) " ;
whereSplit = " and ";
break;
case "已采集":
sqlWhere += whereSplit + " [cPersonID] in ( select [cPersonID] from [FGTemplateLib]) " ;
whereSplit = " and ";
break;
}
lastValues.Add(Controls.IndexOf(TB7), TB7.SelectedIndex);
}
//出生日期
if (st.Checked&&et.Checked)
{
al.Add(new SqlParameter("@v" + i.ToString(), st.Value.ToString("yyyy-MM-dd")));
sqlWhere += whereSplit+ " [dBirthDay] between @v" + i.ToString();
lastValues.Add(Controls.IndexOf(st), st.Value);
i++;
al.Add(new SqlParameter("@v" + i.ToString(), et.Value.ToString("yyyy-MM-dd 23:59:59")));
sqlWhere += " and @v" + i.ToString();
lastValues.Add(Controls.IndexOf(et), et.Value);
whereSplit = " and ";
i++;
}
parentFrm.lastValues = lastValues;
parentFrm.queryDb(" where "+(sqlWhere==""?" 1=1 ":sqlWhere),al);
Close();
}
private void button5_Click(object sender, EventArgs e)
{
Close();
}
private void button3_Click(object sender, EventArgs e)
{
BillFilterConsiDlg bfcd = new BillFilterConsiDlg();
bfcd.callBackAction += bfcd_callBackAction;
bfcd.selectedIndex = 0;
bfcd.headerText1 = "身份证号";
bfcd.headerText2 = "姓名";
bfcd.retTextId = 1;
SqlParameter[] sqlPar = new SqlParameter[2];
sqlPar[0] = new SqlParameter("@v1", "%" + TB1.Text + "%");
sqlPar[1] = new SqlParameter("@v2", "%" + TB1.Text + "%");
bfcd.dt = myHelper.getDataTable("select [cPersonID],[cPersonName] from [DriverInfo] where cPersonID like @v1 or cPersonName like @v2", sqlPar);
bfcd.showDlg();
}
void bfcd_callBackAction(object sender, myHelper.OPEventArgs e)
{
if (e != null && e.param != null)
{
string ctrlName = "TB" + e.param[1];
foreach (Control cl in this.Controls)
{
if (cl.Name == ctrlName)
{
cl.Text = e.param[0];
e.param = null;
e = null;
break;
}
}
}
}
private void button12_Click(object sender, EventArgs e)
{
BillFilterConsiDlg bfcd = new BillFilterConsiDlg();
bfcd.callBackAction += bfcd_callBackAction;
bfcd.selectedIndex = 0;
bfcd.headerText1 = "身份证号";
bfcd.headerText2 = "姓名";
bfcd.retTextId = 2;
SqlParameter[] sqlPar = new SqlParameter[2];
sqlPar[0] = new SqlParameter("@v1", "%" + TB2.Text + "%");
sqlPar[1] = new SqlParameter("@v2", "%" + TB2.Text + "%");
bfcd.dt = myHelper.getDataTable("select [cPersonID],[cPersonName] from [DriverInfo] where cPersonID like @v1 or cPersonName like @v2", sqlPar);
bfcd.showDlg();
}
private void button1_Click(object sender, EventArgs e)
{
BillFilterConsiDlg bfcd = new BillFilterConsiDlg();
bfcd.callBackAction += bfcd_callBackAction;
bfcd.selectedIndex = 0;
bfcd.headerText1 = "民族";
//bfcd.headerText2 = "姓名";
bfcd.retTextId = 5;
SqlParameter[] sqlPar = new SqlParameter[1];
sqlPar[0] = new SqlParameter("@v1", "%" + TB5.Text + "%");
bfcd.dt = myHelper.getDataTable("select distinct [cPersonNation] from [DriverInfo] where cPersonNation like @v1 ", sqlPar);
bfcd.showDlg();
}
private void button2_Click(object sender, EventArgs e)
{
BillFilterConsiDlg bfcd = new BillFilterConsiDlg();
bfcd.callBackAction += bfcd_callBackAction;
bfcd.selectedIndex = 2;
bfcd.headerText1 = "身份证号";
bfcd.headerText2 = "姓名";
bfcd.headerText3 = "住址";
bfcd.retTextId = 6;
SqlParameter[] sqlPar = new SqlParameter[1];
sqlPar[0] = new SqlParameter("@v1", "%" + TB6.Text + "%");
bfcd.dt = myHelper.getDataTable("select [cPersonID],[cPersonName],[cHomeAdd] from [DriverInfo] where cHomeAdd like @v1 ", sqlPar);
bfcd.showDlg();
}
private void button6_Click(object sender, EventArgs e)
{
BillFilterConsiDlg bfcd = new BillFilterConsiDlg();
bfcd.callBackAction += bfcd_callBackAction;
bfcd.selectedIndex = 2;
bfcd.headerText1 = "身份证号";
bfcd.headerText2 = "姓名";
bfcd.headerText3 = "联系电话";
bfcd.retTextId = 8;
SqlParameter[] sqlPar = new SqlParameter[1];
sqlPar[0] = new SqlParameter("@v1", "%" + TB8.Text + "%");
bfcd.dt = myHelper.getDataTable("select [cPersonID],[cPersonName],[cTelephone] from [DriverInfo] where [cTelephone] like @v1 ", sqlPar);
bfcd.showDlg();
}
private void DriverInforFilter_Load(object sender, EventArgs e)
{
st.Value = DateTime.Now;
et.Value = DateTime.Now;
st.Checked = false;
et.Checked = false;
historyDataRestore();
}
}
}
|
namespace CallCenter.Common
{
public enum EventReason
{
Login = 0,
Logout = 1,
Pause = 2,
Ready = 3,
Busy = 4
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RDB_API.Models.Enums
{
public enum TelefoneTipo
{
Celular = 0,
Residencial = 1,
Comercial = 2
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.HttpRequestClientConsole.Interface;
using Sunny.Lib;
using Sunny.Lib.Xml;
using System.Web;
using Sunny.HttpRequestClientConsole.Helper;
namespace Sunny.HttpRequestClientConsole
{
/// <summary>
/// Get PMT 'Seller Name' of balance
/// </summary>
public class PMTSyncSellerNameHelper
{
static PMTSyncSellerNameHelperConfiguration _config = PMTSyncSellerNameHelperConfigurationSectionHandler.GetConfigurationObject(PMTSyncSellerNameHelperConfigurationSectionHandler.SectionGroupName
, PMTSyncSellerNameHelperConfigurationSectionHandler.SectionName);
// 1. Get currently month all balance: List<A>.
// 2. Get account name for balance from step 1.
// 3. Get register account for balances from step 1.
static IList<PMTAccountInfo> list = new List<PMTAccountInfo>() {
new PMTAccountInfo { PayoutAccountId="8682293e0b94495585a7d91dea152e8c01",BillableAccountId=157515098 }
,new PMTAccountInfo { PayoutAccountId="3036528fcaf14b94a1e49ea94368ab2d01",BillableAccountId=53810800 }
};
public static void Start()
{
//GetEncodeAccountId();
//GetNamesOfBalances(list);
//GetSpecialPeriodAllBalances("2013-01-01T00:00:00", "2014-12-31T23:59:59"); //"TotalCount":7
//GetSpecialPeriodAllBalances("2015-01-01T00:00:00", "2015-07-31T23:59:59"); //"TotalCount":245
GetCurrencyMonthAllBalances();
}
public static void GetCurrencyMonthAllBalances()
{
string firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-ddTHH:mm:ss");
var daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
string lastDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, daysInMonth).AddDays(1).AddTicks(-1).ToString("yyyy-MM-ddTHH:mm:ss");
GetSpecialPeriodAllBalances(firstDayOfMonth, lastDayOfMonth);
}
public static void GetSpecialPeriodAllBalances(string startDate = "", string endDate = "")
{
string xPath = string.Format(HttpRequestInfo.XPath_GetHttpRequestInfo_FilterByNameAndCategoryName
, _config.GetCurrentMonthAllBalances_ConfigureName
, _config.GetCurrentMonthAllBalances_CategoryName);
HttpRequestInfo requestConfiguration = XMLSerializerHelper.DeserializeByXPath<HttpRequestInfo>(xPath, Constant.WebRequestConfigFileFullPath);
if (!string.IsNullOrEmpty(startDate))
{
string patternStr = "ge datetime'(.*?)'";
string needBeReplacedStr = RegexHelper.GetMatches_First_JustWantedOne(patternStr, requestConfiguration.RequestUrl);
requestConfiguration.RequestUrl = requestConfiguration.RequestUrl.Replace(needBeReplacedStr, startDate);
}
if (!string.IsNullOrEmpty(endDate))
{
string patternStr = "le datetime'(.*?)'";
string needBeReplacedStr = RegexHelper.GetMatches_First_JustWantedOne(patternStr, requestConfiguration.RequestUrl);
requestConfiguration.RequestUrl = requestConfiguration.RequestUrl.Replace(needBeReplacedStr, endDate);
}
GetPayoutBalancesResponse response = CommonHelper.SendRequest<GetPayoutBalancesResponse>(requestConfiguration);
if (response != null && response.Balances.Count > 0)
{
IList<PMTAccountInfo> pmtAccounts = new List<PMTAccountInfo>();
response.Balances.ForEach(b =>
{
PMTAccountInfo account = new PMTAccountInfo() { BalanceId = b.BalanceId, PayoutAccountId = b.PayoutAccountId, BillableAccountId = b.BillableAccountId };
pmtAccounts.Add(account);
});
GetNamesOfBalances(pmtAccounts, string.Format("_{0}_{1}", Convert.ToDateTime(startDate).ToString("yyyy-MM-dd HH-mm-ss")
, Convert.ToDateTime(endDate).ToString("yyyy-MM-dd HH-mm-ss")));
}
}
private static void GetNamesOfBalances(IList<PMTAccountInfo> pmtAccounts, string partialFileName = "")
{
string fileName = _config.GetExportFileFullName();
if (!string.IsNullOrEmpty(partialFileName))
{
fileName = fileName.Replace(".csv", string.Format("{0}.csv", partialFileName));
}
if (pmtAccounts != null && pmtAccounts.Count > 0)
{
System.IO.File.WriteAllText(fileName, PMTAccountInfo.header + Environment.NewLine);
pmtAccounts.ToList().ForEach(b =>
{
try
{
string puid = GetPUIdByUAID(b.PayoutAccountId);
if (!string.IsNullOrEmpty(puid))
{
b.PUID = puid;
//Task t1 = Task.Run(() => { GetCompanyName(b); });
Task t2 = Task.Run(() => { GetModelAccountName(b); });
Task t3 = Task.Run(() => { GetMintAccountName(b); });
Task t4 = Task.Run(() => { GetMSAAccountName(b); });
Task.WaitAll(new Task[] { /*t1,*/ t2, t3, t4 });
}
}
catch (Exception ex)
{
}
finally
{
string rowStr = b.ToString();
System.IO.File.AppendAllText(fileName, rowStr + Environment.NewLine);
}
});
}
}
// Get PUID by Universal Account Id
private static string GetPUIdByUAID(string uaid)
{
string puid = string.Empty;
string xPath = string.Format(HttpRequestInfo.XPath_GetHttpRequestInfo_FilterByNameAndCategoryName
, _config.UAID2PUID_ConfigureName
, _config.UAID2PUID_CategoryName);
HttpRequestInfo requestConfiguration = XMLSerializerHelper.DeserializeByXPath<HttpRequestInfo>(xPath, Constant.WebRequestConfigFileFullPath);
requestConfiguration.RequestUrl = string.Format("https://accounts.cp.microsoft-int.com/accounts/{0}", uaid);
CommerceAccountResource response = CommonHelper.SendRequest<CommerceAccountResource>(requestConfiguration);
if (response != null && response.Identity != null && response.Identity.Identifier != null && response.Identity.Identifier.IdType == "PUID")
{
puid = response.Identity.Identifier.Id;
}
return puid;
}
private static void GetCompanyName(PMTAccountInfo account)
{
Int64 sellerId = GetSellerIdByPUID(account);
string xPath = string.Format(HttpRequestInfo.XPath_GetHttpRequestInfo_FilterByNameAndCategoryName
, _config.SellerID2AccountInfo_ConfigureName
, _config.SellerID2AccountInfo_CategoryName);
HttpRequestInfo requestConfiguration = XMLSerializerHelper.DeserializeByXPath<HttpRequestInfo>(xPath, Constant.WebRequestConfigFileFullPath);
requestConfiguration.RequestUrl = string.Format("https://accountmgmtservice.dce.mp.microsoft.com/accounts/{0}", sellerId);
var accountEntity = CommonHelper.SendRequest<AccountManagementServiceInterface.AccountEntity>(requestConfiguration);
if (accountEntity != null && accountEntity.Identity != null)
{
account.CompanyName = accountEntity.Identity.PublisherName;
}
}
private static void GetModelAccountName(PMTAccountInfo account)
{
string accountName = string.Empty;
string xPath = string.Format(HttpRequestInfo.XPath_GetHttpRequestInfo_FilterByNameAndCategoryName
, _config.UAID2AccountInfo_ConfigureName
, _config.UAID2AccountInfo_CategoryName);
HttpRequestInfo requestConfiguration = XMLSerializerHelper.DeserializeByXPath<HttpRequestInfo>(xPath, Constant.WebRequestConfigFileFullPath);
requestConfiguration.RequestUrl = string.Format("https://accounts.cp.microsoft-int.com/{0}/profiles?type=intellectual_property_services", account.PayoutAccountId);
JObject response = CommonHelper.SendRequest<JObject>(requestConfiguration);
if (response != null && Convert.ToInt32(response["item_count"]) > 0 && response["items"][0] != null)
{
string strProfile = response["items"][0].ToString();
JsonSerializer deserializer = JsonSerializer.Create(new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Newtonsoft.Json.Formatting.Indented,
MissingMemberHandling = MissingMemberHandling.Ignore,
});
var profile = deserializer.Deserialize<IntellectualPropertyServicesProfileResource>(new JsonTextReader(new StringReader(strProfile)));
if (profile != null)
{
accountName = string.Format("{0} {1}", profile.FirstName, profile.LastName);
}
}
account.ModelAccountName = accountName;
}
private static void GetMintAccountName(PMTAccountInfo account)
{
if (account.BillableAccountId == 0)
{
return;
}
string xPath = string.Format(HttpRequestInfo.XPath_GetHttpRequestInfo_FilterByNameAndCategoryName
, _config.GetMintAccountId_ConfigureName
, _config.GetMintAccountId_CategoryName);
HttpRequestInfo requestConfiguration = XMLSerializerHelper.DeserializeByXPath<HttpRequestInfo>(xPath, Constant.WebRequestConfigFileFullPath);
string encodeAccountId = BdkId.EncodeAccountID(account.BillableAccountId);
string pattern = "<a:AccountId>(.*?)</a:AccountId>";
string needBeReplacedStr = RegexHelper.GetMatches_First_JustWantedOne(pattern, requestConfiguration.RequestParameters);
requestConfiguration.RequestParameters = requestConfiguration.RequestParameters.Replace(needBeReplacedStr, encodeAccountId);
string responseStr = CommonHelper.SendRequest(requestConfiguration);
//var getAccountResponse = XMLSerializerHelper.DeserializeFromMemory<Microsoft.Commerce.Proxy.CTPCommerce.GetAccountResponse>(response);
string pattern1 = "<a:FirstName>(.*?)</a:FirstName>";
string pattern2 = "<a:LastName>(.*?)</a:LastName>";
string[] firstNames = RegexHelper.GetMatches_All_JustWantedOne(pattern1, responseStr);
string[] lastNames = RegexHelper.GetMatches_All_JustWantedOne(pattern2, responseStr);
string firstName = string.Empty;
string lastName = string.Empty;
if (firstNames.Count() == 1)
{
firstName = firstNames[0];
}
else if (firstNames.Count() == 2)
{
firstName = firstNames[1];
}
if (lastNames.Count() == 1)
{
lastName = lastNames[0];
}
else if (lastNames.Count() == 2)
{
lastName = lastNames[1];
}
if (!string.IsNullOrEmpty(firstName) || !string.IsNullOrEmpty(lastName))
{
account.MinAccounttName = string.Format("{0} {1}", firstName, lastName);
}
}
private static void GetMSAAccountName(PMTAccountInfo account)
{
string accountName = string.Empty;
string xPath = string.Format(HttpRequestInfo.XPath_GetHttpRequestInfo_FilterByNameAndCategoryName
, _config.GetAccountInfoByPUID_ConfigureName
, _config.GetAccountInfoByPUID_CategoryName);
HttpRequestInfo requestConfiguration = XMLSerializerHelper.DeserializeByXPath<HttpRequestInfo>(xPath, Constant.WebRequestConfigFileFullPath);
long lPuid;
long.TryParse(account.PUID, out lPuid);
string patternStr = "(<bstrNetIDs>.*</bstrNetIDs>)";
string needBeReplacedStr = RegexHelper.GetMatches_First_JustWantedOne(patternStr, requestConfiguration.RequestParameters);
requestConfiguration.RequestParameters = requestConfiguration.RequestParameters.Replace(needBeReplacedStr
, string.Format("<bstrNetIDs>{0}</bstrNetIDs>", Convert.ToString(lPuid, 16)));
HttpResponseInfo response = (new HttpWebRequestHelper(requestConfiguration)).HttpSendMessage();
if (response != null && response.Status.StartsWith("20"))
{
XmlDocument credentialXML = new XmlDocument();
const string signinNameNodeStr = @"/NETID2Name/SigninName";
int startIndex = response.ResponseString.IndexOf("<NETID2Name>");
int endIndex = response.ResponseString.IndexOf("</NETID2Name>");
string needPart = response.ResponseString.Substring(startIndex, endIndex - startIndex + "</NETID2Name>".Length);
string xmlNode = HttpUtility.HtmlDecode(needPart);
using (XmlReader xmlReader = XmlReader.Create(new StringReader(xmlNode)))
{
credentialXML.Load(xmlReader);
}
var signinNameNode = credentialXML.SelectSingleNode(signinNameNodeStr);
if (signinNameNode != null)
{
// Extract the MSA
accountName = signinNameNode.InnerText.Trim();
}
}
account.MSAAccountName = accountName;
}
private static Int64 GetSellerIdByPUID(PMTAccountInfo account)
{
Int64 sellerId = 0;
string xPath = string.Format(HttpRequestInfo.XPath_GetHttpRequestInfo_FilterByNameAndCategoryName
, _config.PUID2SellerID_ConfigureName
, _config.PUID2SellerID_CategoryName);
HttpRequestInfo requestConfiguration = XMLSerializerHelper.DeserializeByXPath<HttpRequestInfo>(xPath, Constant.WebRequestConfigFileFullPath);
requestConfiguration.RequestUrl = string.Format("https://accountmgmtservice.dce.mp.microsoft.com/api/accountmanagement/sellers/{0}/accounts", account.PUID);
sellerId = CommonHelper.SendRequest<Int64>(requestConfiguration);
return sellerId;
}
private static void GetEncodeAccountId()
{
while (true)
{
Console.WriteLine("Please input a 'BillableAccountId':");
string billableAccountId = Console.ReadLine();
if (string.IsNullOrEmpty(billableAccountId))
{
Console.WriteLine("'BillableAccountId' can't be null or empty!");
}
long billableAccountId1 = 0;
long.TryParse(billableAccountId, out billableAccountId1);
string encodeAccountId = BdkId.EncodeAccountID(billableAccountId1);
Console.WriteLine("After encrypt:" + encodeAccountId);
}
}
}
public class PMTSyncSellerNameHelperConfiguration
{
public string GetCurrentMonthAllBalances_ConfigureName { get; set; }
public string GetCurrentMonthAllBalances_CategoryName { get; set; }
public string UAID2PUID_ConfigureName { get; set; }
public string UAID2PUID_CategoryName { get; set; }
public string UAID2AccountInfo_ConfigureName { get; set; }
public string UAID2AccountInfo_CategoryName { get; set; }
public string GetAccountInfoByPUID_ConfigureName { get; set; }
public string GetAccountInfoByPUID_CategoryName { get; set; }
public string PUID2SellerID_ConfigureName { get; set; }
public string PUID2SellerID_CategoryName { get; set; }
public string SellerID2AccountInfo_ConfigureName { get; set; }
public string SellerID2AccountInfo_CategoryName { get; set; }
public string GetMintAccountId_ConfigureName { get; set; }
public string GetMintAccountId_CategoryName { get; set; }
public string ExportFileRelativePath { get; set; }
public string ExportFileName { get; set; }
public string GetExportFileFullName()
{
return Path.Combine(ExportFileRelativePath, ExportFileName);
}
}
public class PMTSyncSellerNameHelperConfigurationSectionHandler : CustomerConfigurationSectionHandler<PMTSyncSellerNameHelperConfiguration>
{
public const string SectionGroupName = "mySectionGroup";
public const string SectionName = "PMTSyncSellerNameHelper";
}
}
|
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace BookDownloader
{
class Program
{
static async Task Main(string[] args)
{
var bookId = "";
var userToken = ""; // SID from cookies
var resolution = "w1920"; // w1280
var outputPath = Directory.GetCurrentDirectory();
var cts = new CancellationTokenSource();
var downloader = new Downloader(userToken, outputPath, Console.WriteLine);
Console.WriteLine("Started");
Console.WriteLine("Downloading...");
try
{
await downloader.DownloadBookAsync(bookId, resolution, cts.Token);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("Done!");
Console.ReadLine();
}
}
}
|
using System;
using System.IO;
using System.Windows;
using TariffCreator.Config;
namespace TariffCreator.NewTariff.CreateInfFile
{
partial class CreateInf
{
/// <summary>
/// Create and Saves the Tariff as inf File
/// </summary>
/// <param name="path"></param>
void SaveInf(String path)
{
try
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
// [Carrier]
sw.WriteLine("[Carrier]");
sw.WriteLine("Name=" + txtName.Text);
sw.WriteLine("Ident=" + txtIdent.Text);
if (txtMeter.Text != "") sw.WriteLine("MeterRate=" + txtMeter.Text);
sw.WriteLine("DefaultChargeBand=" + ((ChargeBand)comboDefault.SelectedItem).CBShortName);
sw.WriteLine();
sw.Flush();
// [CallCategories]
sw.WriteLine("[CallCategories]");
for (int i = 0; i < CbListe.Count; i++)
sw.WriteLine(CbListe[i].CCShortName + "=" + CbListe[i].CCName);
sw.WriteLine();
sw.Flush();
// [ChargeBands]
sw.WriteLine("[ChargeBands]");
for (int i = 0; i < CbListe.Count; i++)
sw.WriteLine(CbListe[i].CBShortName + "=" + CbListe[i].CBName);
sw.WriteLine();
sw.Flush();
// [ChargeRates]
sw.WriteLine("[ChargeRates]");
for(int i = 0; i < CbListe.Count; i++)
{
sw.Write(CbListe[i].CBShortName);
sw.Write(",A=\"AllDay\",");
sw.Write((int)(CbListe[i].PriceCall * 100000) + ",");
sw.Write((CbListe[i].PricePer * 1000) + ",");
sw.Write((CbListe[i].PriceFor * 1000) + ",");
sw.Write((int)(CbListe[i].PriceMin * 100000) + ",");
sw.Write((int)(CbListe[i].MinimumPrice * 100000) + ",");
sw.WriteLine("None,0,0,0,0,0");
}
sw.WriteLine();
sw.Flush();
// [DailyRates]
sw.WriteLine("[DailyRates]");
for(int i=0;i<CbListe.Count;i++)
{
for (int day = 0; day <= 7; day++)
sw.WriteLine(CbListe[i].CBShortName + "," + day + "=0000:A");
}
sw.WriteLine();
sw.Flush();
// [Destinations]
sw.WriteLine("[Destinations]");
for(int i = 0; i < CbListe.Count; i++)
{
foreach(Country item in CbListe[i].Countrys)
{
if (!(string.IsNullOrWhiteSpace(item.Description) || string.IsNullOrWhiteSpace(item.Prefix)))
{
sw.Write(item.Prefix + "=\"");
sw.Write(item.Description + "\",");
sw.Write(CbListe[i].CCShortName + ",");
sw.WriteLine(CbListe[i].CBShortName);
}
}
}
sw.Dispose();
fs.Dispose();
}
catch (Exception e) { MessageBox.Show(e.Message); }
}
}
}
|
using System;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using XGhms.Helper;
using System.Collections.Generic;
namespace XGhms.DAL
{
/// <summary>
/// 数据访问类:user_message
/// </summary>
public partial class user_message
{
#region 基本方法=============================================
/// <summary>
/// 是否存在该记录
/// </summary>
/// /// <param name="id">ID</param>
/// <returns>true or false</returns>
public bool Exists(int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from xg_user_message");
strSql.Append(" where id=@id ");
SqlParameter[] parameters = {
new SqlParameter("@id", SqlDbType.Int,4)};
parameters[0].Value = id;
return SQLHelper.Exists(strSql.ToString(), parameters);
}
/// <summary>
/// 根据ID来删除相应的数据
/// </summary>
/// <param name="id">ID</param>
/// <returns>true or false</returns>
public bool Delete(int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from xg_user_message ");
strSql.Append(" where id=@id");
SqlParameter[] parameters = {
new SqlParameter("@id", SqlDbType.Int,4)};
parameters[0].Value = id;
int rows = SQLHelper.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 查询id得到一个对象实体
/// </summary>
/// <param name="id">消息id</param>
/// <returns>model对象</returns>
public Model.user_message GetModel(int id)
{
SqlParameter[] parameters = {
new SqlParameter("@id", SqlDbType.Int,4)};
parameters[0].Value = id;
Model.user_message model = new Model.user_message();
DataSet ds = SQLHelper.SelectSqlReturnDataSet("user_message_SelectMessageById", parameters, CommandType.StoredProcedure);
if (ds.Tables[0].Rows.Count > 0)
{
if (ds.Tables[0].Rows[0]["id"] != null && ds.Tables[0].Rows[0]["id"].ToString() != "")
{
model.id = int.Parse(ds.Tables[0].Rows[0]["id"].ToString());
}
if (ds.Tables[0].Rows[0]["type"] != null && ds.Tables[0].Rows[0]["type"].ToString() != "")
{
model.type = int.Parse(ds.Tables[0].Rows[0]["type"].ToString());
}
if (ds.Tables[0].Rows[0]["sender"] != null && ds.Tables[0].Rows[0]["sender"].ToString() != "")
{
model.sender = int.Parse(ds.Tables[0].Rows[0]["sender"].ToString());
}
if (ds.Tables[0].Rows[0]["receiver"] != null && ds.Tables[0].Rows[0]["receiver"].ToString() != "")
{
model.receiver = int.Parse(ds.Tables[0].Rows[0]["receiver"].ToString());
}
if (ds.Tables[0].Rows[0]["content"] != null && ds.Tables[0].Rows[0]["content"].ToString() != "")
{
model.content = ds.Tables[0].Rows[0]["content"].ToString();
}
if (ds.Tables[0].Rows[0]["is_read"] != null && ds.Tables[0].Rows[0]["is_read"].ToString() != "")
{
model.is_read = int.Parse(ds.Tables[0].Rows[0]["is_read"].ToString());
}
if (ds.Tables[0].Rows[0]["send_time"] != null && ds.Tables[0].Rows[0]["send_time"].ToString() != "")
{
model.send_time = DateTime.Parse(ds.Tables[0].Rows[0]["send_time"].ToString());
}
if (ds.Tables[0].Rows[0]["read_time"] != null && ds.Tables[0].Rows[0]["read_time"].ToString() != "")
{
model.read_time = DateTime.Parse(ds.Tables[0].Rows[0]["read_time"].ToString());
}
if (ds.Tables[0].Rows[0]["last_id"] != null && ds.Tables[0].Rows[0]["last_id"].ToString() != "")
{
model.last_id = int.Parse(ds.Tables[0].Rows[0]["last_id"].ToString());
}
return model;
}
else
{
return null;
}
}
/// <summary>
/// 根据消息ID递归查询所有的消息
/// </summary>
/// <param name="mesID">消息ID</param>
/// <returns>消息的集合</returns>
public IEnumerable<Model.user_message> GetMessageInfoBymesID(int mesID)
{
SqlParameter[] parameters = {
new SqlParameter("@mesID", SqlDbType.Int,6)};
parameters[0].Value = mesID;
var modelList=new List<Model.user_message>();
using (DataSet ds = SQLHelper.SelectSqlReturnDataSet("user_message_SelectMessageListBymesID", parameters, CommandType.StoredProcedure))
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
modelList.Add(GetModel(Convert.ToInt32(ds.Tables[0].Rows[i]["id"])));
}
return modelList;
}
}
/// <summary>
/// 根据用户ID和消息ID来查看该消息是否存在并且是否属于该用户
/// </summary>
/// <param name="id">消息id</param>
/// <param name="userID">用户ID</param>
/// <returns>是否属于</returns>
public bool Exists(int id, int userID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from (select sender,receiver from xg_user_message where id=@id)as T where sender=@userID or receiver=@userID");
SqlParameter[] parameters = {
new SqlParameter("@id", SqlDbType.Int,4),
new SqlParameter("@userID",SqlDbType.Int,4)};
parameters[0].Value = id;
parameters[1].Value = userID;
return SQLHelper.Exists(strSql.ToString(), parameters);
}
/// <summary>
/// 消息列表的分页的存储过程,根据各种参数
/// </summary>
/// <param name="ProcedureName">存储过程名</param>
/// <param name="parameters">参数</param>
/// <returns>消息ID的DataTable</returns>
public DataTable GetPageOfTypeForMsgList(string ProcedureName, SqlParameter[] parameters)
{
using (DataSet ds = SQLHelper.SelectSqlReturnDataSet(ProcedureName, parameters, CommandType.StoredProcedure))
{
return ds.Tables[0];
}
}
#endregion
#region 扩展方法=============================================
/// <summary>
/// 根据sql语句获取分页的消息数目
/// </summary>
/// <param name="sql">sql语句</param>
/// <returns>该条件下的消息数目</returns>
public int GetPageNum(string sql)
{
object ob = SQLHelper.GetSingle(sql);
if (ob==null)
{
return 0;
}
return Convert.ToInt32(ob);
}
/// <summary>
/// 回复消息
/// </summary>
/// <param name="type">发送方的类型</param>
/// <param name="senderID">发送者ID</param>
/// <param name="receiverID">接收者ID</param>
/// <param name="msgCon">消息内容</param>
/// <param name="last_id">上次的消息</param>
/// <returns>受影响的行数</returns>
public int InsertByOtherID(int type, int senderID, int receiverID, string msgCon, int last_id)
{
SqlParameter[] parameters = {
new SqlParameter("@type", SqlDbType.Int,6),
new SqlParameter("@sender",SqlDbType.Int,6),
new SqlParameter("@receiver",SqlDbType.Int,6),
new SqlParameter("@content",SqlDbType.NText),
new SqlParameter("@last_id",SqlDbType.TinyInt)
};
parameters[0].Value = type;
parameters[1].Value = senderID;
parameters[2].Value = receiverID;
parameters[3].Value = msgCon;
parameters[4].Value = last_id;
return SQLHelper.ExecuteSql("user_message_InsertByOtherID", parameters);
}
/// <summary>
/// 新建插入消息
/// </summary>
/// <param name="type">发送者的类型</param>
/// <param name="senderID">发送者</param>
/// <param name="receiverID">接收者</param>
/// <param name="msgCon">消息内容</param>
/// <returns>受影响的行数</returns>
public int InsertNewMsg(int type,int senderID,int receiverID,string msgCon)
{
StringBuilder str = new StringBuilder();
str.Append("INSERT INTO [xg_user_message] ");
str.Append("([type],[sender],[receiver],[content],[is_read],[send_time],[read_time],[last_id])");
str.Append(" VALUES(" + type);
str.Append("," + senderID);
str.Append("," + receiverID);
str.Append(",@content");
str.Append(",0");
str.Append(",getdate()");
str.Append(",NULL");
str.Append(",0)");
SqlParameter[] parameters = {
new SqlParameter("@content", SqlDbType.NText)};
parameters[0].Value=msgCon;
return SQLHelper.ExecuteSql(str.ToString(), parameters);
}
/// <summary>
/// 为管理员首页获取3条消息列表(管理员专用)
/// </summary>
/// <param name="userID">用户ID</param>
/// <returns>消息ID</returns>
public DataTable GetThreeMsg(int userID)
{
string sql = "select top 3 id from xg_user_message where receiver=" + userID + " order by is_read,id desc";
using (DataSet ds=SQLHelper.Query(sql))
{
return ds.Tables[0];
}
}
/// <summary>
/// 获取未读学生消息数目
/// </summary>
/// <param name="userID">用户ID</param>
/// <returns>消息数目</returns>
public int GetStuMsgNumForDefault(int userID)
{
string sql = "select count(id) from xg_user_message where receiver=" + userID + " and is_read=0 and type=1";
object obj = SQLHelper.GetSingle(sql);
if (obj==null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 获取未读系统消息数目
/// </summary>
/// <param name="userID">用户ID</param>
/// <returns>消息数目</returns>
public int GetSysMsgNumForDefault(int userID)
{
string sql = "select count(id) from xg_user_message where receiver=" + userID + " and is_read=0 and type=0";
object obj = SQLHelper.GetSingle(sql);
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 获取未读老师消息数目
/// </summary>
/// <param name="userID">用户ID</param>
/// <returns>消息数目</returns>
public int GetTerMsgNumForDefault(int userID)
{
string sql = "select count(id) from xg_user_message where receiver=" + userID + " and is_read=0 and type=2";
object obj = SQLHelper.GetSingle(sql);
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 获取未读管理员消息数目
/// </summary>
/// <param name="userID">用户ID</param>
/// <returns>消息数目</returns>
public int GetAdmMsgNumForDefault(int userID)
{
string sql = "select count(id) from xg_user_message where receiver=" + userID + " and is_read=0 and type=3";
object obj = SQLHelper.GetSingle(sql);
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 获取飞系统消息的未读数目
/// </summary>
/// <param name="userID">用户ID</param>
/// <returns>消息数目</returns>
public int GetNoSysMsgNum(int userID)
{
string sql = "select count(id) from xg_user_message where receiver=" + userID + " and is_read=0";
object obj = SQLHelper.GetSingle(sql);
if (obj == null)
{
return 0;
}
else
{
return (Convert.ToInt32(obj) - GetSysMsgNumForDefault(userID));
}
}
/// <summary>
/// 读取消息后设置该消息为已读
/// </summary>
/// <param name="msgID">消息ID</param>
/// <returns>受影响的行数</returns>
public int updateMsgIsRead(int msgID)
{
string sql = "UPDATE [xg_user_message] SET [is_read] = 1,[read_time] = GETDATE() WHERE id=" + msgID;
return SQLHelper.ExecuteSql(sql);
}
/// <summary>
/// 根据消息ID和用户ID判断这条消息是否给这个用户
/// </summary>
/// <param name="msgID">消息ID</param>
/// <param name="userID">用户ID</param>
/// <returns>是否是给这个用户的消息</returns>
public bool IsThisMsgToReciver(int msgID,int userID)
{
string sql = "select count(1) from xg_user_message where id=" + msgID + " and receiver="+userID;
return SQLHelper.Exists(sql);
}
#endregion
}
}
|
/*
Description: This file declares the ExtensionRequest ViewModel and its properties
for the ExtensionRequest Controller and views.
Author: EAS
*/
using Project._1.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using static Project._1.Models.ExtensionRequest;
using static Project._1.Models.ProbationaryColleague;
namespace Release2.ViewModels
{
/// <summary>
///Extension Request View Model from Extension Request model and used by Extension Request controller
/// </summary>
public class ExtensionRequestViewModel
{
public int Id { get; set; }
[Display(Name = "Extended To")]
public Levels ExtNumber { get; set; }
[Display(Name = "Reason")]
[StringLength(500, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 20)]
[DataType(DataType.MultilineText)]
public string ExtReason { get; set; }
[Display(Name = "Extension Request Status")]
public RequestStatus ExtRequestStatus { get; set; }
[Display(Name = "Submission Date")]
[Column(TypeName = "date")]
public DateTime? ExtRequestSubmissionDate { get; set; }
[Display(Name = "Audit date")]
[Column(TypeName = "date")]
public Levels Level { get; set; }
public ProbationTypes ProbationType { get; set; }
public DateTime? ExtRequestAuditDate { get; set; }
public int? HRAuditId { get; set; }
public int LMSubmitId { get; set; }
public int ExtendedPCId { get; set; }
[Display(Name = "Audited By")]
public string HRAudits { get; set; }
[Display(Name = "Submitted By")]
public string LMSubmits { get; set; }
[Display(Name = "Probationary Colleague")]
public string ExtendedPC { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireThrower : MonoBehaviour {
public GameObject fireThrower;
private GameObject instanceFireThrower;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
public void Fire()
{
instanceFireThrower = Instantiate(fireThrower, transform.position, transform.rotation) as GameObject;
instanceFireThrower.transform.parent = this.transform;
}
public void DestroyFire()
{
Destroy(instanceFireThrower);
}
}
|
using Library.Domain.Concrete;
using Library.Domain.Infrastructure;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library.Domain.Entities
{
public class AppUserManager : UserManager<AppUser>
{
public AppUserManager(IUserStore<AppUser> store) : base(store) { }
public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
{
EFDbContext db = context.Get<EFDbContext>();
AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db));
manager.PasswordValidator = new CustomPasswordValidator
{
RequiredLength = 4,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true
};
manager.UserValidator = new UserValidator<AppUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
const string name = "admin";
const string password = "zaq1@WSXc";
const string email = "admin@gmail.com";
const string role = "Admin";
AppUser user = manager.FindByName(name);
if(user == null)
{
user = new AppUser { UserName = name, Email = email };
manager.Create(user, password);
}
var userRole = manager.GetRoles(user.Id);
if (!userRole.Contains(role))
{
manager.AddToRole(user.Id, role);
}
return manager;
}
}
}
|
using System;
namespace LeeConlin.ExtensionMethods
{
public static class UriBuilderExtensions
{
public static string ToCommonUrlString(this UriBuilder uriBuilder)
{
return uriBuilder.Uri.ToCommonUrlString();
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using firma_budowlana.Models;
namespace firma_budowlana.Controllers
{
public class NotificationsController : Controller
{
private Entities db = new Entities();
// GET: Notifications
public ActionResult Index()
{
var zgloszenia = db.zgloszenia.Include(z => z.klienci);
return View(zgloszenia.ToList());
}
// GET: Notifications/Create
public ActionResult Create()
{
ViewBag.autor_zgloszenia = new SelectList(db.klienci, "id", "dane_personalne.fullName", db.zgloszenia.Include(g => g.klienci));
return View();
}
// POST: Notifications/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,autor_zgloszenia,opis,data_utworzenia")] zgloszenia zgloszenia)
{
if (ModelState.IsValid)
{
db.zgloszenia.Add(zgloszenia);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(zgloszenia);
}
// GET: Notifications/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
zgloszenia zgloszenia = db.zgloszenia.Find(id);
if (zgloszenia == null)
{
return HttpNotFound();
}
ViewBag.autor_zgloszenia = new SelectList(db.klienci, "id", "dane_personalne.fullName", db.zgloszenia.Include(g => g.klienci));
return View(zgloszenia);
}
// POST: Notifications/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "id,autor_zgloszenia,opis,data_utworzenia")] zgloszenia zgloszenia)
{
if (ModelState.IsValid)
{
db.Entry(zgloszenia).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(zgloszenia);
}
// GET: Notifications/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
zgloszenia zgloszenia = db.zgloszenia.Find(id);
if (zgloszenia == null)
{
return HttpNotFound();
}
return View(zgloszenia);
}
// POST: Notifications/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
zgloszenia zgloszenia = db.zgloszenia.Find(id);
try
{
db.zgloszenia.Remove(zgloszenia);
db.SaveChanges();
}
catch (DataException error)
{
TempData["error"] = true;
return RedirectToAction("Delete");
}
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
namespace physics2
{
public interface IEvent
{
double Time { get; }
MightBeCollision Enact();
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PauseWindow : GenericWindow {
public ConfirmationExitToDesktopWindow exitToDesktopWindow;
public ConfirmationExitToMainMenuWindow exitToMainMenuWindow;
public GameObject gameGO;
//public PauseGame pauseGameScript;
public void OnReturn() {
gameGO.SetActive(true);
//pauseGameScript.paused = false;
this.Close();
}
public void OnOptions() {
manager.Open((int)Windows.OptionsWindow - 1);
}
public void OnExitToMainMenu() {
manager.Open((int)Windows.ConfirmationExitToMainMenuWindow - 1);
}
public void OnExitToDesktop() {
manager.Open((int)Windows.ConfirmationExitToDesktopWindow - 1);
}
} |
using UnityEngine;
[CreateAssetMenu(fileName = "Give Item", menuName = "Dialogue Event/Give Item")]
public class DialogueGiveItem : DialogueEvent
{
public int successLink;
public int failLink;
public ItemStats item;
public override int OnEvent()
{
if (GameManager.instance.Inventory.AddToInv(item))
{
return successLink;
}
else
{
return failLink;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Lab_5._3
{
internal class IdentityMatrix : BaseMatrix
{
private int[,] identitymatrix = new int[3, 3];
public IdentityMatrix()
{
for (int i = 0; i < 3; i++) // За тройку извините
{
for (int a = 0; a < 3; a++) // И тут тоже
{
if (i == a)
{
identitymatrix[i, a] = 1;
}
else
{
identitymatrix[i, a] = 0;
}
}
}
}
public void FillMatrix(ref TextBox Box00, ref TextBox Box10, ref TextBox Box20, ref TextBox Box01, ref TextBox Box11, ref TextBox Box21, ref TextBox Box02, ref TextBox Box12, ref TextBox Box22)
{
Box00.Text = Convert.ToString(identitymatrix[0, 0]);
Box10.Text = Convert.ToString(identitymatrix[1, 0]);
Box20.Text = Convert.ToString(identitymatrix[2, 0]);
Box01.Text = Convert.ToString(identitymatrix[0, 1]);
Box11.Text = Convert.ToString(identitymatrix[1, 1]);
Box21.Text = Convert.ToString(identitymatrix[2, 1]);
Box02.Text = Convert.ToString(identitymatrix[0, 2]);
Box12.Text = Convert.ToString(identitymatrix[1, 2]);
Box22.Text = Convert.ToString(identitymatrix[2, 2]);
}
}
}
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace DynamicPermission.AspNetCore.ViewModels.User
{
public class UserRolesViewModel
{
public string Id { get; set; }
public string UserName { get; set; }
public List<string> ValidRoles { get; set; }
public List<string> SelectedRoles { get; set; }
public bool IsAdd { get; set; }
}
}
|
using System;
namespace NetFabric.Hyperlinq.Benchmarks
{
static class Utils
{
public static int[] GetSequentialValues(int count)
{
var array = new int[count];
for (var index = 0; index < count; index++)
array[index] = index;
return array;
}
public static int[] GetRandomValues(int seed, int count)
{
var array = new int[count];
var random = new Random(seed);
for (var index = 0; index < count; index++)
array[index] = random.Next(count);
return array;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LucidChallenge
{
static class Lucid
{
static void Main(string[] args)
{
var grid = ReadGrid();
Console.WriteLine(FindLongestPath(grid));
}
private static int FindLongestPath(int[][] grid)
{
int longest_path = 0;
for(int i = 0; i < grid.Length; i++)
{
for (int j = 0; j < grid[i].Length; j++)
{
Node node = new Node(null, grid[i][j]);
node.AddChildren(grid, i, j);
longest_path = Math.Max(longest_path, node.LongestPath);
int k = 0;
}
}
return longest_path;
}
private static int[][] ReadGrid()
{
List<int[]> lines = new List<int[]>();
Console.ReadLine(); //skip the first line
string line;
while((line = Console.ReadLine()) != null && line != "")
lines.Add(Array.ConvertAll(line.Split(), s=> int.Parse(s)));
return lines.ToArray();
}
}
class Node
{
public Node Parent { get; set; }
public List<Node> Children { get; set; }
public int Value { get; set; }
public Node(Node parent, int val)
{
Parent = parent;
Value = val;
Children = new List<Node>();
}
internal void AddChildren(int[][] grid, int i, int j)
{
TryAddChild(grid, i - 1, j - 1);
TryAddChild(grid, i - 1, j);
TryAddChild(grid, i - 1, j + 1);
TryAddChild(grid, i, j - 1);
TryAddChild(grid, i, j + 1);
TryAddChild(grid, i + 1, j - 1);
TryAddChild(grid, i + 1, j);
TryAddChild(grid, i + 1, j + 1);
}
public int LongestPath {
get
{
if (Children.Count == 0)
return 1;
List<int> maxs = new List<int>();
foreach (var child in Children)
maxs.Add(child.LongestPath);
return 1 + maxs.Max();
}
}
private void TryAddChild(int[][] grid, int i, int j)
{
if (!(i >= 0 && j >= 0 && i < grid.Length && j < grid[i].Length && Math.Abs(Value - grid[i][j]) >= 3))
return;
Node tempParent = this.Parent;
while (tempParent != null)
{
if (tempParent.Value == grid[i][j])
return;
tempParent = tempParent.Parent;
}
Node child = new Node(this,grid[i][j]);
child.AddChildren(grid, i, j);
Children.Add(child);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using StacksAndQueue.Classes;
namespace FIFOAnilmalShelter.Classes
{
public class Animal
{
public string Type { get; set; }
public Animal Next { get; set; }
public Animal()
{
}
public Animal (string type)
{
Type = type;
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace GameProject.Manager:IGameService
{
class CampaignManager
{
public void Add(Campaign campaign)
{
Console.WriteLine("Kampanya eklendi: "+campaign.CampaignName+"İndirim oranı:"+campaign.DiscountRate+'\n');
}
public void Update(Campaign campaign)
{
Console.WriteLine("Kampanya güncellendi: "+campaign.CampaignName+"İndirim oranı:"+campaign.DiscountRate+'\n');
}
public void Delete(Campaign campaign)
{
Console.WriteLine(campaign.CampaignName+"süresi doldugundan kampanya silindi"+'\n');
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
//using System.Data.Entity.Spatial;
namespace Entities
{
public partial class Sales
{
public Sales()
{
Tickets = new HashSet<Tickets>();
}
[Key]
public Guid saleId { get; set; }
public DateTime saleDateTime { get; set; }
public Guid userId { get; set; }
public virtual Users Users { get; set; }
public virtual ICollection<Tickets> Tickets { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace BPiaoBao.Common.Enums
{
/// <summary>
/// 证件类型枚举
/// </summary>
public enum EnumIDType
{
[Description("身份证")]
NormalId = 0,
[Description("护照")]
Passport = 1,
[Description("军官证")]
MilitaryId = 2,
[Description("出生日期")]
BirthDate = 3,
[Description("其它有效证件")]
Other = 4
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Task 12
namespace Employee_Data
{
class Program
{
static void Main(string[] args)
{
string firstName = "";
string lastName = "";
short? age;
char? gender;
int? uniqueNumber;
}
}
}
|
// Accord Machine Learning Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.MachineLearning
{
using Accord.Statistics;
using System;
using System.Collections.Generic;
/// <summary>
/// k-Fold cross-validation.
/// </summary>
///
/// <remarks>
/// <para>
/// Cross-validation is a technique for estimating the performance of a predictive
/// model. It can be used to measure how the results of a statistical analysis will
/// generalize to an independent data set. It is mainly used in settings where the
/// goal is prediction, and one wants to estimate how accurately a predictive model
/// will perform in practice.</para>
/// <para>
/// One round of cross-validation involves partitioning a sample of data into
/// complementary subsets, performing the analysis on one subset (called the
/// training set), and validating the analysis on the other subset (called the
/// validation set or testing set). To reduce variability, multiple rounds of
/// cross-validation are performed using different partitions, and the validation
/// results are averaged over the rounds.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/Cross-validation_(statistics)">
/// Wikipedia, The Free Encyclopedia. Cross-validation (statistics). Available on:
/// http://en.wikipedia.org/wiki/Cross-validation_(statistics) </a></description></item>
/// </list></para>
/// </remarks>
///
/// <example>
/// <code>
/// // This is a sample code on how to use Cross-Validation
/// // to assess the performance of Support Vector Machines.
///
/// // Consider the example binary data. We will be trying
/// // to learn a XOR problem and see how well does SVMs
/// // perform on this data.
///
/// double[][] data =
/// {
/// new double[] { -1, -1 }, new double[] { 1, -1 },
/// new double[] { -1, 1 }, new double[] { 1, 1 },
/// new double[] { -1, -1 }, new double[] { 1, -1 },
/// new double[] { -1, 1 }, new double[] { 1, 1 },
/// new double[] { -1, -1 }, new double[] { 1, -1 },
/// new double[] { -1, 1 }, new double[] { 1, 1 },
/// new double[] { -1, -1 }, new double[] { 1, -1 },
/// new double[] { -1, 1 }, new double[] { 1, 1 },
/// };
///
/// int[] xor = // result of xor for the sample input data
/// {
/// -1, 1,
/// 1, -1,
/// -1, 1,
/// 1, -1,
/// -1, 1,
/// 1, -1,
/// -1, 1,
/// 1, -1,
/// };
///
///
/// // Create a new Cross-validation algorithm passing the data set size and the number of folds
/// var crossvalidation = new CrossValidation(size: data.Length, folds: 3);
///
/// // Define a fitting function using Support Vector Machines. The objective of this
/// // function is to learn a SVM in the subset of the data indicated by cross-validation.
///
/// crossvalidation.Fitting = delegate(int k, int[] indicesTrain, int[] indicesValidation)
/// {
/// // The fitting function is passing the indices of the original set which
/// // should be considered training data and the indices of the original set
/// // which should be considered validation data.
///
/// // Lets now grab the training data:
/// var trainingInputs = data.Submatrix(indicesTrain);
/// var trainingOutputs = xor.Submatrix(indicesTrain);
///
/// // And now the validation data:
/// var validationInputs = data.Submatrix(indicesValidation);
/// var validationOutputs = xor.Submatrix(indicesValidation);
///
///
/// // Create a Kernel Support Vector Machine to operate on the set
/// var svm = new KernelSupportVectorMachine(new Polynomial(2), 2);
///
/// // Create a training algorithm and learn the training data
/// var smo = new SequentialMinimalOptimization(svm, trainingInputs, trainingOutputs);
///
/// double trainingError = smo.Run();
///
/// // Now we can compute the validation error on the validation data:
/// double validationError = smo.ComputeError(validationInputs, validationOutputs);
///
/// // Return a new information structure containing the model and the errors achieved.
/// return new CrossValidationValues(svm, trainingError, validationError);
/// };
///
///
/// // Compute the cross-validation
/// var result = crossvalidation.Compute();
///
/// // Finally, access the measured performance.
/// double trainingErrors = result.Training.Mean;
/// double validationErrors = result.Validation.Mean;
/// </code>
/// </example>
///
/// <seealso cref="Bootstrap"/>
/// <seealso cref="CrossValidation{T}"/>
/// <seealso cref="SplitSetValidation{T}"/>
///
[Serializable]
public class CrossValidation : CrossValidation<object>
{
/// <summary>
/// Creates a new k-fold cross-validation algorithm.
/// </summary>
///
/// <param name="size">The total number samples in the entire dataset.</param>
///
public CrossValidation(int size)
: base(size) { }
/// <summary>
/// Creates a new k-fold cross-validation algorithm.
/// </summary>
///
/// <param name="size">The total number samples in the entire dataset.</param>
/// <param name="folds">The number of folds, usually denoted as <c>k</c> (default is 10).</param>
///
public CrossValidation(int size, int folds)
: base(size, folds) { }
/// <summary>
/// Creates a new k-fold cross-validation algorithm.
/// </summary>
///
/// <param name="labels">A vector containing class labels.</param>
/// <param name="classes">The number of different classes in <paramref name="labels"/>.</param>
/// <param name="folds">The number of folds, usually denoted as <c>k</c> (default is 10).</param>
///
public CrossValidation(int[] labels, int classes, int folds)
: base(labels, classes, folds) { }
/// <summary>
/// Creates a new k-fold cross-validation algorithm.
/// </summary>
///
/// <param name="indices">An already created set of fold indices for each sample in a dataset.</param>
/// <param name="folds">The total number of folds referenced in the <paramref name="indices"/> parameter.</param>
///
public CrossValidation(int[] indices, int folds)
: base(indices, folds) { }
/// <summary>
/// Create cross-validation folds by generating a vector of random fold indices.
/// </summary>
///
/// <param name="size">The number of points in the data set.</param>
/// <param name="folds">The number of folds in the cross-validation.</param>
///
/// <returns>A vector of indices defining the a fold for each point in the data set.</returns>
///
public static int[] Splittings(int size, int folds)
{
return Categorical.Random(size, folds);
}
/// <summary>
/// Create cross-validation folds by generating a vector of random fold indices,
/// making sure class labels get equally distributed among the folds.
/// </summary>
///
/// <param name="labels">A vector containing class labels.</param>
/// <param name="classes">The number of different classes in <paramref name="labels"/>.</param>
/// <param name="folds">The number of folds in the cross-validation.</param>
///
/// <returns>A vector of indices defining the a fold for each point in the data set.</returns>
///
public static int[] Splittings(int[] labels, int classes, int folds)
{
return Categorical.Random(labels, classes, folds);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using HardwareInventoryManager;
using HardwareInventoryManager.Models;
using HardwareInventoryManager.Filters;
namespace HardwareInventoryManager.Controllers
{
[CustomAuthorize]
public class QuoteResponsesController : Controller
{
private CustomApplicationDbContext db = new CustomApplicationDbContext();
// GET: QuoteResponses
public ActionResult Index()
{
var quoteResponses = db.QuoteResponses.Include(q => q.QuoteRequest);
return View(quoteResponses.ToList());
}
// GET: QuoteResponses/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
QuoteResponse quoteResponse = db.QuoteResponses.Find(id);
if (quoteResponse == null)
{
return HttpNotFound();
}
return View(quoteResponse);
}
// GET: QuoteResponses/Create
public ActionResult Create()
{
ViewBag.QuoteReposonseId = new SelectList(db.QuoteRequests, "QuoteRequestId", "SpecificationDetails");
return View();
}
// POST: QuoteResponses/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "QuoteReposonseId,QuoteCostPerItem,QuoteCostTotal,Notes,QuoteRequestId")] QuoteResponse quoteResponse)
{
if (ModelState.IsValid)
{
db.QuoteResponses.Add(quoteResponse);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.QuoteReposonseId = new SelectList(db.QuoteRequests, "QuoteRequestId", "SpecificationDetails", quoteResponse.QuoteReposonseId);
return View(quoteResponse);
}
// GET: QuoteResponses/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
QuoteResponse quoteResponse = db.QuoteResponses.Find(id);
if (quoteResponse == null)
{
return HttpNotFound();
}
ViewBag.QuoteReposonseId = new SelectList(db.QuoteRequests, "QuoteRequestId", "SpecificationDetails", quoteResponse.QuoteReposonseId);
return View(quoteResponse);
}
// POST: QuoteResponses/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "QuoteReposonseId,QuoteCostPerItem,QuoteCostTotal,Notes,QuoteRequestId")] QuoteResponse quoteResponse)
{
if (ModelState.IsValid)
{
db.Entry(quoteResponse).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.QuoteReposonseId = new SelectList(db.QuoteRequests, "QuoteRequestId", "SpecificationDetails", quoteResponse.QuoteReposonseId);
return View(quoteResponse);
}
// GET: QuoteResponses/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
QuoteResponse quoteResponse = db.QuoteResponses.Find(id);
if (quoteResponse == null)
{
return HttpNotFound();
}
return View(quoteResponse);
}
// POST: QuoteResponses/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
QuoteResponse quoteResponse = db.QuoteResponses.Find(id);
db.QuoteResponses.Remove(quoteResponse);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Win32.SafeHandles;
namespace NtApiDotNet.Win32.Rpc
{
internal class CrackedBindingString
{
public string ObjUuid { get; }
public string Protseq { get; }
public string NetworkAddr { get; }
public string Endpoint { get; }
public string NetworkOptions { get; }
public CrackedBindingString(string string_binding)
{
SafeRpcStringHandle objuuid = null;
SafeRpcStringHandle protseq = null;
SafeRpcStringHandle endpoint = null;
SafeRpcStringHandle networkaddr = null;
SafeRpcStringHandle networkoptions = null;
try
{
var status = Win32NativeMethods.RpcStringBindingParse(string_binding,
out objuuid, out protseq, out networkaddr, out endpoint, out networkoptions);
if (status == Win32Error.SUCCESS)
{
ObjUuid = objuuid.ToString();
Protseq = protseq.ToString();
Endpoint = endpoint.ToString();
NetworkAddr = networkaddr.ToString();
NetworkOptions = networkoptions.ToString();
}
else
{
ObjUuid = string.Empty;
Protseq = string.Empty;
Endpoint = string.Empty;
NetworkAddr = string.Empty;
NetworkOptions = string.Empty;
}
}
finally
{
objuuid?.Dispose();
protseq?.Dispose();
endpoint?.Dispose();
networkaddr?.Dispose();
networkoptions?.Dispose();
}
}
}
}
|
using SFML.Graphics;
using SFML.Window;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace LD30
{
abstract class World : GameObject
{
public bool[,] Collisions;
VertexArray tileVA;
Image worldImage;
RenderStates states = RenderStates.Default;
public Dictionary<string, Vector2f> PositionCache = new Dictionary<string, Vector2f>();
public override bool Enabled
{
get
{
return base.Enabled;
}
set
{
base.Enabled = value;
if (!value)
{
tileVA.Clear();
}
}
}
public World(Game game, Image worldImage)
: base(game)
{
this.worldImage = worldImage;
tileVA = new VertexArray(PrimitiveType.Quads, worldImage.Size.X * worldImage.Size.Y * 4);
Collisions = new bool[worldImage.Size.X, worldImage.Size.Y];
states.Transform.Scale(Game.TilemapScale, Game.TilemapScale);
states.Texture = ResourceManager.GetResource<Texture>("tilemapTex");
for (int x = 0; x < worldImage.Size.X; x++)
{
for (int y = 0; y < worldImage.Size.Y; y++)
{
if (getCollisionForColor(worldImage.GetPixel((uint)x, (uint)y)))
Collisions[x, y] = true;
}
}
}
public Vector2f FindFirstWorldPositionForColor(Color findColor)
{
for (int x = 0; x < worldImage.Size.X; x++)
{
for (int y = 0; y < worldImage.Size.Y; y++)
{
var color = worldImage.GetPixel((uint)x, (uint)y);
if (Utility.ColorEquals(color, findColor))
return new Vector2f(x * Game.TileSize, y * Game.TileSize);
}
}
throw new ArgumentException("Couldn't find the specified color");
}
public List<Vector2i> FindAllLocalPositionsForColor(Color findColor)
{
var finds = new List<Vector2i>();
for (int x = 0; x < worldImage.Size.X; x++)
{
for (int y = 0; y < worldImage.Size.Y; y++)
{
var color = worldImage.GetPixel((uint)x, (uint)y);
if (Utility.ColorEquals(color, findColor))
finds.Add(new Vector2i(x, y));
}
}
return finds;
}
public List<Vector2f> FindAllWorldPositionsForColor(Color findColor)
{
var findsLocal = FindAllLocalPositionsForColor(findColor);
var finds = new List<Vector2f>();
for (int i = 0; i < findsLocal.Count; i++)
{
finds.Add(new Vector2f(findsLocal[i].X * Game.TileSize, findsLocal[i].Y * Game.TileSize));
}
return finds;
}
public Color GetColorAtWorldPosition(Vector2f worldPos)
{
var localPos = worldPos * (1f / Game.TileSize);
var color = worldImage.GetPixel((uint)Math.Floor(localPos.X), (uint)Math.Floor(localPos.Y));
return color;
}
public FloatRect GetWorldFloatRectForTile(Vector2i coords)
{
return new FloatRect(coords.X * Game.TileSize, coords.Y * Game.TileSize, Game.TileSize, Game.TileSize);
}
public override void Draw(RenderTarget target)
{
if (!Enabled)
return;
var topLeftView = target.MapPixelToCoords(new Vector2i());
var botRightView = target.MapPixelToCoords(new Vector2i((int)game.MainWindow.Size.X - 1, (int)game.MainWindow.Size.Y - 1));
var viewRect = new FloatRect(topLeftView.X, topLeftView.Y, botRightView.X - topLeftView.X, botRightView.Y - topLeftView.Y);
var topLeftLocal = new Vector2i((int)Math.Floor(topLeftView.X / Game.TileSize), (int)Math.Floor(topLeftView.Y / Game.TileSize));
var botRightLocal = new Vector2i((int)Math.Ceiling(botRightView.X / Game.TileSize), (int)Math.Ceiling(botRightView.Y / Game.TileSize));
tileVA.Clear();
for (int x = topLeftLocal.X; x < botRightLocal.X; x++)
{
for (int y = topLeftLocal.Y; y < botRightLocal.Y; y++)
{
if (x < 0 || y < 0 || x > worldImage.Size.X - 1 || y > worldImage.Size.Y - 1)
continue;
var color = worldImage.GetPixel((uint)x, (uint)y);
var pos = getTilemapPositionForColor(color);
var topLeft = new Vertex(
new Vector2f(x * Game.TilemapSize, y * Game.TilemapSize),
pos);
var topRight = new Vertex(
new Vector2f((x + 1) * Game.TilemapSize, y * Game.TilemapSize),
pos + new Vector2f(Game.TilemapSize, 0f));
var botRight = new Vertex(
new Vector2f((x + 1) * Game.TilemapSize, (y + 1) * Game.TilemapSize),
pos + new Vector2f(Game.TilemapSize, Game.TilemapSize));
var botLeft = new Vertex(
new Vector2f(x * Game.TilemapSize, (y + 1) * Game.TilemapSize),
pos + new Vector2f(0f, Game.TilemapSize));
tileVA.Append(topLeft);
tileVA.Append(topRight);
tileVA.Append(botRight);
tileVA.Append(botLeft);
}
}
target.Draw(tileVA, states);
}
protected abstract Vector2f getTilemapPositionForColor(Color color);
protected abstract bool getCollisionForColor(Color color);
}
}
|
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.Threading;
namespace BaiGiuaKy_PhanVanVuong
{
public partial class FrmDrawLine : Form
{
float xa, xb, ya, yb;
public FrmDrawLine()
{
InitializeComponent();
}
public bool checkInput()
{
bool check = true;
if (tbXa.Text.Equals("") || tbYa.Text.Equals("") || tbXb.Text.Equals("") || tbYb.Text.Equals(""))
{
check = false;
MessageBox.Show("Nhập đủ tọa độ 2 điểm");
}
else
{
try
{
xa = float.Parse(tbXa.Text);
ya = float.Parse(tbYa.Text);
xb = float.Parse(tbXb.Text);
yb = float.Parse(tbYb.Text);
if (xa < 0 || xb < 0 || ya < 0 || yb < 0)
{
MessageBox.Show("Cần nhập tọa độ là số lớn hơn 0");
check = false;
}
else
{
if (xa >= ptbDraw.Width || xb >= ptbDraw.Width || ya >= ptbDraw.Height || yb >= ptbDraw.Height)
{
check = false;
MessageBox.Show("Tọa độ điểm vượt quá khung vẽ");
}
}
}
catch (Exception e)
{
MessageBox.Show("Tọa độ cần nhập số");
check = false;
}
}
return check;
}
public void drawDDA(int x1, int y1, int x2, int y2, Bitmap bm)
{
float xtd = (x1 + x2) / 2;
float ytd = (y1 + y2) / 2;
// Vẽ DDA kết hợp vẽ đối xứng
float dx, dy, steps;
float xInc, yInc, x, y;
dx = xtd - x1;
dy = ytd - y1;
if (Math.Abs(dx) > Math.Abs(dy))
steps = Math.Abs(dx);
else
steps = Math.Abs(dy);
xInc = dx / steps;
yInc = dy / steps;
x = x1;
y = y1;
bm.SetPixel((int)x, (int)y, Color.Red);
bm.SetPixel((int)(2 * xtd - x), (int)(2 * ytd - y), Color.Black);
for (int k = 1; k < steps; k++)
{
x = x + xInc;
y = y + yInc;
bm.SetPixel((int)x, (int)y, Color.Red);
bm.SetPixel((int)(2 * xtd - x), (int)(2 * ytd - y), Color.Black);
}
}
public void drawNetDut(int x1, int y1, int x2, int y2, Bitmap bm)
{
bool draw = true;
float dx, dy, steps;
float xInc, yInc, x, y;
dx = x2 - x1;
dy = y2 - y1;
if (Math.Abs(dx) > Math.Abs(dy))
steps = Math.Abs(dx);
else
steps = Math.Abs(dy);
xInc = dx / steps;
yInc = dy / steps;
x = x1;
y = y1;
bm.SetPixel((int)x, (int)y, Color.Red);
int i = (int)(steps / 10);
int point = i;
for (int k = 1; k < steps; k++)
{
x = x + xInc;
y = y + yInc;
if (k == point)
{
draw = draw ? false : true;
point += i;
}
if (draw)
{
bm.SetPixel((int)x, (int)y, Color.Red);
}
}
}
public void drawLineTrans(int x1, int y1, int x2, int y2, Bitmap bm)
{
float dx, dy, steps;
float xInc, yInc, x, y;
dx = x2 - x1;
dy = y2 - y1;
if (Math.Abs(dx) > Math.Abs(dy))
steps = Math.Abs(dx);
else
steps = Math.Abs(dy);
xInc = dx / steps;
yInc = dy / steps;
x = x1;
y = y1;
bm.SetPixel((int)x, (int)y, Color.Red);
int trans = 255;
int i = (int)(steps / 255);
int point = i > 1 ? i : 1;
for (int k = 1; k < steps; k++)
{
x = x + xInc;
y = y + yInc;
if (k == point)
{
trans--;
if (trans < 0)
{
trans = 0;
}
point += (i > 1 ? i : 1);
}
bm.SetPixel((int)x, (int)y, Color.FromArgb(trans, Color.Black));
}
}
public void drawLineBold(int x1, int y1, int x2, int y2, Bitmap bm)
{
float dx, dy, steps;
float xInc, yInc, x, y;
dx = x2 - x1;
dy = y2 - y1;
if (Math.Abs(dx) > Math.Abs(dy))
steps = Math.Abs(dx);
else
steps = Math.Abs(dy);
xInc = dx / steps;
yInc = dy / steps;
x = x1;
y = y1;
bm.SetPixel((int)x, (int)y, Color.Red);
for (int k = 1; k < steps; k++)
{
x = x + xInc;
y = y + yInc;
for (int i = 0; i < 4; i++)
{
bm.SetPixel((int)(x + i), (int)(y + i), Color.Black);
}
}
}
public void Swap(ref int x1, ref int x2)
{
int temp = x1;
x1 = x2;
x2 = temp;
}
public void drawBresenham(int x1, int y1, int x2, int y2, Bitmap bm)
{
bool flag = false;
int p, const1, const2;
int Dy, Dx;
int i, tang;
if (Math.Abs(x1 - x2) < Math.Abs(y1 - y2))
{
flag = true;
Swap(ref x1, ref y1);
Swap(ref x2, ref y2);
}
if (x1 > x2)
{
Swap(ref x1, ref x2);
Swap(ref y1, ref y2);
}
//---------Tinh Bresenham------------
Dy = y2 - y1;
Dx = x2 - x1;
//--------Tinh huong tang cua Dy
if (Dy > 0) tang = 1;
else
{
tang = -1;
Dy = Dy * -1;
}
p = 2 * Dy - Dx;
const1 = 2 * Dy;
const2 = 2 * (Dy - Dx);
bm.SetPixel(x1, y1, Color.Red);
if (flag == false)
{
for (i = x1; i < x2; i++)
{
if (p < 0) p = p + const1;
else
{
p = p + const2;
y1 += tang;
}
x1++;
bm.SetPixel(x1, y1, Color.Red);
}
}
else
{
for (i = x1; i < x2; i++)
{
if (p < 0) p = p + const1;
else
{
p = p + const2;
y1 += tang;
}
x1++;
bm.SetPixel(y1, x1, Color.Red);
}
}
}
public void drawMidPoint(int x1, int y1, int x2, int y2, Bitmap bm)
{
int x, y, dx, dy, d;
bool flag = false;
int i, tang;
if (Math.Abs(x1 - x2) < Math.Abs(y1 - y2))
{
flag = true;
Swap(ref x1, ref y1);
Swap(ref x2, ref y2);
}
if (x1 > x2)
{
Swap(ref x1, ref x2);
Swap(ref y1, ref y2);
}
y = y1;
dx = x2 - x1;
dy = y2 - y1;
d = dy - dx / 2;
//--------Tinh huong tang cua Dy
if (dy > 0) tang = 1;
else
{
tang = -1;
dy = dy * -1;
}
if (flag == false)
{
for (x = x1; x <= x2; x++)
{
bm.SetPixel(x, y, Color.Red);
if (d <= 0)
d = d + dy;
else
{
y += tang;
d = d + dy - dx;
}
}
}
else
{
for (x = x1; x <= x2; x++)
{
bm.SetPixel(y, x, Color.Red);
if (d <= 0)
d = d + dy;
else
{
y += tang;
d = d + dy - dx;
}
}
}
}
private void btnLineDut_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(ptbDraw.Width, ptbDraw.Height);
Graphics grap = Graphics.FromImage(bm);
grap.Clear(Color.White);
if (checkInput())
{
drawNetDut((int)xa, (int)ya, (int)xb, (int)yb, bm);
ptbDraw.Image = bm;
}
}
private void btnLineTrans_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(ptbDraw.Width, ptbDraw.Height);
Graphics grap = Graphics.FromImage(bm);
grap.Clear(Color.White);
if (checkInput())
{
drawLineTrans((int)xa, (int)ya, (int)xb, (int)yb, bm);
ptbDraw.Image = bm;
}
}
private void btnLineBold_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(ptbDraw.Width, ptbDraw.Height);
Graphics grap = Graphics.FromImage(bm);
grap.Clear(Color.White);
if (checkInput())
{
drawLineBold((int)xa, (int)ya, (int)xb, (int)yb, bm);
ptbDraw.Image = bm;
}
}
private void FrmDrawLine_Load(object sender, EventArgs e)
{
}
private void btnBresenham_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(ptbDraw.Width, ptbDraw.Height);
Graphics grap = Graphics.FromImage(bm);
grap.Clear(Color.White);
if (checkInput())
{
drawBresenham((int)xa, (int)ya, (int)xb, (int)yb, bm);
ptbDraw.Image = bm;
}
}
private void btnMidPoint_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(ptbDraw.Width, ptbDraw.Height);
Graphics grap = Graphics.FromImage(bm);
grap.Clear(Color.White);
if (checkInput())
{
drawMidPoint((int)xa, (int)ya, (int)xb, (int)yb, bm);
ptbDraw.Image = bm;
}
}
private void btnDDA_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(ptbDraw.Width, ptbDraw.Height);
Graphics grap = Graphics.FromImage(bm);
grap.Clear(Color.White);
if (checkInput())
{
drawDDA((int)xa, (int)ya, (int)xb, (int)yb, bm);
ptbDraw.Image = bm;
}
}
}
}
|
using NUnit.Framework;
using System;
using System.IO;
using System.Diagnostics;
using FizzBuzzKata;
namespace FizzBuzzKataTests
{
[TestFixture]
public class FizzBuzzKataTests
{
[Test]
public void CanDivideByThree ()
{
int Number = 3;
bool Result = FizzBuzz.DivisibleByThree (Number);
Assert.IsTrue (Result, "Should return treu when it can divide by three");
int Number2 = 5;
bool Result2 = FizzBuzz.DivisibleByThree (Number2);
Assert.IsFalse (Result2, "Should return false when can't divide by three");
}
[Test]
public void PrintsFizz ()
{
using (StringWriter sw = new StringWriter ())
{
int Number = 4;
Console.SetOut (sw);
FizzBuzz.Evaluate (Number);
string output = sw.ToString().Replace("\n", " ").Trim ();
StringAssert.AreEqualIgnoringCase("1 2 Fizz 4", output);
}
}
[Test]
public void CanDivideByFive ()
{
int Number = 5;
bool Result = FizzBuzz.DivisibleByFive (Number);
Assert.IsTrue (Result, "Should return true when divisible by 5");
}
[Test]
public void PrintsFizzOrBuzz ()
{
using (StringWriter sw = new StringWriter ())
{
int Number = 6;
Console.SetOut (sw);
FizzBuzz.Evaluate (Number);
string output = sw.ToString().Replace("\n", " ").Trim ();
StringAssert.AreEqualIgnoringCase("1 2 Fizz 4 Buzz Fizz", output);
}
}
[Test]
public void PrintsFizzBuzz()
{
using (StringWriter sw = new StringWriter ())
{
int Number = 15;
Console.SetOut (sw);
FizzBuzz.Evaluate (Number);
string output = sw.ToString().Replace("\n", " ").Trim();
StringAssert.AreEqualIgnoringCase("1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz", output);
}
}
}
}
|
namespace TriodorArgeProject.Entities.EntityClasses
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class PersonnelCosts
{
public int ID { get; set; }
public int? CostID { get; set; }
public int? PersonnelID { get; set; }
public decimal? ActualManMonth { get; set; }
public decimal? PlannedManMonth { get; set; }
public decimal? AcceptedManMonth { get; set; }
public string Notes { get; set; }
public virtual Personnels Personnels { get; set; }
public virtual SuppProjectCosts SuppProjectCosts { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Application.Common.Dtos;
using Application.Common.Exceptions;
using Application.Common.Interface;
using Application.Common.Models;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Application.Categories.Queries {
public class GetCategoryDetailQuery : IRequest<CategoryDto> {
public Guid Id { get; set; }
}
public class GetCategoryDetailQueryHandler : BaseCommandHandler<GetCategoryDetailQueryHandler>, IRequestHandler<GetCategoryDetailQuery, CategoryDto> {
public GetCategoryDetailQueryHandler (IAppDbContext context, IMapper mapper, ILogger<GetCategoryDetailQueryHandler> logger) : base (context, mapper, logger) { }
public async Task<CategoryDto> Handle (GetCategoryDetailQuery request, CancellationToken cancellationToken) {
var entity = await Context.Categories.Where (x => x.IdCategory == request.Id).ProjectTo<CategoryDto> (Mapper.ConfigurationProvider).FirstOrDefaultAsync (cancellationToken);
if (entity == null) throw new NotFoundException ("Product", "Product not found");
return entity;
}
}
} |
// Copyright (C) 2017 Kazuhiro Fujieda <fujieda@users.osdn.me>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DynaJson;
using KancolleSniffer.Model;
using KancolleSniffer.Util;
namespace KancolleSniffer
{
public class BattleResultError : Exception
{
}
public class ErrorLog
{
private readonly Sniffer _sniffer;
private BattleState _prevBattleState = BattleState.None;
private readonly List<Main.Session> _battleApiLog = new List<Main.Session>();
public ErrorLog(Sniffer sniffer)
{
_sniffer = sniffer;
}
public void CheckBattleApi(Main.Session session)
{
if (_prevBattleState == BattleState.None)
_battleApiLog.Clear();
try
{
if (_sniffer.Battle.BattleState != BattleState.None)
{
_battleApiLog.Add(session);
}
else if (_prevBattleState == BattleState.Result &&
// battleresultのあとのship_deckかportでのみエラー判定する
_sniffer.IsBattleResultError)
{
throw new BattleResultError();
}
}
finally
{
_prevBattleState = _sniffer.Battle.BattleState;
}
}
public string GenerateBattleErrorLog()
{
foreach (var s in _battleApiLog)
Privacy.Remove(s);
var version = string.Join(".", Application.ProductVersion.Split('.').Take(2));
var api = CompressApi(string.Join("\r\n",
new[] {BattleStartSlots()}.Concat(_battleApiLog.SelectMany(s => s.Lines))));
var rank = _sniffer.Battle.DisplayedResultRank;
var status = string.Join("\r\n", new[]
{
rank.IsError ? $"{rank.Assumed}->{rank.Actual}" : "",
HpDiffLog()
}.Where(s => !string.IsNullOrEmpty(s)));
var result = $"{{{{{{\r\n{DateTime.Now:g} {version}\r\n{status}\r\n{api}\r\n}}}}}}";
File.WriteAllText("error.log", result);
return result;
}
private string BattleStartSlots()
{
return new JsonObject((from ship in _sniffer.BattleStartStatus
group ship by ship.Fleet
into fleet
select
(from s in fleet
select (from item in s.AllSlot select item.Spec.Id).ToArray()
).ToArray()
).ToArray()).ToString();
}
private string HpDiffLog() => string.Join(" ",
from pair in _sniffer.BattleResultStatusDiff
let assumed = pair.Assumed // こちらのFleetはnull
let actual = pair.Actual
select $"({actual.Fleet.Number}-{actual.DeckIndex}) {assumed.NowHp}->{actual.NowHp}");
public string GenerateErrorLog(Main.Session s, string exception)
{
Privacy.Remove(s);
var version = string.Join(".", Application.ProductVersion.Split('.').Take(2));
var api = CompressApi(string.Join("\r\n", s.Lines));
var result = $"{{{{{{\r\n{DateTime.Now:g} {version}\r\n{exception}\r\n{api}\r\n}}}}}}";
File.WriteAllText("error.log", result);
return result;
}
private string CompressApi(string api)
{
var output = new MemoryStream();
var gzip = new GZipStream(output, CompressionLevel.Optimal);
var bytes = Encoding.UTF8.GetBytes(api);
gzip.Write(bytes, 0, bytes.Length);
gzip.Close();
var ascii85 = Ascii85.Encode(output.ToArray());
var result = new List<string>();
var rest = ascii85.Length;
const int lineLength = 80;
for (var i = 0; i < ascii85.Length; i += lineLength, rest -= lineLength)
result.Add(ascii85.Substring(i, Math.Min(rest, lineLength)));
return string.Join("\r\n", result);
}
}
} |
namespace IntegradorZeusPDV.DB.DB.CriptografiaMD5
{
public class CriptografiaMD5
{
public static string CodificaSenha(string Chave, string Senha)
{
DemoEncryption Demo = new DemoEncryption(Chave);
return Demo.EncryptUsernamePassword(Senha);
}
public static string DecodificaSenha(string Chave, string Senha)
{
DemoEncryption Demo = new DemoEncryption(Chave);
return Demo.DecryptUsernamePassword(Senha);
}
}
}
|
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Quartz;
using System.Threading.Tasks;
using Whale.DAL.Models;
using Whale.Shared.Services;
namespace Whale.Shared.Jobs
{
public class ScheduledMeetingJob : IJob
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IMapper _mapper;
public ScheduledMeetingJob(IServiceScopeFactory serviceScopeFactory, IMapper mapper)
{
_serviceScopeFactory = serviceScopeFactory;
_mapper = mapper;
}
public async Task Execute(IJobExecutionContext context)
{
var dataMap = context.JobDetail.JobDataMap;
var meeting = JsonConvert.DeserializeObject<Meeting>(dataMap.GetString("JobData"));
using var scope = _serviceScopeFactory.CreateScope();
var meetingService = scope.ServiceProvider.GetService<MeetingService>();
await meetingService.StartScheduledMeetingAsync(meeting);
}
}
}
|
using Alword.Algoexpert.Tier0;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Alword.Algoexpert.Tests
{
public class ValidSubsquenceTest
{
[Fact]
public void ValidSequence()
{
var array = new List<int> { 5, 1, 22, 25, 6, -1, 8, 10 };
var sequence = new List<int> { 5, 1, 22, 23, 6, -1, 8, 10 };
Assert.False(ValidSubsequence.IsValidSubsequence(array, sequence));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GAPT.Models;
namespace GAPT.ViewModels
{
public class ViewRepliesViewModel
{
public IEnumerable<Comment> Replies { get; set; }
public Comment Comment { get; set; }
public int Pid { get; set; }
public bool Submitted { get; set; }
public bool HasApproval { get; set; }
public string Section { get; set; }
}
} |
// -----------------------------------------------------------------------
// <copyright file="StreamingMediaPlugin.cs" company="Henric Jungheim">
// Copyright (c) 2012-2014.
// <author>Henric Jungheim</author>
// </copyright>
// -----------------------------------------------------------------------
// Copyright (c) 2012-2014 Henric Jungheim <software@henric.org>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.SilverlightMediaFramework.Plugins;
using Microsoft.SilverlightMediaFramework.Plugins.Metadata;
using Microsoft.SilverlightMediaFramework.Plugins.Primitives;
using Microsoft.SilverlightMediaFramework.Utilities.Extensions;
using SM.Media.MediaParser;
using SM.Media.Utility;
using SM.Media.Web;
namespace SM.Media.MediaPlayer
{
/// <summary>
/// Represents a media plug-in that can play streaming media.
/// </summary>
[ExportMediaPlugin(PluginName = PluginName,
PluginDescription = PluginDescription,
PluginVersion = PluginVersion,
SupportedDeliveryMethods = SupportedDeliveryMethodsInternal,
SupportedMediaTypes = new[] { "application/vnd.apple.mpegurl" })]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class StreamingMediaPlugin : IMediaPlugin
{
const string PluginName = "StreamingMediaPlugin";
const string PluginDescription =
"Provides HTTP Live Streaming capabilities for the Silverlight Media Framework by wrapping the MediaElement.";
const string PluginVersion = "1.1.0.0";
const DeliveryMethods SupportedDeliveryMethodsInternal = DeliveryMethods.Streaming;
const double SupportedPlaybackRate = 1;
static readonly double[] SupportedRates = { SupportedPlaybackRate };
protected MediaElement MediaElement { get; set; }
Stream _streamSource;
HttpClients _httpClients;
readonly IApplicationInformation _applicationInformation = ApplicationInformationFactory.Default;
IMediaStreamFascade _mediaStreamFascade;
Dispatcher _dispatcher;
Uri _source;
#region Events
/// <summary>
/// Occurs when the plug-in is loaded.
/// </summary>
public event Action<IPlugin> PluginLoaded;
/// <summary>
/// Occurs when the plug-in is unloaded.
/// </summary>
public event Action<IPlugin> PluginUnloaded;
/// <summary>
/// Occurs when an exception occurs when the plug-in is loaded.
/// </summary>
public event Action<IPlugin, Exception> PluginLoadFailed;
/// <summary>
/// Occurs when an exception occurs when the plug-in is unloaded.
/// </summary>
public event Action<IPlugin, Exception> PluginUnloadFailed;
/// <summary>
/// Occurs when the log is ready.
/// </summary>
public event Action<IPlugin, LogEntry> LogReady;
//IMediaPlugin Events
/// <summary>
/// Occurs when a seek operation has completed.
/// </summary>
public event Action<IMediaPlugin> SeekCompleted;
/// <summary>
/// Occurs when the percent of the media being buffered changes.
/// </summary>
public event Action<IMediaPlugin, double> BufferingProgressChanged;
/// <summary>
/// Occurs when the percent of the media downloaded changes.
/// </summary>
public event Action<IMediaPlugin, double> DownloadProgressChanged;
/// <summary>
/// Occurs when a marker defined for the media file has been reached.
/// </summary>
public event Action<IMediaPlugin, MediaMarker> MarkerReached;
/// <summary>
/// Occurs when the media reaches the end.
/// </summary>
public event Action<IMediaPlugin> MediaEnded;
/// <summary>
/// Occurs when the media does not open successfully.
/// </summary>
public event Action<IMediaPlugin, Exception> MediaFailed;
/// <summary>
/// Occurs when the media successfully opens.
/// </summary>
public event Action<IMediaPlugin> MediaOpened;
/// <summary>
/// Occurs when the state of playback for the media changes.
/// </summary>
public event Action<IMediaPlugin, MediaPluginState> CurrentStateChanged;
#pragma warning disable 67
/// <summary>
/// Occurs when the user clicks on an ad.
/// </summary>
public event Action<IAdaptiveMediaPlugin, IAdContext> AdClickThrough;
/// <summary>
/// Occurs when there is an error playing an ad.
/// </summary>
public event Action<IAdaptiveMediaPlugin, IAdContext> AdError;
/// <summary>
/// Occurs when the progress of the currently playing ad has been updated.
/// </summary>
public event Action<IAdaptiveMediaPlugin, IAdContext, AdProgress> AdProgressUpdated;
/// <summary>
/// Occurs when the state of the currently playing ad has changed.
/// </summary>
public event Action<IAdaptiveMediaPlugin, IAdContext> AdStateChanged;
/// <summary>
/// Occurs when the media's playback rate changes.
/// </summary>
public event Action<IMediaPlugin> PlaybackRateChanged;
#pragma warning restore 67
#endregion
#region Properties
public CacheMode CacheMode
{
get { return MediaElement != null ? MediaElement.CacheMode : null; }
set { MediaElement.IfNotNull(i => i.CacheMode = value); }
}
/// <summary>
/// Gets a value indicating whether a plug-in is currently loaded.
/// </summary>
public bool IsLoaded { get; private set; }
/// <summary>
/// Gets or sets a value that indicates whether the media file starts to play immediately after it is opened.
/// </summary>
public bool AutoPlay
{
get { return MediaElement != null && MediaElement.AutoPlay; }
set { MediaElement.IfNotNull(i => i.AutoPlay = value); }
}
/// <summary>
/// Gets or sets the ratio of the volume level across stereo speakers.
/// </summary>
/// <remarks>
/// The value is in the range between -1 and 1. The default value of 0 signifies an equal volume between left and right
/// stereo speakers.
/// A value of -1 represents 100 percent volume in the speakers on the left, and a value of 1 represents 100 percent
/// volume in the speakers on the right.
/// </remarks>
public double Balance
{
get { return MediaElement != null ? MediaElement.Balance : default(double); }
set { MediaElement.IfNotNull(i => i.Balance = value); }
}
/// <summary>
/// Gets a value indicating if the current media item can be paused.
/// </summary>
public bool CanPause
{
get { return MediaElement != null && MediaElement.CanPause; }
}
/// <summary>
/// Gets a value indicating if the current media item allows seeking to a play position.
/// </summary>
public bool CanSeek
{
get { return MediaElement != null && MediaElement.CanSeek; }
}
/// <summary>
/// Gets the total time of the current media item.
/// </summary>
public TimeSpan Duration
{
get
{
return MediaElement != null && MediaElement.NaturalDuration.HasTimeSpan
? MediaElement.NaturalDuration.TimeSpan
: TimeSpan.Zero;
}
}
/// <summary>
/// Gets the end time of the current media item.
/// </summary>
public TimeSpan EndPosition
{
get { return Duration; }
}
/// <summary>
/// Gets or sets a value indicating if the current media item is muted so that no audio is playing.
/// </summary>
public bool IsMuted
{
get { return MediaElement != null && MediaElement.IsMuted; }
set { MediaElement.IfNotNull(i => i.IsMuted = value); }
}
/// <summary>
/// Gets or sets the LicenseAcquirer associated with the IMediaPlugin.
/// The LicenseAcquirer handles acquiring licenses for DRM encrypted content.
/// </summary>
public LicenseAcquirer LicenseAcquirer
{
get
{
return MediaElement != null
? MediaElement.LicenseAcquirer
: null;
}
set { MediaElement.IfNotNull(i => i.LicenseAcquirer = value); }
}
/// <summary>
/// Gets the size value (unscaled width and height) of the current media item.
/// </summary>
public Size NaturalVideoSize
{
get
{
return MediaElement != null
? new Size(MediaElement.NaturalVideoWidth, MediaElement.NaturalVideoHeight)
: Size.Empty;
}
}
/// <summary>
/// Gets the play speed of the current media item.
/// </summary>
/// <remarks>
/// A rate of 1.0 is normal speed.
/// </remarks>
public double PlaybackRate
{
get { return SupportedPlaybackRate; }
set
{
if (value != SupportedPlaybackRate)
throw new ArgumentOutOfRangeException("value");
}
}
/// <summary>
/// Gets the current state of the media item.
/// </summary>
public MediaPluginState CurrentState
{
get
{
return MediaElement != null
? ConvertToPlayState(MediaElement.CurrentState)
: MediaPluginState.Stopped;
}
}
/// <summary>
/// Gets the current position of the media item.
/// </summary>
public TimeSpan Position
{
get
{
return MediaElement != null
? MediaElement.Position
: TimeSpan.Zero;
}
set
{
if (MediaElement != null)
{
_mediaStreamFascade.SeekTarget = value;
MediaElement.Position = value;
SeekCompleted.IfNotNull(i => i(this));
}
}
}
/// <summary>
/// Gets whether this plugin supports ad scheduling.
/// </summary>
public bool SupportsAdScheduling
{
get { return false; }
}
/// <summary>
/// Gets the start position of the current media item (0).
/// </summary>
public TimeSpan StartPosition
{
get { return TimeSpan.Zero; }
}
/// <summary>
/// Gets the stretch setting for the current media item.
/// </summary>
public Stretch Stretch
{
get
{
return MediaElement != null
? MediaElement.Stretch
: default(Stretch);
}
set { MediaElement.IfNotNull(i => i.Stretch = value); }
}
/// <summary>
/// Gets or sets a Boolean value indicating whether to
/// enable GPU acceleration. In the case of the Progressive
/// MediaElement, the CacheMode being set to BitmapCache
/// is the equivalent of setting EnableGPUAcceleration = true
/// </summary>
public bool EnableGPUAcceleration
{
get { return MediaElement != null && MediaElement.CacheMode is BitmapCache; }
set
{
if (value)
MediaElement.IfNotNull(i => i.CacheMode = new BitmapCache());
else
MediaElement.IfNotNull(i => i.CacheMode = null);
}
}
/// <summary>
/// Gets the delivery methods supported by this plugin.
/// </summary>
public DeliveryMethods SupportedDeliveryMethods
{
get { return SupportedDeliveryMethodsInternal; }
}
/// <summary>
/// Gets a collection of the playback rates for the current media item.
/// </summary>
public IEnumerable<double> SupportedPlaybackRates
{
get { return SupportedRates; }
}
/// <summary>
/// Gets a reference to the media player control.
/// </summary>
public FrameworkElement VisualElement
{
get { return MediaElement; }
}
/// <summary>
/// Gets or sets the initial volume setting as a value between 0 and 1.
/// </summary>
public double Volume
{
get
{
return MediaElement != null
? MediaElement.Volume
: 0;
}
set { MediaElement.IfNotNull(i => i.Volume = value); }
}
/// <summary>
/// Gets the dropped frames per second.
/// </summary>
public double DroppedFramesPerSecond
{
get
{
return MediaElement != null
? MediaElement.DroppedFramesPerSecond
: 0;
}
}
/// <summary>
/// Gets the rendered frames per second.
/// </summary>
public double RenderedFramesPerSecond
{
get
{
return MediaElement != null
? MediaElement.RenderedFramesPerSecond
: 0;
}
}
/// <summary>
/// Gets the percentage of the current buffering that is completed.
/// </summary>
public double BufferingProgress
{
get
{
return MediaElement != null
? MediaElement.BufferingProgress
: default(double);
}
}
/// <summary>
/// Gets or sets the amount of time for the current buffering action.
/// </summary>
public TimeSpan BufferingTime
{
get
{
return MediaElement != null
? MediaElement.BufferingTime
: TimeSpan.Zero;
}
set { MediaElement.IfNotNull(i => i.BufferingTime = value); }
}
/// <summary>
/// Gets the percentage of the current buffering that is completed
/// </summary>
public double DownloadProgress
{
get { return MediaElement.DownloadProgress; }
}
/// <summary>
/// Gets the download progress offset
/// </summary>
public double DownloadProgressOffset
{
get { return MediaElement.DownloadProgressOffset; }
}
/// <summary>
/// Gets or sets the location of the media file.
/// </summary>
public Uri Source
{
get { return _source; }
set
{
Debug.WriteLine("StreamingMediaPlugin.Source setter: " + value);
_source = value;
if (null == _mediaStreamFascade)
return;
_mediaStreamFascade.Source = _source;
_mediaStreamFascade.Play();
}
}
public Stream StreamSource
{
get { return _streamSource; }
set
{
Debug.WriteLine("StreamingMediaPlugin.StreamSource setter");
if (MediaElement != null)
{
MediaElement.SetSource(value);
_streamSource = value;
}
}
}
#endregion
/// <summary>
/// Starts playing the current media file from its current position.
/// </summary>
public void Play()
{
Debug.WriteLine("StreamingMediaPlugin.Play()");
StartPlayback();
}
/// <summary>
/// Pauses the currently playing media.
/// </summary>
public void Pause()
{
Debug.WriteLine("StreamingMediaPlugin.Pause()");
MediaElement.IfNotNull(i => i.Pause());
}
/// <summary>
/// Stops playing the current media.
/// </summary>
public void Stop()
{
Debug.WriteLine("StreamingMediaPlugin.Stop()");
MediaElement.IfNotNull(i => i.Stop());
}
/// <summary>
/// Loads a plug-in for playing streaming media.
/// </summary>
public void Load()
{
try
{
if (null != _httpClients)
_httpClients.Dispose();
_httpClients = new HttpClients(userAgent: _applicationInformation.CreateUserAgent());
InitializeStreamingMediaElement();
IsLoaded = true;
PluginLoaded.IfNotNull(i => i(this));
//SendLogEntry(KnownLogEntryTypes.ProgressiveMediaPluginLoaded, message: ProgressiveMediaPluginResources.ProgressiveMediaPluginLoadedLogMessage);
_dispatcher = MediaElement.Dispatcher;
_mediaStreamFascade = MediaStreamFascadeSettings.Parameters.Create(_httpClients, SetSourceAsync);
}
catch (Exception ex)
{
PluginLoadFailed.IfNotNull(i => i(this, ex));
}
}
/// <summary>
/// Unloads a plug-in for streaming media.
/// </summary>
public void Unload()
{
try
{
IsLoaded = false;
if (null != _mediaStreamFascade)
{
_mediaStreamFascade.DisposeSafe();
_mediaStreamFascade = null;
}
if (null != _httpClients)
{
_httpClients.Dispose();
_httpClients = null;
}
DestroyStreamingMediaElement();
PluginUnloaded.IfNotNull(i => i(this));
//SendLogEntry(KnownLogEntryTypes.ProgressiveMediaPluginUnloaded, message: ProgressiveMediaPluginResources.ProgressiveMediaPluginUnloadedLogMessage);
}
catch (Exception ex)
{
PluginUnloadFailed.IfNotNull(i => i(this, ex));
}
}
/// <summary>
/// Requests that this plugin generate a LogEntry via the LogReady event
/// </summary>
public void RequestLog()
{
MediaElement.IfNotNull(i => i.RequestLog());
}
/// <summary>
/// Schedules an ad to be played by this plugin.
/// </summary>
/// <param name="adSource">The source of the ad content.</param>
/// <param name="deliveryMethod">The delivery method of the ad content.</param>
/// <param name="duration">
/// The duration of the ad content that should be played. If omitted the plugin will play the full
/// duration of the ad content.
/// </param>
/// <param name="startTime">
/// The position within the media where this ad should be played. If omitted ad will begin playing
/// immediately.
/// </param>
/// <param name="clickThrough">The URL where the user should be directed when they click the ad.</param>
/// <param name="pauseTimeline">
/// Indicates if the timeline of the currently playing media should be paused while the ad is
/// playing.
/// </param>
/// <param name="appendToAd">
/// Another scheduled ad that this ad should be appended to. If omitted this ad will be scheduled
/// independently.
/// </param>
/// <param name="data">User data.</param>
/// <returns>A reference to the IAdContext that contains information about the scheduled ad.</returns>
public IAdContext ScheduleAd(Uri adSource, DeliveryMethods deliveryMethod, TimeSpan? duration = null,
TimeSpan? startTime = null, TimeSpan? startOffset = null, Uri clickThrough = null, bool pauseTimeline = true,
IAdContext appendToAd = null, object data = null, bool isLinearClip = false)
{
throw new NotImplementedException();
}
void InitializeStreamingMediaElement()
{
if (MediaElement == null)
{
MediaElement = new MediaElement();
MediaElement.MediaOpened += MediaElement_MediaOpened;
MediaElement.MediaFailed += MediaElement_MediaFailed;
MediaElement.MediaEnded += MediaElement_MediaEnded;
MediaElement.CurrentStateChanged += MediaElement_CurrentStateChanged;
MediaElement.BufferingProgressChanged += MediaElement_BufferingProgressChanged;
MediaElement.DownloadProgressChanged += MediaElement_DownloadProgressChanged;
MediaElement.LogReady += MediaElement_LogReady;
}
}
void DestroyStreamingMediaElement()
{
if (MediaElement != null)
{
MediaElement.MediaOpened -= MediaElement_MediaOpened;
MediaElement.MediaFailed -= MediaElement_MediaFailed;
MediaElement.MediaEnded -= MediaElement_MediaEnded;
MediaElement.CurrentStateChanged -= MediaElement_CurrentStateChanged;
MediaElement.BufferingProgressChanged -= MediaElement_BufferingProgressChanged;
MediaElement.DownloadProgressChanged -= MediaElement_DownloadProgressChanged;
MediaElement.LogReady -= MediaElement_LogReady;
MediaElement.Source = null;
MediaElement = null;
}
}
void MediaElement_DownloadProgressChanged(object sender, RoutedEventArgs e)
{
DownloadProgressChanged.IfNotNull(i => i(this, MediaElement.DownloadProgress));
}
void MediaElement_BufferingProgressChanged(object sender, RoutedEventArgs e)
{
BufferingProgressChanged.IfNotNull(i => i(this, MediaElement.BufferingProgress));
}
void MediaElement_MarkerReached(object sender, TimelineMarkerRoutedEventArgs e)
{
//var logMessage = string.Format(ProgressiveMediaPluginResources.TimelineMarkerReached, e.Marker.Time,
// e.Marker.Type, e.Marker.Text);
//SendLogEntry(KnownLogEntryTypes.MediaElementMarkerReached, message: logMessage);
var mediaMarker = new MediaMarker
{
Type = e.Marker.Type,
Begin = e.Marker.Time,
End = e.Marker.Time,
Content = e.Marker.Text
};
NotifyMarkerReached(mediaMarker);
}
void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
{
var playState = ConvertToPlayState(MediaElement.CurrentState);
CurrentStateChanged.IfNotNull(i => i(this, playState));
}
void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
{
MediaEnded.IfNotNull(i => i(this));
CleanupMedia();
}
void MediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
MediaFailed.IfNotNull(i => i(this, e.ErrorException));
CleanupMedia();
}
void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
MediaOpened.IfNotNull(i => i(this));
}
void MediaElement_LogReady(object sender, LogReadyRoutedEventArgs e)
{
//var message = string.Format(ProgressiveMediaPluginResources.MediaElementGeneratedLogMessageFormat,
// e.LogSource);
//var extendedProperties = new Dictionary<string, object> { { "Log", e.Log } };
//SendLogEntry(KnownLogEntryTypes.MediaElementLogReady, LogLevel.Statistics, message, extendedProperties: extendedProperties);
}
void NotifyMarkerReached(MediaMarker mediaMarker)
{
MarkerReached.IfNotNull(i => i(this, mediaMarker));
}
void SendLogEntry(string type, LogLevel severity = LogLevel.Information,
string message = null,
DateTime? timeStamp = null,
IEnumerable<KeyValuePair<string, object>> extendedProperties = null)
{
if (LogReady != null)
{
var logEntry = new LogEntry
{
Type = type,
Severity = severity,
Message = message,
SenderName = PluginName,
Timestamp = timeStamp.HasValue ? timeStamp.Value : DateTime.Now
};
extendedProperties.ForEach(logEntry.ExtendedProperties.Add);
LogReady(this, logEntry);
}
}
static MediaPluginState ConvertToPlayState(MediaElementState mediaElementState)
{
return (MediaPluginState)Enum.Parse(typeof(MediaPluginState), mediaElementState.ToString(), true);
}
void CleanupMedia()
{
Debug.WriteLine("StreamingMediaPlugin.CleanupMedia()");
Close();
}
public void Close()
{
Debug.WriteLine("StreamingMediaPlugin.Close()");
Debug.Assert(_dispatcher.CheckAccess());
MediaElement.Source = null;
_mediaStreamFascade.RequestStop();
}
Task SetSourceAsync(IMediaStreamSource mediaStreamSource)
{
Debug.WriteLine("StreamingMediaPlugin.SetSourceAsync()");
var mss = (MediaStreamSource)mediaStreamSource;
return _dispatcher.InvokeAsync(() =>
{
if (null == MediaElement)
return;
MediaElement.SetSource(mss);
});
}
void StartPlayback()
{
Debug.WriteLine("StreamingMediaPlugin.StartPlayback()");
if (null == MediaElement)
return;
if (null == _mediaStreamFascade)
return;
if (MediaElementState.Closed != MediaElement.CurrentState)
{
if (new[] { MediaElementState.Paused, MediaElementState.Stopped }.Contains(MediaElement.CurrentState))
{
MediaElement.Play();
return;
}
}
_mediaStreamFascade.Source = _source;
_mediaStreamFascade.Play();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsFormsApp2;
namespace WindowsFormsApp2
{
public class Distribution
{
private static long Choose(int n, int r)
{
long top = Factorial(n);
long bot = Factorial(r) * Factorial(n - r);
return top / bot;
}
private static long Factorial(int n)
{
long result = 1;
for (long i = 2; i <= n; i++)
{
result *= i;
}
return result;
}
private int trials { get; set; }
public double probabilty { get; set; }
public Distribution(double prob, int trials)
{
this.trials = trials;
this.probabilty = prob;
}
public double exact(int X)
{
return Choose(trials, X) * Math.Pow(probabilty, X) * Math.Pow(1 - probabilty, trials - X);
}
public double atleast(int X)
{
double result = 0;
for(int i = X; i < trials; i++)
{
result = result + exact(i);
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Controller
{
public static class ThreadPool
{
private static List<Task> AllThreads = new List<Task>();
public static void AddTask(Task task)
{
AllThreads.Add(task);
}
public static void WaitCompletion()
{
Task[] tasks = AllThreads.ToArray();
Task.WaitAll(tasks);
AllThreads.Clear();
}
}
}
|
using System;
namespace IMDB.Api.Repositories.Interfaces
{
public interface IPlotKeywordRepository : IGenericRepository<Entities.PlotKeyword>
{
}
}
|
using System;
using System.Runtime.CompilerServices;
namespace UnityEngine
{
public sealed partial class Time
{
// Overwritten property
public static float deltaTime
{
get
{
return 0.0166666675f;
}
}
}
}
|
using System;
using System.Collections.Generic;
#nullable disable
namespace Repository.Models
{
/// <summary>
/// Repo Model from database-first scaffolding
/// </summary>
public partial class Setting
{
public string Setting1 { get; set; }
public int? IntValue { get; set; }
public string StringValue { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class EnemyState : MonoBehaviour {
public CurrentState nmeCurrentState;
public enum CurrentState
{
Stationary = 0,
Patroling = 1,
Chasing = 2,
Firing = 3,
Turning = 4,
Padding = 5,
Searching = 6
}
public bool justLostEm;
private bool inTrigger;
private EnemySight scriptSight;
private EnemyMovement scriptMovement;
// Use this for initialization
void Start ()
{
nmeCurrentState = CurrentState.Stationary;
scriptSight = transform.parent.GetComponentInChildren<EnemySight>();
scriptMovement = transform.parent.GetComponent<EnemyMovement>();
}
// Update is called once per frame
void Update ()
{
if (scriptSight.playerInSight)
{
justLostEm = false; // If we can see the player, we don't need to search anymore.
if (inTrigger)
{
if (scriptSight.JustFOVAngle())
{
nmeCurrentState = CurrentState.Firing;
}
else
{
nmeCurrentState = CurrentState.Turning;
}
}
else
{
nmeCurrentState = CurrentState.Chasing;
}
}
else if (scriptSight.playerHasTouched)
{
nmeCurrentState = CurrentState.Turning;
}
else if (justLostEm)
{
nmeCurrentState = CurrentState.Searching;
}
else if (scriptMovement.listTransPatrol.Count > 1)
{
nmeCurrentState = CurrentState.Patroling;
}
else if (scriptMovement.listTransPatrol.Count == 1)
{
nmeCurrentState = CurrentState.Padding;
}
else
{
nmeCurrentState = CurrentState.Stationary;
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "Character")
{
inTrigger = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.name == "Character")
{
inTrigger = false;
}
}
}
|
using System;
using Microsoft.Extensions.Configuration;
namespace RipplerES.CommandHandler.Utilities
{
public static class ConfigurationExtensions
{
private static int ParseInt(string literal, int defaultValue)
{
int result;
return int.TryParse(literal, out result)
? result
: defaultValue;
}
private static bool ParseBool(string literal, bool defaultValue)
{
bool result;
return bool.TryParse(literal, out result)
? result
: defaultValue;
}
private static string ParseString(string literal, string defaultValue)
{
return string.IsNullOrWhiteSpace(literal)
? defaultValue
: literal;
}
private static TResult GetAggregateSetting<TResult>(IConfiguration configurationRoot,
string section,
string settingKey,
TResult defaultValue,
Func<string, TResult, TResult> parser)
{
var setting = configurationRoot.GetSection(section)[settingKey];
return string.IsNullOrWhiteSpace(setting)
? defaultValue
: parser(setting, defaultValue);
}
public static int GetInt(this IConfiguration config,
string section,
string setting,
int defaultValue)
{
return GetAggregateSetting(config, section, setting, defaultValue, ParseInt);
}
public static bool GetBool(this IConfiguration config,
string section,
string setting,
bool defaultValue)
{
return GetAggregateSetting(config, section, setting, defaultValue, ParseBool);
}
public static string GetString(this IConfiguration config,
string section,
string setting,
string defaultValue)
{
return GetAggregateSetting(config, section, setting, defaultValue, ParseString);
}
}
} |
using PhotoFrame.Domain.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace PhotoFrame.Persistence.Csv
{
/// <summary>
/// <see cref="IKeywordRepository">の実装クラス
/// </summary>
class KeywordRepository : IKeywordRepository
{
/// <summary>
/// 永続化ストアとして利用するCSVファイルパス
/// </summary>
private string CsvFilePath { get; }
public KeywordRepository(string databaseName)
{
this.CsvFilePath = $"{databaseName}_Keyword.csv"; // $"{...}" : 文字列展開
if (!System.IO.File.Exists(CsvFilePath))
{
using (System.IO.File.CreateText(CsvFilePath)) { }
}
}
public IEnumerable<Keyword> Find(Func<IQueryable<Keyword>, IQueryable<Keyword>> query)
=> query(FindAll().AsQueryable()).ToList();
public Keyword Find(Func<IQueryable<Keyword>, Keyword> query)
=> query(FindAll().AsQueryable());
public Keyword FindBy(string id)
{
using (var reader = new StreamReader(CsvFilePath, Encoding.UTF8))
{
while (reader.Peek() >= 0)
{
var row = reader.ReadLine();
var entity = Deserialize(row);
if (entity.Id == id)
{
return entity;
}
}
}
return null;
}
public bool Exists(Keyword entity) => ExistsBy(entity.Id);
public bool ExistsBy(string id) => FindBy(id) != null;
public Keyword Store(Keyword entity)
{
var serialized = Serialize(entity);
var updated = false;
var tmpFile = Path.GetTempFileName();
using (var reader = new StreamReader(CsvFilePath, Encoding.UTF8))
using (var writer = new StreamWriter(tmpFile, false, Encoding.UTF8))
{
while (reader.Peek() >= 0)
{
var row = reader.ReadLine();
var deserialized = Deserialize(row);
if (deserialized.Id == entity.Id)
{
// 更新
updated = true;
writer.WriteLine(serialized);
continue;
}
else
{
writer.WriteLine(row);
}
}
if (!updated)
{
// 追加
writer.WriteLine(serialized);
}
}
System.IO.File.Copy(tmpFile, CsvFilePath, true);
System.IO.File.Delete(tmpFile);
return entity;
}
// Keyword型のデータをCSVの1行に変換する
private string Serialize(Keyword keyword)
=> $"{keyword.Id},{keyword.Name}";
// CSVの1行をKeyword型のデータに変換する
private Keyword Deserialize(string csvRow)
{
var split = csvRow.Split(',');
return new Keyword(split[0], split[1]);
}
// CSVの行データをすべて取得する
private IEnumerable<Keyword> FindAll()
{
var result = new List<Keyword>();
using (var reader = new StreamReader(CsvFilePath, Encoding.UTF8))
{
while (reader.Peek() >= 0)
{
var row = reader.ReadLine();
var entity = Deserialize(row);
result.Add(entity);
}
}
return result;
}
}
}
|
using Ninject;
using Prj.BusinessLogic.MapperConfig;
using Prj.BusinessLogic.ModuleConfig;
using Prj.Web.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Prj.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AutoMapperConfig.ConfigureMapper();
IKernel kernel = new StandardKernel(new ServicesModule());
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
|
using JAGA.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace JAGA.Mapping
{
public static class SongMapper
{
public static Song MapToModel(this song dbResult)
{
if (dbResult == null) return null;
return new Song()
{
Artist = dbResult.artist,
Difficulty = dbResult.difficulty.GetValueOrDefault(),
Id = dbResult.id,
Tabs = dbResult.tabs,
Title = dbResult.title
};
}
public static List<Song> MapToModels(this IEnumerable<song> dbResult)
{
List<Song> list = new List<Song>();
if (dbResult == null) return null;
foreach (var item in dbResult)
{
list.Add(item.MapToModel());
}
return list;
}
public static song MapToResult(this Song model)
{
if (model == null) return null;
return new song()
{
artist = model.Artist,
difficulty = model.Difficulty,
id = model.Id,
tabs = model.Tabs,
title = model.Title,
};
}
}
} |
namespace GetLabourManager.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Employee_Contribution_Relation : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.EmployeeContributions",
c => new
{
Id = c.Int(nullable: false, identity: true),
StaffId = c.Int(nullable: false),
SSF = c.Boolean(nullable: false),
Welfare = c.Boolean(nullable: false),
UnionDues = c.Boolean(nullable: false),
}).Index(x=>x.StaffId)
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.EmployeeRelations",
c => new
{
Id = c.Int(nullable: false, identity: true),
StaffId = c.Int(nullable: false),
GuarantorName = c.String(nullable: false, maxLength: 80),
GuarantorPhone = c.String(nullable: false, maxLength: 18),
GuarantorRelation = c.String(maxLength: 20),
GuarantorAddress = c.String(nullable: false, maxLength: 70),
NextofKinName = c.String(nullable: false, maxLength: 80),
NextofKinPhone = c.String(nullable: false, maxLength: 18),
NextofKinRelation = c.String(maxLength: 20),
NextofKinAddress = c.String(nullable: false, maxLength: 70),
}).Index(x => x.StaffId)
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.EmployeeRelations");
DropTable("dbo.EmployeeContributions");
}
}
}
|
using System;
using GithubRepository.Accessors;
using GithubRepository.Contracts;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Threading.Tasks;
using Language = GithubRepository.Contracts.Language;
using Repository = GithubRepository.Contracts.Repository;
namespace GithubRepository.Managers
{
/// <summary>
/// Class RepositoryManager.
/// </summary>
/// <seealso cref="GithubRepository.Managers.IRepositoryManager" />
public class RepositoryManager : IRepositoryManager
{
/// <summary>
/// The accessor
/// </summary>
private readonly IRepositoryAccessor _accessor;
/// <summary>
/// The settings
/// </summary>
private readonly RepositoryAppSettings _settings;
/// <summary>
/// Initializes a new instance of the <see cref="RepositoryManager"/> class.
/// </summary>
/// <param name="accessor">The accessor.</param>
/// <param name="settings">The settings.</param>
public RepositoryManager(IRepositoryAccessor accessor, IOptions<RepositoryAppSettings> settings)
{
_accessor = accessor;
_settings = settings.Value;
}
/// <summary>
/// Gets the repositories.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="language">The language.</param>
/// <returns>Task<IEnumerable<Repository>>.</returns>
public async Task<IEnumerable<Repository>> GetRepositories(string name, Octokit.Language? language)
{
var searchCriteria = new SearchCriteria
{
Name = !string.IsNullOrEmpty(name) ? name : null,
Language = language
};
//If now criteria was provided limits search result for items created no more than one year ago
//to improve performance. TODO: Implement paging
if (string.IsNullOrEmpty(name) && language == null)
searchCriteria.GreaterThan = DateTime.UtcNow.AddYears(_settings.GreaterThan);
//Limits items per page to improve performance. TODO: Implement paging
return await _accessor.GetRepositories(searchCriteria, 1, _settings.ItemsPerPage);
}
/// <summary>
/// Gets the languages.
/// </summary>
/// <returns>Task<IEnumerable<Contracts.Language>>.</returns>
public async Task<IEnumerable<Language>> GetLanguages()
{
return await _accessor.GetLanguages();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MMSdb.dbo.Tables
{
[Table("tbl_DDSA")]
public class tbl_DDSA
{
[Key]
public long ddsa_ID { get; set; }
public long dmg_ID { get; set; }
public String? ddsa_AdjudicatorName { get; set; }
public String? ddsa_AdjudicatorPhone { get; set; }
public String? ddsa_AdjudicatorPhoneExt { get; set; }
public String? ddsa_Address { get; set; }
public Boolean? ddsa_WorkHistory { get; set; }
public DateTime? ddsa_WorkHistoryDate { get; set; }
public Boolean? ddsa_ADL { get; set; }
public DateTime? ddsa_ADLDate { get; set; }
public Boolean? ddsa_ThirdPartyADL { get; set; }
public DateTime? ddsa_ThirdPartyADLDate { get; set; }
public Boolean? ddsa_ContactList { get; set; }
public DateTime? ddsa_ContactListDate { get; set; }
public Boolean? ddsa_Physician { get; set; }
public DateTime? ddsa_PhysicianDate { get; set; }
public Boolean? ddsa_PainQuestionaire { get; set; }
public DateTime? ddsa_PainQuestionaireDate { get; set; }
public Boolean? ddsa_Anxiety { get; set; }
public DateTime? ddsa_AnxietyDate { get; set; }
public Boolean? ddsa_PanicAttack { get; set; }
public DateTime? ddsa_PanicAttackDate { get; set; }
public Boolean? ddsa_Cardiac { get; set; }
public DateTime? ddsa_CardiacDate { get; set; }
public Boolean? ddsa_Neuropathy { get; set; }
public DateTime? ddsa_NeuropathyDate { get; set; }
public Boolean? ddsa_NeuropathyRpt { get; set; }
public DateTime? ddsa_NeuropathyRptDate { get; set; }
public Boolean? ddsa_IQ { get; set; }
public DateTime? ddsa_IQDate { get; set; }
public Boolean? ddsa_Eye { get; set; }
public DateTime? ddsa_EyeDate { get; set; }
public Boolean? ddsa_Teacher { get; set; }
public DateTime? ddsa_TeacherDate { get; set; }
public Boolean? ddsa_SSA3820 { get; set; }
public DateTime? ddsa_SSA3820Date { get; set; }
public Boolean? ddsa_ReportCard { get; set; }
public DateTime? ddsa_ReportCardDate { get; set; }
public Boolean? ddsa_SchoolWorksheet { get; set; }
public DateTime? ddsa_SchoolWorksheetDate { get; set; }
public Boolean? ddsa_Counselor { get; set; }
public DateTime? ddsa_CounselorDate { get; set; }
public String? ddsa_MedRecSentFrom { get; set; }
public DateTime? ddsa_MedRecDate { get; set; }
public DateTime? ddsa_OnsetDate { get; set; }
public DateTime? ddsa_ApprovalDate { get; set; }
public String? ddsa_Notes { get; set; }
public DateTime? ddsa_ReleaseFormDueDate { get; set; }
public DateTime? ddsa_SeizureRptDate { get; set; }
public Boolean? ddsa_SeizureRpt { get; set; }
public Boolean? ddsa_HeadacheRpt { get; set; }
public DateTime? ddsa_HeadacheRptDate { get; set; }
public Boolean? ddsa_MSRFCRpt { get; set; }
public DateTime? ddsa_MSRFCRptDate { get; set; }
public Boolean? deleted { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Task 3
namespace CorrectPlacedBrackets
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter an expression: ");
string expression = Console.ReadLine();
int bracketsCound = IsBracketsCorrect(expression);
if (bracketsCound == 0)
{
Console.WriteLine("The brackets are correctly placed!");
}
else
{
Console.WriteLine("The brackets are incorrectly placed!");
}
}
static int IsBracketsCorrect(string expression)
{
int bracketsCount = 0;
foreach (char symbol in expression)
{
if (symbol == '(')
{
bracketsCount++;
}
else if (symbol == ')')
{
bracketsCount--;
}
}
return bracketsCount;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightTutorial : TutorialSection
{
protected override void TaskNeedsVerification()
{
switch (activeTask.eventIndex)
{
case 0:
base.NextTask();
break;
case 1:
base.NextTask();
break;
case 2:
//check on and off time
base.NextTask();
break;
}
}
}
|
using JT7SKU.Lib.Twitch;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Concurrency;
using Orleans.Core;
using Orleans.Runtime;
using Services.Kirjasto.Unit.Twitch.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace Services.Kirjasto.Unit.Twitch.Grains
{
// Service alert channel what broadcast
[Reentrant]
public class TwitchToastService : GrainService, ITwitchToastService , IDisposable
{
readonly IGrainFactory GrainFactory;
private SubscriberGrain subscriberGrain;
private FollowerGrain followerGrain;
private TipperGrain tipperGrain;
private CheererGrain cheererGrain;
private Timer Countdown;
public event Action OnHide;
public event Action<string, ToastLevel> OnShow;
public TwitchToastService(IServiceProvider services, IGrainIdentity id, Silo silo, ILoggerFactory LoggerFactory, IGrainFactory grainFactory) : base(id, silo, LoggerFactory) => GrainFactory = grainFactory;
public override Task Init(IServiceProvider serviceProvider)
{
return base.Init(serviceProvider);
}
public override Task Stop()
{
return base.Stop();
}
public override Task Start()
{
return base.Start();
}
public async Task NewToast(User user,ToastLevel toastLevel,Message message)
{
switch (toastLevel)
{
case ToastLevel.NewCheer:
await cheererGrain.NewCheer(message);
break;
case ToastLevel.NewFollower:
await followerGrain.NewFollower(user,message);
break;
case ToastLevel.NewSubscriber:
await subscriberGrain.NewSubscriber(user, message);
break;
case ToastLevel.NewTip:
await tipperGrain.NewTip(message);
break;
}
}
public void Dispose()
{
Countdown?.Dispose();
}
public void ShowToast(string message, ToastLevel level)
{
OnShow?.Invoke(message, level);
StartCountdown();
}
private void StartCountdown()
{
SetCowndown();
if (Countdown.Enabled)
{
Countdown.Stop();
Countdown.Start();
}
else
{
Countdown.Start();
}
}
private void HideToast(object source, ElapsedEventArgs args)
{
OnHide?.Invoke();
}
private void SetCowndown()
{
if (Countdown == null)
{
Countdown = new Timer(5000);
Countdown.Elapsed += HideToast;
Countdown.AutoReset = false;
}
}
}
}
|
using UDM;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Moq;
using System.Collections;
using System.Collections.Generic;
namespace TestUDM
{
/// <summary>
///This is a test class for FilterCommandTest and is intended
///to contain all FilterCommandTest Unit Tests
///</summary>
[TestClass()]
public class FilterCommandTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for Execute
///</summary>
[TestMethod()]
public void ExecuteTest()
{
var table = new Mock<Table>();
var table2 = new Mock<Table>();
var cell1 = new Mock<Cell>();
var cell2 = new Mock<Cell>();
cell1.Setup(foo => foo.Content).Returns(1.0);
cell2.Setup(foo => foo.Content).Returns(5.0);
var cell3 = new Mock<Cell>();
var cell4 = new Mock<Cell>();
//var cell5 = new Mock<Cell>();
//var cell6 = new Mock<Cell>();
//var cell7 = new Mock<Cell>();
//var cell8 = new Mock<Cell>();
List<Cell> list1 = new List<Cell>();
List<Cell> list2 = new List<Cell>();
List<Cell> list3 = new List<Cell>();
List<Cell> list4 = new List<Cell>();
list1.Add(cell1.Object);
list1.Add(cell2.Object);
list2.Add(cell3.Object);
list2.Add(cell4.Object);
list3.Add(cell2.Object);
list4.Add(cell4.Object);
var column1 = new Mock<Column>();
var column2 = new Mock<Column>();
var column3 = new Mock<Column>();
var column4 = new Mock<Column>();
column1.Setup(foo => foo.Cells).Returns(list1);
column2.Setup(foo => foo.Cells).Returns(list2);
column3.Setup(foo => foo.Cells).Returns(list3);
column4.Setup(foo => foo.Cells).Returns(list4);
List<Column> columns1 = new List<Column>();
List<Column> columns2 = new List<Column>();
columns1.Add(column1.Object);
columns1.Add(column2.Object);
columns2.Add(column3.Object);
columns2.Add(column4.Object);
//tabela do filtrowania
table.Setup(foo => foo.Columns).Returns(columns1);
table2.Setup(foo => foo.Columns).Returns(columns2);
FilterCommand.Del del = c => (double)c > 2.0;
Command cmd = new FilterCommand(column1.Object, del);
var result = cmd.Execute(table.Object);
int n = table2.Object.Columns.Count;
int m = result.Columns.Count;
Assert.AreEqual(n, m);
for (int i = 0; i < n; i++)
{
CollectionAssert.AreEqual(table2.Object.Columns[i].Cells, result.Columns[i].Cells);
}
}
}
}
|
using System;
public class Program
{
public static void Main()
{
var charName = Console.ReadLine();
var charCurrHealth = int.Parse(Console.ReadLine());
var charMaxHealth = int.Parse(Console.ReadLine());
var charCurrEnergy = int.Parse(Console.ReadLine());
var charMaxEnergy = int.Parse(Console.ReadLine());
Console.WriteLine($"Name: {charName}");
PrintCurrentStats(charCurrHealth, charMaxHealth, "Health");
PrintCurrentStats(charCurrEnergy, charMaxEnergy, "Energy");
}
public static void PrintCurrentStats(int currentStat, int maxStat, string currStatType)
{
Console.Write($"{currStatType}: |");
for (int i = 1, j = 0; i <= maxStat; i++)
{
if (j < currentStat)
{
j++;
}
if (i == j)
{
Console.Write("|");
}
else
{
Console.Write(".");
}
}
Console.WriteLine("|");
}
} |
using System;
namespace CloudFile
{
public class CloudFileLoader
{
protected E_LoaderState m_myState;
protected LoaderError m_error;
private float m_progress;
protected int m_idForRequestObject;
protected float Progress
{
get
{
if (this.m_progress < 0f)
{
return 0f;
}
if (this.m_progress > 1f)
{
return 1f;
}
return this.m_progress;
}
set
{
this.m_progress = value;
}
}
public virtual int TaskRecordID
{
get
{
return 0;
}
}
public CloudFileLoader()
{
this.m_myState = E_LoaderState.Idle;
this.m_error = new LoaderError();
this.m_progress = 0f;
this.m_idForRequestObject = 1;
}
public virtual void Start()
{
}
public virtual void Stop()
{
}
public virtual void Pause()
{
}
public virtual void Restart()
{
this.m_idForRequestObject++;
}
public virtual void Close()
{
this.Stop();
}
public virtual void Reset()
{
this.Stop();
this.m_error.Reset();
}
protected virtual void ReportProgress()
{
}
protected virtual void ReportError()
{
}
protected virtual void ReportTimeout()
{
}
protected virtual void ImDone()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace EBV
{
public partial class Login : System.Web.UI.Page
{
BLL.BLL objbll = new BLL.BLL();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string User = Request.Form["email"];
string Pass = Request.Form["password"];
if (objbll.Adminlogin(User, Pass))
{
if (User.Split('@')[0] == "Admin")
Response.Redirect("AdminMail.aspx");
else
Response.Redirect("HospitalHome.aspx");
}
else if (objbll.companyLogin(User, Pass))
{
Session["company"] = User.Split('@')[0];
string cname = Convert.ToString(Session["company"]);
DataTable c = objbll.getCname(cname);
DataRow row = c.Rows[0];
Session["cid"] = Int32.Parse(row["CmpnyId"].ToString());
Response.Redirect("CompanyDetails.aspx");
}
else if (objbll.employeeLogin(User, Pass))
{
Session["employee"] = User.Split('@')[0];
string ename = Convert.ToString(Session["employee"]);
DataTable c = objbll.getEidByName(ename);
DataRow row = c.Rows[0];
Session["eid"] = Int32.Parse(row["EmpID"].ToString());
Response.Redirect("EmployeeDetails.aspx");
}
else if (objbll.guestLogin(User, Pass))
{
Session["GuestName"] = User;
string guest = Convert.ToString(Session["GuestName"]);
DataTable c = objbll.getGuestByMail(User);
DataRow row = c.Rows[0];
Session["GuestGid"] = Int32.Parse(row["GuestId"].ToString());
Response.Redirect("GuestHome.aspx");
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Invalid User')", true);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DBStore.DataAccess.Data.Repository.IRepository;
using DBStore.Models.VModels;
using ExcelDataReader;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace DBStore.Pages.Admin.City
{
public class ImportModel : PageModel
{
private IUnitOfWorkRepository _unitOfWork;
private IWebHostEnvironment _hostingEnvironment;
public ImportModel(IUnitOfWorkRepository unitOfWork, IWebHostEnvironment hostingEnvironment)
{
_unitOfWork = unitOfWork;
_hostingEnvironment = hostingEnvironment;
}
public void OnGet()
{
}
[BindProperty]
public CityVM CityObj { get; set; }
//public IActionResult OnPost()
//{
// var citycount = _unitOfWork.City.GetAll().Count();
// if (citycount > 0)
// {
// IFormFile file = Request.Form.Files[0];
// int startRec = Convert.ToInt32(HttpContext.Request.Form["start"][0]);
// string folderName = "ExcelFile";
// string webRootPath = _hostingEnvironment.WebRootPath;
// string newPath = Path.Combine(webRootPath, folderName);
// StringBuilder sb = new StringBuilder();
// if (!Directory.Exists(newPath))
// {
// Directory.CreateDirectory(newPath);
// }
// _unitOfWork.City.Add(CityObj.City);
// }
// else
// {
// int startRec = Convert.ToInt32(HttpContext.Request.Form["start"][0]);
// IFormFile file = Request.Form.Files[0];
// string folderName = "ExcelFile";
// string webRootPath = _hostingEnvironment.WebRootPath;
// string newPath = Path.Combine(webRootPath, folderName);
// if (file.Length > 0)
// {
// string sFileExtension = Path.GetExtension(file.FileName).ToLower();
// //ISheet sheet;
// string fullPath = Path.Combine(newPath, file.FileName);
// using (var stream = System.IO.File.Create(fullPath))
// {
// file.CopyToAsync(stream);
// }
// using (var streams = System.IO.File.Open(fullPath, FileMode.Open, FileAccess.Read))
// {
// System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// using (var reader = ExcelReaderFactory.CreateReader(streams))
// {
// while (reader.Read())
// {
// if (reader.GetValue(0) != null)
// {
// CityObj.City.Name = reader.GetValue(1) != null ? reader.GetValue(startRec).ToString() : "Not defined";
// CityObj.City.AddDate = DateTime.Now;
// CityObj.City.AddedBy = "1";
// CityObj.City.Status = 1;
// }
// }
// }
// System.IO.File.Delete(fullPath);
// }
// }
// _unitOfWork.City.Update(CityObj.City);
// }
// return this.Content("Successfully saved in database");
//}
public void OnPost(IFormFile file)
{
// IFormFile file = Request.Form.Files[0];
// int startRec = Convert.ToInt32(HttpContext.Request.Form["start"][0]); //startRec te value pass hoscche nah
// string folderName = "ExcelFile";
// string webRootPath = _hostingEnvironment.ContentRootPath;
// string newPath = Path.Combine(webRootPath, folderName);
// StringBuilder sb = new StringBuilder();
// if (!Directory.Exists(newPath))
// {
// Directory.CreateDirectory(newPath);
// }
// if (file.Length > 0)
// {
// string sFileExtension = Path.GetExtension(file.FileName).ToLower();
// //ISheet sheet;
// string fullPath = Path.Combine(newPath, file.FileName);
// using (var stream = System.IO.File.Create(fullPath))
// {
// file.CopyToAsync(stream);
// }
// using (var streams = System.IO.File.Open(fullPath, FileMode.Open, FileAccess.Read))
// {
// System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// using (var reader = ExcelReaderFactory.CreateReader(streams))
// {
// while (reader.Read())
// {
// if (reader.GetValue(0) != null)
// {
// CityObj.City.Name = reader.GetValue(1) != null ? reader.GetValue(startRec).ToString() : "Not defined";
// CityObj.City.AddDate = DateTime.Now;
// CityObj.City.AddedBy = "1";
// CityObj.City.Status = 1;
// //datas.LastName = reader.GetValue(2) != null ? reader.GetValue(1).ToString() : "Last Name";
// //datas.Email = reader.GetValue(3) != null ? reader.GetValue(1).ToString() : "Email";
// //datas.FbLink = reader.GetValue(4) != null ? reader.GetValue(1).ToString() : "FbLink";
// _unitOfWork.City.Add(CityObj.City);
// }
// }
// }
// System.IO.File.Delete(fullPath);
// }
// }
// return this.Content("Successfully saved in database");
//}
List<CityVM> users = new List<CityVM>();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = new MemoryStream())
{
file.CopyTo(stream);
stream.Position = 0;
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read()) //Each row of the file
{
//users.Add(new CityVM { Name = reader.GetValue(0).ToString(), City = reader.GetValue(1).ToString() });
}
}
}
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zhouli.Common.Middleware
{
/// <summary>
/// 请求记录中间件
/// </summary>
public class LogReqResponseMiddleware
{
private readonly RequestDelegate _next;
private SortedDictionary<string, object> _data;
private Stopwatch _stopwatch;
public LogReqResponseMiddleware(RequestDelegate next)
{
_next = next;
_stopwatch = new Stopwatch();
}
public async Task Invoke(HttpContext context)
{
var strAccept = context.Request.Headers["Accept"].ToString().ToLower();
if (strAccept.Contains("image") || strAccept.Contains("html") || strAccept.Contains("css"))
{
await _next(context);
return;
}
var strRequestUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
if (strRequestUrl.Contains(".js") || strRequestUrl.Contains(".html") || strRequestUrl.Contains(".css"))
{
await _next(context);
return;
}
context.Request.EnableBuffering();
_stopwatch.Restart();
_data = new SortedDictionary<string, object>();
var requestReader = new StreamReader(context.Request.Body);
var requestContent = requestReader.ReadToEnd();
//记录请求信息
_data.Add("request.url", strRequestUrl);
_data.Add("request.headers", context.Request.Headers.ToDictionary(x => x.Key, v => string.Join(";", v.Value.ToList())));
_data.Add("request.method", context.Request.Method);
_data.Add("request.executeStartTime", DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
_data.Add("request.body", requestContent);
context.Request.Body.Position = 0;
var originalBodyStream = context.Response.Body;
using (var responseBody = new MemoryStream())
{
context.Response.Body = responseBody;
await _next(context);
var response = context.Response;
response.Body.Seek(0, SeekOrigin.Begin);
//转化为字符串
string text = await new StreamReader(response.Body).ReadToEndAsync();
//从新设置偏移量0
response.Body.Seek(0, SeekOrigin.Begin);
await responseBody.CopyToAsync(originalBodyStream);
//记录返回值
_stopwatch.Stop();
_data.Add("elaspedTime", _stopwatch.ElapsedMilliseconds + "ms");
_data.Add("response.body", text);
_data.Add("response.executeEndTime", DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
Log4netHelper.Info(typeof(LogReqResponseMiddleware), JsonConvert.SerializeObject(_data));
}
}
}
/// <summary>
/// 请求记录中间件(依赖于log4net)
/// </summary>
public static class LogReqResponseMiddlewareExtensions
{
/// <summary>
/// 请求记录中间件(依赖于log4net)
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseLogReqResponseMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LogReqResponseMiddleware>();
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using RMAT3.Models;
namespace RMAT3.Data.Mapping
{
public class AuditWarrantyMap : EntityTypeConfiguration<AuditWarranty>
{
public AuditWarrantyMap()
{
// Primary Key
HasKey(t => t.AuditWarrantyId);
// Properties
Property(t => t.UpdatedCommentTxt)
.HasMaxLength(100);
Property(t => t.WarrantyNm)
.HasMaxLength(100);
Property(t => t.WarrantyStatusCd)
.HasMaxLength(50);
Property(t => t.WarrantyTxt)
.HasMaxLength(2000);
// Table & Column Mappings
ToTable("AuditWarranty", "OLTP");
Property(t => t.AuditWarrantyId).HasColumnName("AuditWarrantyId");
Property(t => t.AddedByPartyERId).HasColumnName("AddedByPartyERId");
Property(t => t.AddTs).HasColumnName("AddTs");
Property(t => t.UpdatedByPartyERId).HasColumnName("UpdatedByPartyERId");
Property(t => t.UpdatedCommentTxt).HasColumnName("UpdatedCommentTxt");
Property(t => t.UpdatedTs).HasColumnName("UpdatedTs");
Property(t => t.IsActiveInd).HasColumnName("IsActiveInd");
Property(t => t.WarrantyDueDt).HasColumnName("WarrantyDueDt");
Property(t => t.WarrantyNm).HasColumnName("WarrantyNm");
Property(t => t.WarrantyStatusCd).HasColumnName("WarrantyStatusCd");
Property(t => t.WarrantyTxt).HasColumnName("WarrantyTxt");
Property(t => t.WarrantyTypeId).HasColumnName("WarrantyTypeId");
Property(t => t.AuditDetailId).HasColumnName("AuditDetailId");
// Relationships
HasOptional(t => t.AuditDetail)
.WithMany(t => t.AuditWarranties)
.HasForeignKey(d => d.AuditDetailId);
HasOptional(t => t.WarrantyType)
.WithMany(t => t.AuditWarranties)
.HasForeignKey(d => d.WarrantyTypeId);
}
}
}
|
using UnityEngine;
using System.Collections;
using SLua;
[SLua.CustomLuaClass]
public class OzLuaCoroutine : MonoBehaviour
{
public void ExecuteWhen(object instruction, LuaFunction func, object param)
{
StartCoroutine(ExecuteWhenCoroutine(instruction, func, param));
}
private IEnumerator ExecuteWhenCoroutine(object instruction, LuaFunction func, object param)
{
yield return instruction;
func.call(param);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Windows.Forms;
namespace HCAlarmService
{
public class XMLClass
{
private static string applicationStr = "";
public static DataSet GetAppConfig()
{
string path = Application.StartupPath + "\\App.xml";
DataSet ds = new DataSet();
ds.ReadXml(path);
return ds;
}
public static void UpdateAppConfig(string key, string newValue)
{
//初始化XML文档操作类
XmlDocument myDoc = new XmlDocument();
//加载XML文件
string FileName = Application.StartupPath + "\\App.xml";
myDoc.Load(FileName);
//搜索指定的节点
System.Xml.XmlNodeList nodes = myDoc.SelectNodes("//appSetting");
if (nodes != null)
{
foreach (System.Xml.XmlNode xn in nodes)
{
if (xn.Attributes["key"].Value == key)
{
if (xn.Attributes["value"].Value == newValue)
{
return;
}
else
{
xn.Attributes["value"].Value = newValue;
break;
}
}
}
}
myDoc.Save(FileName);
}
}
}
|
using UnityEngine;
using System.Collections;
public class UpgradingGUI : MonoBehaviour {
//GUI, die bei Ansprechen eines Schmieds aufgerufen wird um die Ausrüstung des Charakters zu verbessern
public string upgradeWeapon;
public string upgradeArmor;
public int upgradeCap;
//Werte für Waffenausbau
WeaponValues playerWeaponStats;
public float damageIncrease;
public float attackCostDecrease;
public int weaponUpgradeCosts;
//Werte für Helmausbau
ArmorValues playerHelmetStats;
public float helmetIncrease;
//Werte für Kürassausbau
ArmorValues playerCuirassStats;
public float cuirassIncrease;
public int cuirassUpgradeCosts;
//Werte für Handschuhausbau
ArmorValues playerGauntletsStats;
public float gauntletsIncrease;
//Werte für Beinschienenausbau
ArmorValues playerLeggingsStats;
public float leggingsIncrease;
void Start(){
playerWeaponStats = Persistent.persist.weapon.GetComponent<WeaponValues> ();
playerCuirassStats = Persistent.persist.cuirass.GetComponent<ArmorValues> ();
upgradeWeapon = weaponUpgradeCosts+" Souls: " + playerWeaponStats.weaponName + "+" + playerWeaponStats.weaponLevel;
upgradeArmor = cuirassUpgradeCosts+" Souls: " + playerCuirassStats.cuirassName + "+" + playerCuirassStats.armorLevel;
}
void OnGUI(){
//Waffenausbau erhöht Schaden und verringert die Ausdauerkosten pro Angriff
if (GUI.Button (new Rect (Screen.width / 2f - 100, Screen.height / 4f, 200, 40), upgradeWeapon)) {
if(playerWeaponStats.weaponLevel < upgradeCap){
if(Persistent.persist.souls >= weaponUpgradeCosts){
Persistent.persist.souls -= weaponUpgradeCosts;
weaponUpgradeCosts += 1000;
playerWeaponStats.weaponLevel += 1;
playerWeaponStats.damage += damageIncrease;
playerWeaponStats.attackCost -= attackCostDecrease;
upgradeWeapon = weaponUpgradeCosts+" Souls: " + playerWeaponStats.weaponName + "+" + playerWeaponStats.weaponLevel;
Persistent.persist.UpdateWeapon();
}
else{
GUI.Box (new Rect (0, 0, Screen.width, 30), "Not enough souls to upgrade Weapon");
Debug.Log ("Not enough souls to upgrade Weapon");
}
}
else if(playerWeaponStats.weaponLevel >= upgradeCap){
Debug.Log ("Weapon is already fully upgraded");
}
}
//Kürassausbau erhöht den Rüstungswert auf der Brustplatte und erhöht die Ausdauerregeneration
else if(GUI.Button (new Rect (Screen.width / 2f -100, Screen.height / 4f + 60, 200, 40), upgradeArmor)){
if(playerCuirassStats.armorLevel < upgradeCap){
if(Persistent.persist.souls >= cuirassUpgradeCosts){
Persistent.persist.souls -= cuirassUpgradeCosts;
cuirassUpgradeCosts += 1000;
playerCuirassStats.armorLevel += 1;
playerCuirassStats.armorValue += cuirassIncrease;
upgradeArmor = cuirassUpgradeCosts+" Souls: " + playerCuirassStats.cuirassName + "+" + playerCuirassStats.armorLevel;
Persistent.persist.UpdateCuirass();
}
else{
GUI.Box (new Rect (0, 0, Screen.width, 30), "Not enough souls to upgrade Armor");
Debug.Log("Not enough souls to upgrade Armor");
}
}
else if (playerCuirassStats.armorLevel >= upgradeCap){
Debug.Log ("Armor is already fully upgraded");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Cognitive_Application
{
/// <summary>
/// Logique d'interaction pour Home.xaml
/// </summary>
public partial class Home : Page
{
public Home()
{
InitializeComponent();
}
private void EmotionButton_Click(object sender, RoutedEventArgs e)
{
MainWindow.SwitchPage("Emotion");
}
private void TextAnalysisButton_Click(object sender, RoutedEventArgs e)
{
MainWindow.SwitchPage("TextAnalysis");
}
private void StatisticsButton_Click(object sender, RoutedEventArgs e)
{
MainWindow.SwitchPage("Statistics");
}
#region Esthetic
private void EmotionButton_MouseEnter(object sender, MouseEventArgs e)
{
EmotionButton.Opacity = 1;
BorderEmotion.BorderThickness = new Thickness(5);
}
private void EmotionButton_MouseLeave(object sender, MouseEventArgs e)
{
EmotionButton.Opacity = 0.6;
BorderEmotion.BorderThickness = new Thickness(0);
}
private void TextAnalysisButton_MouseEnter(object sender, MouseEventArgs e)
{
TextAnalysisButton.Opacity = 1;
BorderTextAnalysis.BorderThickness = new Thickness(5);
}
private void TextAnalysisButton_MouseLeave(object sender, MouseEventArgs e)
{
TextAnalysisButton.Opacity = 0.6;
BorderTextAnalysis.BorderThickness = new Thickness(0);
}
private void StatisticsButton_MouseEnter(object sender, MouseEventArgs e)
{
StatisticsButton.Opacity = 1;
BorderStatistics.BorderThickness = new Thickness(5);
}
private void StatisticsButton_MouseLeave(object sender, MouseEventArgs e)
{
StatisticsButton.Opacity = 0.6;
BorderStatistics.BorderThickness = new Thickness(0);
}
#endregion Esthetic
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02_Uygulama
{
class Daire //const kullanımı için yazıldı. Set edilemeyeceği için dörülemiyor.
{
public const double pi = 3.14;
private int _cap;
public int Cap
{
get { return _cap; }
set { _cap = value; }
}
public double AlanHesapla()
{
return pi * (Cap / 2) * (Cap / 2);
}
}
}
|
using System;
using System.Runtime.Serialization;
namespace Migration.Common.Log
{
[Serializable]
public class AbortMigrationException : Exception
{
protected AbortMigrationException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
}
public AbortMigrationException(string reason)
{
Reason = reason;
}
public string Reason { get; private set; }
}
} |
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Scrawl.CodeEngine.Roslyn")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OmniSharp")] |
using Newtonsoft.Json;
namespace Grimoire.Game.Data
{
public class QuestReward
{
[JsonProperty("iCP")]
public int ClassPoints { get; set; }
[JsonProperty("intGold")]
public int Gold { get; set; }
[JsonProperty("intExp")]
public int Experience { get; set; }
[JsonProperty("typ")]
public string Type { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class Damage : MonoBehaviour {
//Health
public float health;
public float hearthProb;
public AudioClip morir;
//Drops
//public Dictionary<String,GameObject> Drops;
public GameObject[] drops;
public Vector3 lastPosition;
public void HealthVaration(float variation)
{
health += variation;
if(health <= 0)
{
DieAndReplace();
}
}
public void ApplyDamage(float damage)
{
HealthVaration(damage);
}
public void DieAndReplace()
{
AudioSource.PlayClipAtPoint (morir, transform.position);
lastPosition = transform.position;
gameObject.SetActive(false);
if(Dices.prob(1- hearthProb))
{
//drops[0].transform.position = lastPosition;
//drops[0].SetActive(true);
Instantiate(drops[0],lastPosition,Quaternion.identity);
}
else
{
int index = Dices.dice(0,4);
Debug.Log(index);
//drops[index].transform.position = lastPosition;
//drops[index].SetActive(true);
Instantiate(drops[index],lastPosition,Quaternion.identity);
}
}
}
|
/** 版本信息模板在安装目录下,可自行修改。
* Key.cs
*
* 功 能: N/A
* 类 名: Key
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2014/12/4 17:26:50 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
namespace IES.Resource.Model
{
/// <summary>
/// 标签表、关键字表
/// </summary>
[Serializable]
public partial class Key
{
#region 补充属性
/// <summary>
/// 标签下习题数
/// </summary>
public int ExerciseCount { get; set; }
#endregion
public Key()
{ }
#region Model
private int _keyid;
private string _name;
private int _owneruserid = 0;
private int? _createuserid;
private int _courseid = 0;
private int? _ocid = 0;
/// <summary>
///
/// </summary>
public int KeyID
{
set { _keyid = value; }
get { return _keyid; }
}
/// <summary>
///
/// </summary>
public string Name
{
set { _name = value; }
get { return _name; }
}
/// <summary>
///
/// </summary>
public int OwnerUserID
{
set { _owneruserid = value; }
get { return _owneruserid; }
}
/// <summary>
///
/// </summary>
public int? CreateUserID
{
set { _createuserid = value; }
get { return _createuserid; }
}
/// <summary>
///
/// </summary>
public int CourseID
{
set { _courseid = value; }
get { return _courseid; }
}
/// <summary>
///
/// </summary>
public int? OCID
{
set { _ocid = value; }
get { return _ocid; }
}
#endregion Model
}
}
|
#load "common.csx"
string pathToBuildDirectory = @"tmp/";
private string version = "1.0.0";
WriteLine("DotNet.Script.NuGetMetadataResolver version {0}" , version);
Execute(() => InitializBuildDirectories(), "Preparing build directories");
Execute(() => BuildAllFrameworks(), "Building all frameworks");
Execute(() => CreateNugetPackages(), "Creating NuGet packages");
private void CreateNugetPackages()
{
string pathToProjectFile = Path.Combine(pathToBuildDirectory, @"Dotnet.Script.NuGetMetadataResolver/Dotnet.Script.NuGetMetadataResolver.csproj");
DotNet.Pack(pathToProjectFile, pathToBuildDirectory);
string myDocumentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
RoboCopy(pathToBuildDirectory, myDocumentsFolder, "*.nupkg");
}
private void BuildAllFrameworks()
{
BuildDotNet();
}
private void BuildDotNet()
{
string pathToProjectFile = Path.Combine(pathToBuildDirectory, @"Dotnet.Script.NuGetMetadataResolver/Dotnet.Script.NuGetMetadataResolver.csproj");
DotNet.Build(pathToProjectFile);
}
private void InitializBuildDirectories()
{
DirectoryUtils.Delete(pathToBuildDirectory);
Execute(() => InitializeNugetBuildDirectory("NETSTANDARD16"), "Preparing NetStandard1.6");
}
private void InitializeNugetBuildDirectory(string frameworkMoniker)
{
CreateDirectory(pathToBuildDirectory);
RoboCopy("../src", pathToBuildDirectory, "/e /XD bin obj .vs TestResults packages /XF project.lock.json");
}
|
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using W3ChampionsStatisticService.WebApi.ExceptionFilters;
namespace W3ChampionsStatisticService.WebApi.ActionFilters
{
public class CheckIfBattleTagBelongsToAuthCodeFilter : IAsyncActionFilter {
private readonly IW3CAuthenticationService _authService;
public CheckIfBattleTagBelongsToAuthCodeFilter(IW3CAuthenticationService authService)
{
_authService = authService;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
context.RouteData.Values.TryGetValue("battleTag", out var battleTag);
var queryString = HttpUtility.ParseQueryString(context.HttpContext.Request.QueryString.Value);
if (queryString.AllKeys.Contains("authorization"))
{
var auth = queryString["authorization"];
var res = _authService.GetUserByToken(auth);
var btagString = battleTag?.ToString();
if (
res != null
&& !string.IsNullOrEmpty(btagString)
&& btagString.Equals(res.BattleTag))
{
context.ActionArguments["battleTag"] = res.BattleTag;
await next.Invoke();
}
}
var unauthorizedResult = new UnauthorizedObjectResult(new ErrorResult("Sorry H4ckerb0i"));
context.Result = unauthorizedResult;
}
}
} |
using CP.i8n;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CriticalPath.Data
{
public partial class PurchaseOrderDTO : IIsApproved, IHasProduct, ICancelled, IAllPrice
{
partial void Initiliazing(PurchaseOrder entity)
{
Constructing(entity);
}
/// <summary>
/// Constructing with a PurchaseOrder instance
/// </summary>
/// <param name="entity">PurchaseOrder instance</param>
protected virtual void Constructing(PurchaseOrder entity)
{
foreach (var rate in entity.SizeRatios)
{
SizeRatios.Add(new POSizeRatioDTO(rate));
}
if (entity.Designer?.AspNetUser != null)
DesignerName = string.Format("{0} {1}", entity.Designer.AspNetUser.FirstName, entity.Designer.AspNetUser.LastName);
if (entity.Merchandiser1?.AspNetUser != null)
Merchandiser1Name = string.Format("{0} {1}", entity.Merchandiser1.AspNetUser.FirstName, entity.Merchandiser1.AspNetUser.LastName);
if (entity.Merchandiser2?.AspNetUser != null)
Merchandiser2Name = string.Format("{0} {1}", entity.Merchandiser2.AspNetUser.FirstName, entity.Merchandiser2.AspNetUser.LastName);
}
partial void Converting(PurchaseOrder entity)
{
foreach (var rate in SizeRatios)
{
entity.SizeRatios.Add(rate.ToPOSizeRatio());
}
}
public ICollection<POSizeRatioDTO> SizeRatios
{
set { _sizeRatios = value; }
get
{
if (_sizeRatios == null)
InitSizeRatios();
return _sizeRatios;
}
}
private ICollection<POSizeRatioDTO> _sizeRatios;
protected virtual void InitSizeRatios()
{
_sizeRatios = new List<POSizeRatioDTO>();
}
[Display(ResourceType = typeof(EntityStrings), Name = "Designer")]
public string DesignerName { get; set; }
[Display(ResourceType = typeof(EntityStrings), Name = "Merchandiser1")]
public string Merchandiser1Name { get; set; }
[Display(ResourceType = typeof(EntityStrings), Name = "Merchandiser2")]
public string Merchandiser2Name { get; set; }
}
}
|
//Problem 1. School classes
// We are given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches a set of disciplines.
// Students have name and unique class number. Classes have unique text identifier. Teachers have name. Disciplines have name, number of lectures
// and number of exercises. Both teachers and students are people. Students, classes, teachers and disciplines could have optional comments (free text block).
// Your task is to identify the classes (in terms of OOP) and their attributes and operations, encapsulate their fields, define the class hierarchy and create a class diagram with Visual Studio.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OOPPrinciplesPart1
{
class MainProgram
{
static void Main(string[] args)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ClickPizza.WindowsPhone.Model;
namespace ClickPizza.WindowsPhone.Data
{
public class StubRepository :IRepository
{
private static readonly StubRepository _stubRepository = new StubRepository();
public static StubRepository Instance
{
get
{
{
return _stubRepository;
}
}
}
private readonly IList<PizzaDetailsModel> _pizzaCollection = new List<PizzaDetailsModel>();
public IEnumerable<PizzaDetailsModel> PizzaCollection { get { return _pizzaCollection; } }
public PizzaDetailsModel GetPizzaById(int id)
{
return _pizzaCollection.First(p=>p.Id==id);
}
private StubRepository()
{
for (var i = 1; i < 11; i++)
{
var path = @"../Assets/PizzaImages/"+ new Random().Next(1,4)+".jpg";
_pizzaCollection.Add(new PizzaDetailsModel(i,path, @"Pizza № " + i, "Some composition", i * i, i + i, i * 100 / 3.0F));
}
}
}
}
|
using Models;
using System;
using DL;
using System.Collections.Generic;
namespace BL
{
public class PetBL : IPetBL
{
private IPetRepo _repo;
public PetBL(IPetRepo repo)
{
_repo = repo;
}
public List<Cat> ViewAllCats(){
return _repo.GetAllCats();
}
}
}
|
using System.IO;
using System.Linq;
using System.Speech.Recognition;
using System.Threading.Tasks;
namespace SpeechApi.Models
{
public class SpeechToText
{
private readonly Grammar _grammar;
public SpeechToText()
{
_grammar = new DictationGrammar {Name = "Dictation Grammar"};
}
public string GetText(Stream stream)
{
return Recognize(stream);
}
public async Task<string> GetTextAsync(Stream stream)
{
return await Task.Run(() => GetText(stream));
}
private string Recognize(Stream stream)
{
using (SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine(GetRecognizerInfo()))
{
recognizer.LoadGrammar(_grammar);
SetRecognizerInput(recognizer, stream);
var result = recognizer.Recognize();
//async version
//recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
//recognizer.RecognizeCompleted += new EventHandler<RecognizeCompletedEventArgs>(recognizer_RecognizeCompleted);
return result?.Text;
}
}
protected void SetRecognizerInput(SpeechRecognitionEngine recognizer, Stream stream)
{
//var fmt = new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono);
recognizer.SetInputToWaveStream(stream);
}
private RecognizerInfo GetRecognizerInfo()
{
var recognizers = SpeechRecognitionEngine.InstalledRecognizers();
return recognizers.First();
}
}
} |
using System;
using UnityEngine;
namespace UnityUIPlayables
{
[Serializable]
public class SliderAnimationBehaviour : AnimationBehaviour
{
[SerializeField] private SliderAnimationValue _startValue;
[SerializeField] private SliderAnimationValue _endValue;
public SliderAnimationValue StartValue => _startValue;
public SliderAnimationValue EndValue => _endValue;
}
} |
using Microsoft.Extensions.DependencyInjection;
using System;
namespace Hybrid.Domain.UnitOfWorks
{
public class UnitOfWorkManager : IUnitOfWorkManager
{
//private readonly IIocResolve _iocResolve;
private readonly IServiceProvider _serviceProvider;
private readonly ICurrentUnitOfWorkProvider _currentUnitOfWorkProvider;
public UnitOfWorkManager(IServiceProvider serviceProvider, ICurrentUnitOfWorkProvider currentUnitOfWorkProvider)
{
_serviceProvider = serviceProvider;
_currentUnitOfWorkProvider = currentUnitOfWorkProvider;
}
public IActiveUnitOfWork Current => _currentUnitOfWorkProvider.Current;
/// <summary>
/// Begin
/// </summary>
/// <returns></returns>
public IUnitOfWorkCompleteHandle Begin()
{
var outerUow = _currentUnitOfWorkProvider.Current;
if (outerUow != null)
return new InnerUnitOfWorkCompleteHandle();
var uow = _serviceProvider.GetService<IUnitOfWork>();
uow.Begin();
_currentUnitOfWorkProvider.Current = uow;
return uow;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class on_off_music : MonoBehaviour
{
public GameObject on;
public GameObject off;
public AudioSource[] musics;
private Player player;
public void Start()
{
player = GameObject.FindObjectOfType<Player>();
refreshList();
Debug.Log("Music: " + player.IsMusicOn);
if (player.IsMusicOn)
{
on.SetActive(true);
off.SetActive(false);
foreach (AudioSource music in musics)
{
if (music.tag == "Music_Source")
{
music.volume = 1.0f;
}
}
}
else
{
off.SetActive(true);
on.SetActive(false);
foreach (AudioSource music in musics)
{
if (music.tag == "Music_Source")
{
music.volume = 0.0f;
}
}
}
}
public void refreshList()
{
musics = GameObject.FindObjectsOfType<AudioSource>();
}
public void toggleOnOff()
{
refreshList();
if (!on.activeSelf)
{
on.SetActive(true);
off.SetActive(false);
player.IsMusicOn = true;
foreach (AudioSource music in musics)
{
if (music.tag == "Music_Source")
{
music.volume = 1.0f;
}
}
}
else
{
off.SetActive(true);
on.SetActive(false);
player.IsMusicOn = false;
foreach (AudioSource music in musics)
{
if (music.tag == "Music_Source")
{
music.volume = 0.0f;
}
}
}
}
}
|
using UnityEngine;
using UnityEngine.AI;
public class StopAgentHandler : MonoBehaviour
{
public FloatData HoldTime;
private NavMeshAgent agent;
public GameAction StopAgentAction;
void Start()
{
agent = GetComponent<NavMeshAgent>();
StopAgentAction.RaiseNoArgs += AgentHandler;
}
private void AgentHandler ()
{
agent.isStopped = true;
Invoke("RestartAgent", HoldTime.Value);
}
private void RestartAgent()
{
agent.isStopped = false;
}
private void OnDestroy()
{
StopAgentAction.RaiseNoArgs -= AgentHandler;
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using DotNetNuke.Entities.Modules;
using DotNetNuke.UI.Modules;
namespace DotNetNuke.Web.Mvc
{
public class MvcSettingsControl : MvcHostControl, ISettingsControl
{
public MvcSettingsControl() : base("Settings")
{
ExecuteModuleImmediately = false;
}
public void LoadSettings()
{
ExecuteModule();
}
public void UpdateSettings()
{
ExecuteModule();
ModuleController.Instance.UpdateModule(ModuleContext.Configuration);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ProductTest.Models;
namespace ProductTest.Data
{
public class BulkUpload : IBulkUpload
{
private readonly DataContext _context;
public BulkUpload(DataContext context)
{
_context = context;
}
public async Task<List<BooleanTest>> Bool(List<BooleanTest> bools)
{
await _context.BooleanTests.AddRangeAsync(bools);
await _context.SaveChangesAsync();
return bools;
}
public async Task<List<Test>> Testing(List<Test> tests)
{
await _context.Tests.AddRangeAsync(tests);
await _context.SaveChangesAsync();
return tests;
}
public async Task<List<PatternTest>> UploadPattern(List<PatternTest> patterns)
{
var existingPatterns = await _context.Patterns.Where(x => x.Title == x.Title).ToListAsync();
_context.RemoveRange(existingPatterns);
await _context.SaveChangesAsync();
await _context.Patterns.AddRangeAsync(patterns);
await _context.SaveChangesAsync();
return patterns;
}
public async Task<List<SkuTest>> UploadSku(List<SkuTest> skus)
{
var existingSkus = await _context.Skus.Where(x => x.Sku == x.Sku).ToListAsync();
_context.RemoveRange(existingSkus);
await _context.SaveChangesAsync();
await _context.Skus.AddRangeAsync(skus);
await _context.SaveChangesAsync();
return skus;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UI.ViewModels
{
public class ProdutoClienteInsertViewModel
{
public Guid Vendedor_id { get; set; }
public Guid Cliente_id { get; set; }
public Guid Produto_id { get; set; }
}
public class ProdutoClienteAvaliateViewModel
{
public Guid ProdutoCliente_id { get; set; }
public int Estrelas { get; set; }
}
public class ComprasViewModelResult
{
public ComprasViewModelResult(int avaliacao, string nome_produto)
{
Avaliacao = avaliacao;
Nome_produto = nome_produto;
}
public int Avaliacao { get; set; }
public string Nome_produto { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace OnlineShopping
{
public partial class UserAdd : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "")
{
Response.Write("<script>alert('请输入用户名')</script>");
return;
}
if (txtNickName.Text == "")
{
Response.Write("<script>alert('请输入昵称')</script>");
return;
}
if (txtNewUserPassword.Text == "")
{
Response.Write("<script>alert('请输入密码')</script>");
return;
}
if (txtEnterUserPassword.Text == "")
{
Response.Write("<script>alert('请确认密码')</script>");
return;
}
if(DBHelper.Select("select * from Users where UserName='"+txtUserName.Text+"'").Tables[0].Rows.Count>0)
{
Response.Write("<script>alert('该用户名已使用')</script>");
return;
}
if(txtNewUserPassword.Text!=txtEnterUserPassword.Text)
{
Response.Write("<script>alert('两次输入密码不一致')</script>");
return;
}
if(DBHelper.Update("insert into Users (UserName,NickName,UserPassword,IsAdmin) values ('"+txtUserName.Text+"','"+txtNickName.Text+"','"+txtNewUserPassword.Text+"',1)"))
{
Response.Write("<script>alert('添加管理员成功');window.location.href='UserAdd.aspx'</script>");
return;
}
else
{
Response.Write("<script>alert('添加管理员失败')</script>");
return;
}
}
}
} |
using UnityEngine;
using System.Collections;
public class BulletScript : MonoBehaviour {
public float speed = 10;
public int maxDamage = 1;
public int minDamage = 2;
public int baseDamage = 0;
public int direction = 0;
public int angle = 0;
public GameObject origin;
// Use this for initialization
void Start () {
//Destroy (gameObject, 1);
//shoot up
if (direction == 0) {
transform.Rotate(0,0,90);
}
//shoot right
if (direction == 1) {
transform.Rotate(0,0,0,0);
}
//shoot down
if (direction == 2) {
transform.Rotate(0,0,270,0);
}
//shoot left
if (direction == 3) {
transform.Rotate(0,0,180,0);
}
}
// Update is called once per frame
void Update () {
var behave = GameObject.FindGameObjectWithTag("Behaviour").GetComponent<GameBehavior>();
if(!behave.pause){
//partial solution check when reworking classes
if(angle == 0){
transform.Translate(Vector3.right * (speed * Time.deltaTime));
}else{
transform.Translate(new Vector3(Mathf.Cos(angle * (float)(Mathf.PI / 180.0)),Mathf.Sin(angle * (float)(Mathf.PI / 180.0)),0) * (speed * Time.deltaTime));
}
}
}
void OnTriggerEnter2D (Collider2D col){
var maxDamageCurrent = maxDamage + (int)(maxDamage * (float)(baseDamage / 50.0));
var minDamageCurrent = minDamage + (int)(minDamage * (float)(baseDamage / 50.0));
if (col.gameObject.tag == "Player" && col.gameObject != origin) {
col.gameObject.GetComponent<Player>().TakeDamage(Random.Range(minDamageCurrent,maxDamageCurrent));
Destroy (this.gameObject);
return;
}
if (col.gameObject.tag == "Enemy" && col.gameObject.tag == origin.tag && col.gameObject != origin) {
Destroy (this.gameObject);
return;
}
if (col.gameObject.tag == "Enemy" && col.gameObject != origin) {
col.gameObject.GetComponent<Enemy>().TakeDamage(Random.Range(minDamageCurrent,maxDamageCurrent));
Destroy (this.gameObject);
return;
}
if (col.gameObject.tag == "Wall") {
Destroy(this.gameObject);
return;
}
if (col.gameObject.tag == "Destructable" && origin.tag == "Player") {
col.gameObject.GetComponent<Appear>().AppearThing();
Destroy(this.gameObject);
Destroy(col.gameObject);
return;
}
if (col.gameObject.tag == "Destructable" && origin.tag == "Enemy") {
Destroy(this.gameObject);
return;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using RimWorld.Planet;
using RimWorld.QuestGen;
using UnityEngine;
using Verse;
namespace Quests
{
public class QuestNode_GetPawnForQuest : QuestNode
{
private IEnumerable<Pawn> ExistingUsablePawns(Slate slate)
{
return from x in PawnsFinder.AllMapsWorldAndTemporary_Alive
where this.IsGoodPawn(x, slate)
select x;
}
protected override bool TestRunInt(Slate slate)
{
if (this.questGiver != null && this.storeAs.GetValue(slate) == "asker")
{
slate.Set<Pawn>(this.storeAs.GetValue(slate), this.questGiver, false);
return true;
}
if (this.mustHaveNoFaction.GetValue(slate) && this.mustHaveRoyalTitleInCurrentFaction.GetValue(slate))
{
return false;
}
if (this.canGeneratePawn.GetValue(slate) && (this.mustBeFactionLeader.GetValue(slate) || this.mustBeWorldPawn.GetValue(slate) || this.mustBePlayerPrisoner.GetValue(slate) || this.mustBeFreeColonist.GetValue(slate)))
{
Log.Warning("QuestNode_GetPawn has incompatible flags set, when canGeneratePawn is true these flags cannot be set: mustBeFactionLeader, mustBeWorldPawn, mustBePlayerPrisoner, mustBeFreeColonist", false);
return false;
}
Pawn pawn;
if (slate.TryGet<Pawn>(this.storeAs.GetValue(slate), out pawn, false) && this.IsGoodPawn(pawn, slate))
{
return true;
}
IEnumerable<Pawn> source = this.ExistingUsablePawns(slate);
if (source.Count<Pawn>() > 0)
{
slate.Set<Pawn>(this.storeAs.GetValue(slate), source.RandomElement<Pawn>(), false);
return true;
}
if (!this.canGeneratePawn.GetValue(slate))
{
return false;
}
Faction faction;
if (!this.mustHaveNoFaction.GetValue(slate) && !this.TryFindFactionForPawnGeneration(slate, out faction))
{
return false;
}
FloatRange senRange = this.seniorityRange.GetValue(slate);
return !this.mustHaveRoyalTitleInCurrentFaction.GetValue(slate) || !this.requireResearchedBedroomFurnitureIfRoyal.GetValue(slate) || DefDatabase<RoyalTitleDef>.AllDefsListForReading.Any((RoyalTitleDef x) => (senRange.max <= 0f || senRange.IncludesEpsilon((float)x.seniority)) && this.PlayerHasResearchedBedroomRequirementsFor(x));
}
private bool TryFindFactionForPawnGeneration(Slate slate, out Faction faction)
{
return (from x in Find.FactionManager.GetFactions(false, false, false, TechLevel.Undefined)
where (this.excludeFactionDefs.GetValue(slate) == null || !this.excludeFactionDefs.GetValue(slate).Contains(x.def)) && (!this.mustHaveRoyalTitleInCurrentFaction.GetValue(slate) || x.def.HasRoyalTitles) && (!this.mustBeNonHostileToPlayer.GetValue(slate) || !x.HostileTo(Faction.OfPlayer)) && ((this.allowPermanentEnemyFaction.GetValue(slate) ?? false) || !x.def.permanentEnemy) && x.def.techLevel >= this.minTechLevel.GetValue(slate)
select x).TryRandomElement(out faction);
}
protected override void RunInt()
{
Slate slate = QuestGen.slate;
Pawn pawn;
if (this.questGiver != null && this.storeAs.GetValue(slate) == "asker")
{
slate.Set<Pawn>(this.storeAs.GetValue(slate), this.questGiver, false);
return;
}
if (QuestGen.slate.TryGet<Pawn>(this.storeAs.GetValue(slate), out pawn, false) && this.IsGoodPawn(pawn, slate))
{
return;
}
IEnumerable<Pawn> source = this.ExistingUsablePawns(slate);
int num = source.Count<Pawn>();
Faction faction;
if (Rand.Chance(this.canGeneratePawn.GetValue(slate) ? Mathf.Clamp01(1f - (float)num / (float)this.maxUsablePawnsToGenerate.GetValue(slate)) : 0f) && (this.mustHaveNoFaction.GetValue(slate) || this.TryFindFactionForPawnGeneration(slate, out faction)))
{
pawn = this.GeneratePawn(slate, null);
}
else
{
pawn = source.RandomElement<Pawn>();
}
if (pawn.Faction != null && !pawn.Faction.def.hidden)
{
QuestPart_InvolvedFactions questPart_InvolvedFactions = new QuestPart_InvolvedFactions();
questPart_InvolvedFactions.factions.Add(pawn.Faction);
QuestGen.quest.AddPart(questPart_InvolvedFactions);
}
QuestGen.slate.Set<Pawn>(this.storeAs.GetValue(slate), pawn, false);
}
private Pawn GeneratePawn(Slate slate, Faction faction = null)
{
PawnKindDef pawnKindDef = this.mustBeOfKind.GetValue(slate);
if (faction == null && !this.mustHaveNoFaction.GetValue(slate))
{
if (!this.TryFindFactionForPawnGeneration(slate, out faction))
{
Log.Error("QuestNode_GetPawn tried generating pawn but couldn't find a proper faction for new pawn.", false);
}
else if (pawnKindDef == null)
{
pawnKindDef = faction.RandomPawnKind();
}
}
RoyalTitleDef fixedTitle;
if (this.mustHaveRoyalTitleInCurrentFaction.GetValue(slate))
{
FloatRange senRange;
if (!this.seniorityRange.TryGetValue(slate, out senRange))
{
senRange = FloatRange.Zero;
}
IEnumerable<RoyalTitleDef> source = from t in DefDatabase<RoyalTitleDef>.AllDefsListForReading
where faction.def.RoyalTitlesAllInSeniorityOrderForReading.Contains(t) && (senRange.max <= 0f || senRange.IncludesEpsilon((float)t.seniority))
select t;
if (this.requireResearchedBedroomFurnitureIfRoyal.GetValue(slate) && source.Any((RoyalTitleDef x) => this.PlayerHasResearchedBedroomRequirementsFor(x)))
{
source = from x in source
where this.PlayerHasResearchedBedroomRequirementsFor(x)
select x;
}
fixedTitle = source.RandomElementByWeight((RoyalTitleDef t) => t.commonality);
if (this.mustBeOfKind.GetValue(slate) == null && !(from k in DefDatabase<PawnKindDef>.AllDefsListForReading
where k.titleRequired != null && k.titleRequired == fixedTitle
select k).TryRandomElement(out pawnKindDef))
{
(from k in DefDatabase<PawnKindDef>.AllDefsListForReading
where k.titleSelectOne != null && k.titleSelectOne.Contains(fixedTitle)
select k).TryRandomElement(out pawnKindDef);
}
}
else
{
fixedTitle = null;
}
if (pawnKindDef == null)
{
pawnKindDef = (from kind in DefDatabase<PawnKindDef>.AllDefsListForReading
where kind.race.race.Humanlike
select kind).RandomElement<PawnKindDef>();
}
Pawn pawn = PawnGenerator.GeneratePawn(new PawnGenerationRequest(pawnKindDef, faction, PawnGenerationContext.NonPlayer, -1, fixedTitle: fixedTitle));
Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Decide);
if (pawn.royalty != null && pawn.royalty.AllTitlesForReading.Any<RoyalTitle>())
{
QuestPart_Hyperlinks questPart_Hyperlinks = new QuestPart_Hyperlinks();
questPart_Hyperlinks.pawns.Add(pawn);
QuestGen.quest.AddPart(questPart_Hyperlinks);
}
return pawn;
}
private bool IsGoodPawn(Pawn pawn, Slate slate)
{
if (this.mustBeFactionLeader.GetValue(slate))
{
Faction faction = pawn.Faction;
if (faction == null || faction.leader != pawn || !faction.def.humanlikeFaction || faction.defeated || faction.def.hidden || faction.IsPlayer || pawn.IsPrisoner)
{
return false;
}
}
if (pawn.Faction != null && this.excludeFactionDefs.GetValue(slate) != null && this.excludeFactionDefs.GetValue(slate).Contains(pawn.Faction.def))
{
return false;
}
if (pawn.Faction != null && pawn.Faction.def.techLevel < this.minTechLevel.GetValue(slate))
{
return false;
}
if (this.mustBeOfKind.GetValue(slate) != null && pawn.kindDef != this.mustBeOfKind.GetValue(slate))
{
return false;
}
if (this.mustHaveRoyalTitleInCurrentFaction.GetValue(slate) && (pawn.Faction == null || pawn.royalty == null || !pawn.royalty.HasAnyTitleIn(pawn.Faction)))
{
return false;
}
if (this.seniorityRange.GetValue(slate) != default(FloatRange) && (pawn.royalty == null || pawn.royalty.MostSeniorTitle == null || !this.seniorityRange.GetValue(slate).IncludesEpsilon((float)pawn.royalty.MostSeniorTitle.def.seniority)))
{
return false;
}
if (this.mustBeWorldPawn.GetValue(slate) && !pawn.IsWorldPawn())
{
return false;
}
if (this.ifWorldPawnThenMustBeFree.GetValue(slate) && pawn.IsWorldPawn() && Find.WorldPawns.GetSituation(pawn) != WorldPawnSituation.Free)
{
return false;
}
if (this.ifWorldPawnThenMustBeFreeOrLeader.GetValue(slate) && pawn.IsWorldPawn() && Find.WorldPawns.GetSituation(pawn) != WorldPawnSituation.Free && Find.WorldPawns.GetSituation(pawn) != WorldPawnSituation.FactionLeader)
{
return false;
}
if (pawn.IsWorldPawn() && Find.WorldPawns.GetSituation(pawn) == WorldPawnSituation.ReservedByQuest)
{
return false;
}
if (this.mustHaveNoFaction.GetValue(slate) && pawn.Faction != null)
{
return false;
}
if (this.mustBeFreeColonist.GetValue(slate) && !pawn.IsFreeColonist)
{
return false;
}
if (this.mustBePlayerPrisoner.GetValue(slate) && !pawn.IsPrisonerOfColony)
{
return false;
}
if (this.mustBeNotSuspended.GetValue(slate) && pawn.Suspended)
{
return false;
}
if (this.mustBeNonHostileToPlayer.GetValue(slate) && (pawn.HostileTo(Faction.OfPlayer) || (pawn.Faction != null && pawn.Faction != Faction.OfPlayer && pawn.Faction.HostileTo(Faction.OfPlayer))))
{
return false;
}
if (!(this.allowPermanentEnemyFaction.GetValue(slate) ?? true) && pawn.Faction != null && pawn.Faction.def.permanentEnemy)
{
return false;
}
if (this.requireResearchedBedroomFurnitureIfRoyal.GetValue(slate))
{
RoyalTitle royalTitle = pawn.royalty.HighestTitleWithBedroomRequirements();
if (royalTitle != null && !this.PlayerHasResearchedBedroomRequirementsFor(royalTitle.def))
{
return false;
}
}
return true;
}
private bool PlayerHasResearchedBedroomRequirementsFor(RoyalTitleDef title)
{
if (title.bedroomRequirements == null)
{
return true;
}
for (int i = 0; i < title.bedroomRequirements.Count; i++)
{
if (!title.bedroomRequirements[i].PlayerCanBuildNow())
{
return false;
}
}
return true;
}
public Pawn questGiver;
[NoTranslate]
public SlateRef<string> storeAs;
public SlateRef<bool> mustBeFactionLeader;
public SlateRef<bool> mustBeWorldPawn;
public SlateRef<bool> ifWorldPawnThenMustBeFree;
public SlateRef<bool> ifWorldPawnThenMustBeFreeOrLeader;
public SlateRef<bool> mustHaveNoFaction;
public SlateRef<bool> mustBeFreeColonist;
public SlateRef<bool> mustBePlayerPrisoner;
public SlateRef<bool> mustBeNotSuspended;
public SlateRef<bool> mustHaveRoyalTitleInCurrentFaction;
public SlateRef<bool> mustBeNonHostileToPlayer;
public SlateRef<bool?> allowPermanentEnemyFaction;
public SlateRef<bool> canGeneratePawn;
public SlateRef<bool> requireResearchedBedroomFurnitureIfRoyal;
public SlateRef<PawnKindDef> mustBeOfKind;
public SlateRef<FloatRange> seniorityRange;
public SlateRef<TechLevel> minTechLevel;
public SlateRef<List<FactionDef>> excludeFactionDefs;
public SlateRef<int> maxUsablePawnsToGenerate = 10;
}
}
|
namespace ShoppingCart.UnitTests
{
public class ProductData
{
public string Name;
public int Price;
public string Sku;
public ProductData(string name, int price, string sku)
{
Sku = sku;
Price = price;
Name = name;
}
public ProductData()
{ }
public override bool Equals(object obj)
{
ProductData pd = (ProductData) obj;
return Name.Equals(pd.Name) && Sku.Equals(pd.Sku) && Price == pd.Price;
}
public override int GetHashCode()
{
return Name.GetHashCode() ^ Sku.GetHashCode() ^ Price.GetHashCode();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Payroll
{
class Employee : WorkPerDay
{
String name;
String id;
public string Name { get => name; set => name = value; }
public string Id { get => id; set => id = value; }
public double SSS = 100;
public double PAG_IBIG = 100;
public double PhilHealth = 100;
public double TotalDeductions()
{
return SSS + PAG_IBIG + PhilHealth;
}
}
}
|
using UnityEngine;
using sugi.cc.data;
using SFB;
using System.IO;
public class LayoutSettingLoader : MonoBehaviour
{
[SerializeField] LayoutSetting layoutSetting;
[SerializeField] private Space space = Space.World;
public void Start()
{
ApplyLayoutSetting();
}
void ApplyLayoutSetting()
{
var objectSettings = layoutSetting.Data.objectSettings;
foreach (var setting in objectSettings)
{
var obj = Instantiate(layoutSetting.PrefabReferences[setting.prefabIdx], transform);
switch (space)
{
case Space.World:
{
obj.transform.position = setting.position;
obj.transform.rotation = setting.rotation;
obj.transform.localScale = setting.scale;
break;
}
case Space.Self:
{
obj.transform.localPosition = setting.position;
obj.transform.localRotation = setting.rotation;
obj.transform.localScale = setting.scale;
break;
}
}
}
}
[ContextMenu("load setting")]
void Load()
{
ApplyLayoutSetting();
}
[ContextMenu("load from file")]
void LoadFile()
{
var filePath = layoutSetting.FilePath;
var directoryName = 0 < filePath.Length ? Path.GetDirectoryName(filePath) : "";
var fileName = 0 < filePath.Length ? Path.GetFileName(filePath) : "";
var extensions = new[]
{
new ExtensionFilter("Json File", "json"),
new ExtensionFilter("All Files", "*")
};
StandaloneFileBrowser.OpenFilePanelAsync(
$"Load {layoutSetting.Data.GetType().Name} JSON", directoryName, extensions, false, (paths) =>
{
if (0 < paths.Length)
{
layoutSetting.Load(paths[0]);
ApplyLayoutSetting();
}
});
}
}
|
using System;
using System.Text.RegularExpressions;
namespace LabTen
{
class Program
{
static void Main(string[] args)
{
bool repeat = false;
int circleCount = 0;
Console.WriteLine("Welcome to the Grand Circus Circle Factory!");
do
{
makeCircle();
circleCount++;
repeat = keepGoing();
} while (repeat == true);
Console.WriteLine($"You created {circleCount} circles today!");
return;
}
static public double Validator(string radius)
{
while (Regex.IsMatch(radius, "([!0-9]*)") == true)
{
Console.Write("Invalid input. Please enter a number: ");
radius = Console.ReadLine();
}
return Convert.ToDouble(radius);
}
static public void makeCircle()
{
string myRadius;
Circle myCircle = new Circle();
do
{
Console.WriteLine("------------------------------------");
Console.Write("Please enter the radius of your circle: ");
myRadius = Console.ReadLine();
Console.WriteLine();
try
{
myCircle.radius = double.Parse(myRadius);
}
catch (FormatException)
{
Console.WriteLine("Invalid input.");
continue;
}
catch (NullReferenceException)
{
Console.WriteLine("Null not allowed.");
continue;
}
catch (ArgumentNullException)
{
Console.WriteLine("Null not allowed.");
continue;
}
} while (double.TryParse(myRadius, out myCircle.radius) == false);
printOutput(myCircle);
}
static public void printOutput(Circle myCircle)
{
Console.WriteLine(myCircle.CalculateFormattedArea(myCircle.radius));
Console.WriteLine(myCircle.CalculateFormattedCircumference(myCircle.radius));
Console.WriteLine();
}
static public bool keepGoing()
{
Console.Write("Would you like to make another circle? Please enter yes or no: ");
string yourChoice = Console.ReadLine().ToLower();
while (!Regex.IsMatch(yourChoice, "(yes)|(y)|(no)|(n)"))
{
Console.Write("Please enter a valid choice, yes or no: ");
yourChoice = Console.ReadLine();
}
if (Regex.IsMatch(yourChoice, "(yes)|(y)"))
{
return true;
}
else
{
return false;
}
}
}
}
|
using System;
using System.Windows.Forms;
namespace QuanLyTiemGiatLa.Danhmuc
{
public partial class frmCTDotGiamGia : Form
{
public OnSaved onsaved;
private TrangThai TrangThai;
public frmCTDotGiamGia()
{
InitializeComponent();
this.Load += new EventHandler(frmCTDotGiamGia_Load);
}
private void frmCTDotGiamGia_Load(object sender, EventArgs e)
{
TrangThai = this.DotGiamGia == null ? TrangThai.Them : TrangThai.Sua;
if (TrangThai == TrangThai.Them)
{
DotGiamGia = new Entity.DotGiamGiaEntity();
dtpTuNgay.Value = DateTime.Now;
dtpDenNgay.Value = DateTime.Now;
}
else
{
txtTenDotGiamGia.Text = DotGiamGia.TenDotGiamGia;
dtpTuNgay.Value = DotGiamGia.TuNgay;
dtpDenNgay.Value = DotGiamGia.DenNgay;
nudGiamGia.Value = DotGiamGia.GiamGia;
}
}
public Entity.DotGiamGiaEntity DotGiamGia { get; set; }
private void btnThoat_Click(object sender, EventArgs e)
{
this.Close();
}
private Boolean CheckForm()
{
txtTenDotGiamGia.Text = txtTenDotGiamGia.Text.Trim();
if (String.IsNullOrEmpty(txtTenDotGiamGia.Text))
{
txtTenDotGiamGia.Focus();
MessageBox.Show("Tên đợt giảm giá trống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
Int32 giamgia;
Int32.TryParse(nudGiamGia.Value.ToString(), out giamgia);
if (giamgia == 0)
{
nudGiamGia.Focus();
MessageBox.Show("Bạn chưa chọn giảm giá", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
if (dtpTuNgay.Value > dtpDenNgay.Value)
{
dtpDenNgay.Focus();
MessageBox.Show("Từ ngày phải nhỏ hơn đến ngày", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
return true;
}
private void btnGhi_Click(object sender, EventArgs e)
{
if (!this.CheckForm()) return;
DotGiamGia.TenDotGiamGia = txtTenDotGiamGia.Text;
DotGiamGia.TuNgay = dtpTuNgay.Value;
DotGiamGia.DenNgay = dtpDenNgay.Value;
DotGiamGia.GiamGia = (Int32)nudGiamGia.Value;
if (TrangThai == TrangThai.Them)
{
DotGiamGia.MaDotGiamGia = Business.DotGiamGiaBO.Insert(DotGiamGia);
onsaved();
this.Close();
}
else
{
Int32 kq = Business.DotGiamGiaBO.Update(DotGiamGia);
onsaved();
this.Close();
}
}
private void txtTenDotGiamGia_KeyDown(object sender, KeyEventArgs e)
{
Xuly.Xuly.ControlFocus(e, dtpTuNgay);
}
private void dtpTuNgay_KeyDown(object sender, KeyEventArgs e)
{
Xuly.Xuly.ControlFocus(e, dtpDenNgay);
}
private void dtpDenNgay_KeyDown(object sender, KeyEventArgs e)
{
Xuly.Xuly.ControlFocus(e, nudGiamGia);
}
private void nudGiamGia_KeyDown(object sender, KeyEventArgs e)
{
Xuly.Xuly.ControlFocus(e, btnGhi);
}
}
}
|
using UnityEngine;
using System.Collections;
public class RegularProjectile : ProjectileController
{
void Awake()
{
ThisTransform = transform;
Damage = 20.0f;
PiercingDamage = 0.0f;
SlowMagnitude = 0.0f;
SlowDuration = 0.0f;
AreaOfEffect = 0.0f;
AreaOfEffectDamage = 0.0f;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.