text stringlengths 13 6.01M |
|---|
using System;
using System.Threading.Tasks;
using MonoTouch.UIKit;
namespace iPadPos
{
public enum CreditCardProcessorType
{
//CardFlight,
Paypal,
PayAnywhere,
}
public abstract class CreditCardProcessor
{
static CreditCardProcessor shared;
public static CreditCardProcessor Shared {
get {
if (shared == null) {
switch (Settings.Shared.CreditCardProcessor) {
// case CreditCardProcessorType.CardFlight:
// shared = new CardFlightProccessor ();
// return shared;
case CreditCardProcessorType.Paypal:
shared = new PaypalProcessor ();
return shared;
case CreditCardProcessorType.PayAnywhere:
shared = new PayAnywhereProcessor ();
return shared;
}
}
return shared;
}
set {
shared = value;
}
}
public CreditCardProcessorType ProcessorType {get;set;}
public abstract Task<Tuple<ChargeDetails,string>> Charge(UIViewController parent, Invoice invoice);
public abstract bool NeedsSignature {get;}
}
}
|
using UnityEngine;
public class TaskAttackWorkers : TaskBase<EntityBat> {
[SerializeField]
private float _workerSpotRange = 5f;
[SerializeField]
private float _attackRate = 1f;
private EntityWorker target;
private float attackTimer;
private NavPath navPath;
public override bool shouldExecute() {
foreach(EntityBase e in this.owner.world.entities.list) {
if(e is EntityWorker) {
if(e.depth == this.owner.depth && Vector2.Distance(e.worldPos, this.owner.worldPos) < this._workerSpotRange) {
NavPath p = this.agent.calculatePath(e.position);
if(p != null) {
this.navPath = p;
this.agent.setPath(p);
this.target = (EntityWorker)e;
return true;
}
}
}
}
return false;
}
public override bool continueExecuting() {
return this.navPath != null && this.target != null && this.target.depth == this.owner.depth;
}
public override void preform() {
// Update the path if the worker moves to a new cell
if(this.target.position != this.navPath.endPoint.position) {
this.navPath = this.agent.calculatePath(this.target.position);
this.agent.setPath(this.navPath);
if(this.navPath != null) {
// The target can no longer be reached. With the
// navPath field being null, the task will end
// next frame.
return;
}
}
if(this.attackTimer > 0) {
this.attackTimer -= Time.deltaTime;
}
if(Vector2.Distance(this.target.worldPos, this.owner.worldPos) < 1f && this.attackTimer <= 0) {
// Attack
// TODO
this.attackTimer = this._attackRate;
}
}
public override void onTaskStop() {
base.onTaskStop();
this.navPath = null;
this.target = null;
this.attackTimer = 0;
}
}
|
using System.Collections.Generic;
namespace XF40Demo.Models
{
public class WindDirectionSensorData
{
public List<CompassPoint> CompassPoints { get; }
public CompassPoint MostCommon { get; internal set; }
public WindDirectionSensorData()
{
CompassPoints = new List<CompassPoint>();
}
public WindDirectionSensorData(List<CompassPoint> points, CompassPoint common)
{
CompassPoints = points;
MostCommon = common;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace MeriMudra.Models
{
[Table("CityGroup")]
public class CityGroup
{
[Key]
public int GroupId { get; set; }
public string GroupName { get; set; }
public string CityIds { get; set; }
}
} |
1. Nalozimo sliko. Ce rezolucija ni 2^N*2^N, dodamo nicle
2. Jemljemo bloke 8x8
3. Od vsakega pixela v bloku odstejemo 128
4. FDCT
for (int u = 0; u < 8; u++)
{
for (int v = 0; v < 8; v++)
{
double c1, c2, vsota = 0;
if (u == 0)
{
c1 = 1/sqrt(2);
}
else
{
c1 = 1;
}
if (v == 0)
{
c2 = 1/sqrt(2);
}
else
{
c2 = 1;
}
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
vsota += slika8x8[x][y] * cos...;
}
}
izhod8x8[u][v] = 0.25 * c1 * c2* vsota;
}
}
5. FAKTOR STISKANJA
6. CIK-CAK
7. DATOTEKA
Dve pravili: |
using System.ComponentModel;
using CommandLine;
using Newtonsoft.Json;
namespace Titan.Bootstrap
{
public class Options
{
[Option('f', "file", Default = "accounts.json", Required = false,
HelpText = "The file containg a list of Steam accounts owning CS:GO that should be used")]
[DefaultValue("accounts.json")]
[JsonProperty("accounts_file", DefaultValueHandling = DefaultValueHandling.Ignore)]
public string AccountsFile { get; set; } = "accounts.json";
[Option('s', "secure", Default = false, Required = false,
HelpText = "If Secure Mode is enabled, all logs in the console like account passwords and Web API key" +
"will be hidden. Use this if you're recording a video or taking a screenshot of Titan.")]
[DefaultValue(false)]
[JsonProperty("secure", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool Secure { get; set; } = false;
[Option('a', "admin", Default = false, Required = false,
HelpText = "Allow administrators to execute this program. This is NOT recommended as it may " +
"cause security issues. (Steam also doesn't allow to be run as root)")]
[DefaultValue(false)]
[JsonProperty("allow_admin", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool AllowAdmin { get; set; } = false;
[Option('g', "nosteamgroup", Default = false, Required = false,
HelpText = "Disables automatic joining of the Titan Report Bot Steam Group")]
[DefaultValue(false)]
[JsonProperty("no_steam_group", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool NoSteamGroup { get; set; } = false;
[Option('b', "noblacklist", Default = false, Required = false,
HelpText = "Disables the Blacklist that is preventing botting of the authors and friend's own bots")]
[DefaultValue(false)]
[JsonProperty("disable_blacklist", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool DisableBlacklist { get; set; } = false;
[Option('k', "steamkitdebug", Default = false, Required = false,
HelpText = "Should SteamKit debug messages be printed?")]
[DefaultValue(false)]
[JsonProperty("steamkit_debug", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool SteamKitDebug { get; set; } = false;
[Option('d', "debug", Default = true, Required = false, Hidden = true,
HelpText = "Should the Titan Debug Mode be enabled?")]
[DefaultValue(true)]
[JsonProperty("debug", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool Debug { get; set; } = true;
}
}
|
using System;
using System.Collections.Generic;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class BondRedeemedEvent : Event
{
public const string NAME = "Bond redeemed";
public const string DESCRIPTION = "Triggered when you redeem a combat bond";
public const string SAMPLE = @"{ ""timestamp"":""2016-12-29T10:10:11Z"", ""event"":""RedeemVoucher"", ""Type"":""CombatBond"",""Amount"":2000,""Factions"":[{""Faction"":""The Pilots Federation"",""Amount"":1000},{""Faction"":""The Dark Wheel"",""Amount"":500},{""Faction"":""Los Chupacabras"",""Amount"":500}]}";
[PublicAPI("The rewards obtained broken down by faction")]
public List<Reward> rewards { get; private set; }
[PublicAPI("The amount rewarded (after any broker fees)")]
public long amount { get; private set; }
[PublicAPI("Broker precentage fee (if paid via a Broker)")]
public decimal? brokerpercentage { get; private set; }
public BondRedeemedEvent(DateTime timestamp, List<Reward> rewards, long amount, decimal? brokerpercentage) : base(timestamp, NAME)
{
this.rewards = rewards;
this.amount = amount;
this.brokerpercentage = brokerpercentage;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Docller.Core.Common;
using Docller.Core.Models;
using Docller.Core.Repository.Collections;
namespace Docller.Core.Repository
{
public interface IProjectRepository:IRepository
{
int Create(string userName, PermissionFlag permissionFlag, Project project, List<Status> defaultStatus);
Project GetProjectDetails(string userName, long projectId);
IEnumerable<Status> GetProjectStatuses(long projectId);
void UpdateProject(Project project);
}
}
|
using System.Threading.Tasks;
namespace Alabo.Framework.Core.Reflections.Interfaces {
/// <summary>
/// 数据一致性检查
/// </summary>
public interface ICheckData {
/// <summary>
/// 同步方法执行数据检查
/// </summary>
void Execute();
/// <summary>
/// 异步方法执行检查
/// </summary>
Task ExcuteAsync();
}
} |
namespace QStore.Tests.QIndexedStringSetTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using QStore.Strings;
using QStore.Tests.Comparers;
using QStore.Tests.Helpers;
[TestClass]
public class GetIndexTests
{
public static void GetIndexTestHelper(IComparer<char> comparer, params string[] strings)
{
var target = QIndexedStringSet.Create(strings, comparer);
var sequenceComparer = new SequenceComparer<char>(comparer);
var expected = strings.OrderBy(s => s, sequenceComparer).ToArray();
for (int i = 0; i < expected.Length; i++)
{
Assert.AreEqual(i, target.GetIndex(expected[i]));
}
}
public static void GetIndexTestHelper(params string[] strings)
{
GetIndexTestHelper(Comparer<char>.Default, strings);
}
[TestMethod]
public void GetIndexEmptySequence()
{
GetIndexTestHelper("aa", "ab", string.Empty);
}
[TestMethod]
public void GetIndexNegative()
{
var target = QIndexedStringSet.Create(new[] { "ba", "bc" }, Comparer<char>.Default);
Assert.AreEqual(~0, target.GetIndex(string.Empty));
Assert.AreEqual(~0, target.GetIndex("aa"));
Assert.AreEqual(~1, target.GetIndex("baa"));
Assert.AreEqual(~1, target.GetIndex("bb"));
Assert.AreEqual(~2, target.GetIndex("bca"));
Assert.AreEqual(~2, target.GetIndex("bd"));
}
[TestMethod]
public void GetIndexNullSequence()
{
const string ParamName = "sequence";
var target = QIndexedStringSet.Create(new[] { "aa", "ab" }, Comparer<char>.Default);
var e = ExceptionAssert.Throws<ArgumentNullException>(() => target.GetIndex(null));
Assert.AreEqual(new ArgumentNullException(ParamName).Message, e.Message);
}
[TestMethod]
public void GetIndexSimple1()
{
GetIndexTestHelper("aa", "ab", "ac", "abc");
}
[TestMethod]
public void GetIndexSimple2()
{
GetIndexTestHelper("one", "two", "three", "four", "five");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms
{
public static class CodilityAuthorityPartners
{
private static int result = 0;
//TODO Fix from 3 to 5
public static int GetStableCycleTimesOfParticles(int[] A)
{
//{ -1, 1, 3, 3, 3, 2, 3, 2, 1, 0 };
if (A.Length < 3)
return result;
var seq1 = A[1] - A[0];
var seq2 = A[2] - A[1];
if (seq1 == seq2)
result++;
result = GetStableCycleTimesOfParticles(A.Skip(2).ToArray());
if (result == 1000000000)
return -1;
return result;
}
//TODO Fix
public static int RepetitionPeriod(int n)
{
int[] d = new int[30];
int l = 0;
int p;
while (n > 0)
{
d[l] = n % 2;
n /= 2;
l++;
}
for (p = 1; p < 1 + l; ++p)
{
int i;
bool ok = true;
for (i = 0; i < l - p; ++i)
{
if (d[i] != d[i + p])
{
ok = false;
break;
}
}
if (ok)
{
return p;
}
}
return -1;
}
public static int GetMinimalWinter(int[] A)
{ //Fix
//new int[] { -5, -5, -5, -42, 6, 12 }
int result = 0;
Array.Sort(A);
int halfLength = A.Length % 2 == 0 ? A.Length / 2 : (A.Length + 1) / 2;
for (int i = 0; i < halfLength; i++)
{
if (A[i] < A[A.Length -1])
result++;
}
if (result == 1000000000)
return -1;
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MartianRobotsService.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MartianRobotsService
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var section = Configuration.GetSection("Settings");
ValidateSection(section.Exists(), "Settings");
services.AddOptions<SettingsOptions>()
.Bind(section)
.ValidateDataAnnotations();
services.AddGrpc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<MartianRobotsCommandService>();
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
});
});
}
private static void ValidateSection(bool sectionExists, string sectionName)
{
if (!sectionExists)
{
throw new Exception(sectionName);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace workshop.FactoryMethod
{
public interface IAreaCalculator { }
public class CircleAreaCalculator : IAreaCalculator { }
public class RectangleAreaCalculator : IAreaCalculator { }
public class SlotAreaCalculator : IAreaCalculator { }
public abstract class AreaUpdater
{
public abstract IAreaCalculator CreateAreaCalculator();
public void UpdateSomeValues()
{
var calculator = CreateAreaCalculator();
//some operations
}
}
public class CircleCalculatorFactory : AreaUpdater
{
public override IAreaCalculator CreateAreaCalculator()
{
return new CircleAreaCalculator();
}
}
public class RectangleCalculatorFactory : AreaUpdater
{
public override IAreaCalculator CreateAreaCalculator()
{
return new RectangleAreaCalculator();
}
}
public class SlotCalculatorFactory : AreaUpdater
{
public override IAreaCalculator CreateAreaCalculator()
{
return new SlotAreaCalculator();
}
}
}
|
using System;
using System.Linq;
using System.DirectoryServices.AccountManagement;
namespace MemLeaker
{
/// <summary>
/// One of the un-managed memory leaks is fixed.
/// Application still leaks a lot of memory.
/// Use the mem profiler to see what's going on:
/// - Enable native code debugging for this project
/// - Enable Heap profiling in the mem profile
/// - Go to the native mem profile and disable the Hide unresolved allocations filter
/// - See what is causing the leaks
/// </summary>
class AdLeak3
{
private PrincipalContext _context;
public void Execute()
{
using (_context = new PrincipalContext(ContextType.Domain, Program.AdDomain))
{
var groupName = GetGroup(Program.AdGroupName);
Console.WriteLine($"{groupName}");
}
}
private string GetGroup(string groupName)
{
var group = GroupPrincipal.FindByIdentity(_context, groupName);
var members = group.Members.Where(s => s is UserPrincipal).Select(s => s.SamAccountName).Aggregate((a, b) => $"{a},{b}");
Console.WriteLine(members);
return group.Name;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;
using System.Management;
namespace IRAP.Global
{
public class RDPClientIP
{
[DllImport("wtsapi32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool WTSEnumerateSessions(
int hServer,
int Reserved,
int Version,
ref long ppSessionInfo,
ref int pCount);
[DllImport("wtsapi32")]
public static extern void WTSFreeMemory(IntPtr pMemory);
[DllImport("wtsapi32")]
public static extern bool WTSLogoffSession(
int hServer,
long SessionId,
bool bWait);
[DllImport("wtsapi32")]
public static extern bool WTSQuerySessionInformation(
IntPtr hServer,
int sessionId,
WTSInfoClass wtsInfoClass,
out IntPtr ppBuffer,
out uint pBytesReturned);
[DllImport("wtsapi32.dll")]
public static extern bool WTSQuerySessionInformation(
IntPtr hServer,
int sessionId,
WTSInfoClass wtsInfoClass,
out StringBuilder ppBuffer,
out uint pBytesReturned);
[DllImport("kernel32")]
public static extern bool ProcessIdToSessionId(
uint dwProcessId,
ref uint pSessionId);
[DllImport("kernel32")]
public static extern uint GetCurrentProcessId();
public enum WTSInfoClass
{
WTSInitialProgram,
WTSApplicationName,
WTSWorkingDirectory,
WTSOEMId,
WTSSessionId,
WTSUserName,
WTSWinStationName,
WTSDomainName,
WTSConnectState,
WTSClientBuildNumber,
WTSClientName,
WTSClientDirectory,
WTSClientProductId,
WTSClientHardwareId,
WTSClientAddress,
WTSClientDisplay,
WTSClientProtocolType,
}
/// <summary>
/// The WTS_CONNECTSTATE_CLASS enumeration type contains INT values
/// that indicate the connection state of a Terminal Services session.
/// </summary>
public enum WTS_CONNECTSTATE_CLASS
{
WTSActive,
WTSConnected,
WTSConnectQuery,
WTSShadown,
WTSDisconnected,
WTSIdle,
WTSListen,
WTSReset,
WTSDown,
WTSInit,
}
/// <summary>
/// The WTS_SESSION_INFO structure contains information about a client
/// session on a terminal server. If the WTS_SESSION_INFO.SessionID == 0,
/// it means that the SESSION is the local logon user's session.
/// </summary>
public struct WTS_SESSION_INFO
{
public int SessionID;
[MarshalAs(UnmanagedType.LPTStr)]
public string WinStationName;
public WTS_CONNECTSTATE_CLASS State;
}
/// <summary>
/// The SessionEnumeration function retrieves a list of WTS_SESSION_INFO
/// on a current terminal server.
/// </summary>
/// <returns>a list of WTS_SESSION_INFO o a current terminal server</returns>
public static WTS_SESSION_INFO[] SessionEnumeration()
{
// Set handle of terminal server as the current terminal server
int hServer = 0;
bool retVal;
long lpBuffer = 0;
int count = 0;
long p;
WTS_SESSION_INFO session_Info = new WTS_SESSION_INFO();
WTS_SESSION_INFO[] arrSessionInfo;
retVal = WTSEnumerateSessions(hServer, 0, 1, ref lpBuffer, ref count);
arrSessionInfo = new WTS_SESSION_INFO[0];
if (retVal)
{
arrSessionInfo = new WTS_SESSION_INFO[count];
p = lpBuffer;
for (int i = 0; i < count; i++)
{
arrSessionInfo[i] =
(WTS_SESSION_INFO)Marshal.PtrToStructure(
new IntPtr(p),
session_Info.GetType());
p += Marshal.SizeOf(session_Info.GetType());
}
WTSFreeMemory(new IntPtr(lpBuffer));
}
else
{
// Insert Error Reactive Here
}
return arrSessionInfo;
}
#region Structures
/// <summary>
/// Structure for Terminal Service Client IP Address
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct WTS_CLIENT_ADDRESS
{
public int AddressFamily;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public byte[] Address;
}
/// <summary>
/// Structre for Terminal Service Session Client Display
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct WTS_CLIENT_DISPLAY
{
public int HorizontalResolution;
public int VerticalResolution;
/// <summary>
/// 1 - The display uses 4 bits per pixel for a maximum of 16 colors.
/// 2 - The display uses 8 bits per pixel for a maximum of 256 colors.
/// 4 - The display uses 16 bits per pixel for a maximum of 2^16 colors.
/// 8 - The display uses 3-byte RGB values for a maximum of 2^24 colors.
/// 16 - The display uses 15 bits per pixel for a maximum of 2^15 colors.
/// </summary>
public int ColorDepth;
}
#endregion
}
public class RDPClientMAC
{
[DllImport("iphlpapi.dll")]
private static extern int SendARP(
Int32 DestIP,
Int32 SrcIP,
ref Int64 MacAddr,
ref Int32 PhyAddrLen);
[DllImport("ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
public static string GetRDPMacAddress()
{
RDPClientIP.WTS_SESSION_INFO[] pSessionInfo = RDPClientIP.SessionEnumeration();
try
{
uint count = 0;
uint count2 = 0;
IntPtr buffer = IntPtr.Zero;
uint id = RDPClientIP.GetCurrentProcessId();
uint sessionID = 0;
RDPClientIP.ProcessIdToSessionId(id, ref sessionID);
IntPtr sb = IntPtr.Zero;
StringBuilder outBuffer = new StringBuilder();
string sIPAddress = string.Empty;
RDPClientIP.WTS_CLIENT_ADDRESS oClientAddress = new RDPClientIP.WTS_CLIENT_ADDRESS();
bool dwRet =
RDPClientIP.WTSQuerySessionInformation(
IntPtr.Zero,
(int)sessionID,
RDPClientIP.WTSInfoClass.WTSClientName,
out outBuffer,
out count2);
if (dwRet == true && count2 > 3)
{
bool bsuccess =
RDPClientIP.WTSQuerySessionInformation(
IntPtr.Zero,
(int)sessionID,
RDPClientIP.WTSInfoClass.WTSClientAddress,
out sb,
out count);
if (bsuccess)
{
oClientAddress =
(RDPClientIP.WTS_CLIENT_ADDRESS)Marshal.PtrToStructure(
sb,
oClientAddress.GetType());
sIPAddress =
string.Format(
"{0}.{1}.{2}.{3}",
oClientAddress.Address[2],
oClientAddress.Address[3],
oClientAddress.Address[4],
oClientAddress.Address[5]);
string mac = RDPClientMAC.GetMacBySendARP(sIPAddress);
return mac;
}
else
{
return "FFFFFFFFFFFF";
}
}
else
{
string mac = GetLocalMac2();
return mac;
}
}
catch (Exception err)
{
return "FFFFFFFFFFFF";
}
}
/// <summary>
/// SendARP 获取 MAC 地址
/// </summary>
/// <param name="remoteIP"></param>
/// <returns></returns>
public static string GetMacBySendARP(string remoteIP)
{
StringBuilder macAddress = new StringBuilder();
try
{
Int32 remote = inet_addr(remoteIP);
Int64 macInfo = new long();
Int32 length = 6;
SendARP(remote, 0, ref macInfo, ref length);
string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
int x = 12;
for (int i = 0; i < 6; i++)
{
if (i == 5)
{
macAddress.Append(temp.Substring(x - 2, 2));
}
else
{
macAddress.Append(temp.Substring(x - 2, 2) + "");
}
x -= 2;
}
return macAddress.ToString();
}
catch
{
return macAddress.ToString();
}
}
public static string GetLocalMac()
{
// 通过硬件接口获取,即使不联网
List<string> macs = new List<string>();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
macs.Add(ni.GetPhysicalAddress().ToString());
}
StringBuilder res = new StringBuilder();
foreach (string item in macs)
{
if (item.Trim() != string.Empty)
{
res.Append(item + ";");
}
}
return res.Remove(res.Length - 1, 1).ToString();
}
public static string GetLocalMac2()
{
List<string> macs = new List<string>();
try
{
string mac = "";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
mac = mo["MacAddress"].ToString();
string[] addresses = (string[])mo["IPAddress"];
macs.Add(mac);
}
}
moc = null;
mc = null;
}
catch
{
return "FFFFFFFFFFFF";
}
StringBuilder res = new StringBuilder();
foreach (string item in macs)
{
res.Append(item.Replace(":", "") + ";");
}
return res.Remove(res.Length - 1, 1).ToString();
}
}
} |
<Query Kind="Program">
<NuGetReference>morelinq</NuGetReference>
</Query>
/*
Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys.
To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes.
The input to the MD5 hash is some secret key (your puzzle input, given below) followed by a number in decimal.
To mine AdventCoins, you must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) that produces such a hash.
For example:
If your secret key is abcdef, the answer is 609043, because the MD5 hash of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the lowest such number to do so.
If your secret key is pqrstuv, the lowest number it combines with to make an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of pqrstuv1048970 looks like 000006136ef....
Your puzzle input is ckczppom.
*/
void Main()
{
var secretKey = "ckczppom";
var md5 = System.Security.Cryptography.MD5.Create();
var q = from n in Enumerable.Range(1, 10000000)
let inputString = $"{secretKey}{n}"
let inputBytes = System.Text.Encoding.ASCII.GetBytes(inputString)
let hashBytes = md5.ComputeHash(inputBytes)
let hashString = BitConverter.ToString(hashBytes).Replace("-","")
where hashString.StartsWith("00000")
select new {n, hashString};
q.FirstOrDefault().Dump();
}
// Define other methods and classes here
|
using System;
using System.Collections.Generic;
namespace BSMU_Schedule.Entities
{
[Serializable]
public class WeekSchedule
{
public WeekSchedule()
{
}
public WeekSchedule(int weekNumber, List<DaySchedule> daySchedules)
{
DaySchedules = daySchedules;
WeekNumber = weekNumber;
}
public List<DaySchedule> DaySchedules { get; set; }
public int WeekNumber { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace NumbersToWords
{
public class TensConverter : ITensConverter
{
public string ConvertTensToWords(int input)
{
var tensMap = new[] { "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninty" };
return tensMap[input / 10 - 2];
}
}
}
|
using UnityEngine;
using System.Collections;
public class SensorController : MonoBehaviour {
private Animator animator;
void Awake() {
animator = this.GetComponent<Animator>();
}
void OnTriggerEnter2D(Collider2D collider) {
if (collider.gameObject.layer == LayerMask.NameToLayer("Character"))
animator.SetTrigger("activate");
}
}
|
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Models.DTO
{
[Serializable]
public class Challenge
{
[XmlAttribute("id")]
public int Id;
[XmlArray("Names")]
public GenderName[] Names;
public string Description;
[XmlElement("Image")]
public Image ImageUri;
public ChallengeCategoryEnum Category;
public ChallengeRequirements BasicRequirements;
public ChallengeRequirements ExtraRequirements;
public List<ChallengeTask> BasicTasks;
public List<ChallengeTask> ExtraTasks;
}
[Serializable]
public struct ChallengeCategory
{
[XmlElement("Name")]
public ChallengeCategoryEnum Enum;
[XmlAttribute("id")]
public int Id;
}
[Serializable]
public class Image : IXmlSerializable
{
public string Uri;
public string LocalPath;
public Image()
{
}
public Image(string uriString, string localPath = null)
{
Uri = uriString;
LocalPath = localPath;
}
public XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(XmlReader reader)
{
Uri = reader.GetAttribute("uri");
LocalPath = reader.GetAttribute("localPath");
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("uri", Uri);
writer.WriteAttributeString("localPath", LocalPath);
}
}
[Serializable]
public enum ChallengeCategoryEnum
{
Art,
Technology,
Camping,
Social,
NaturalScience,
Watering,
Service,
Sports,
Religion,
Scouting
}
[Serializable]
public struct GenderName
{
[XmlText]
public string Name;
[XmlAttribute("gender")]
public Gender Gender;
}
[Serializable]
public enum Gender
{
Male, Female
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TomKlonowski.Api.Data.Repository;
using TomKlonowski.Model;
namespace TomKlonowski.Api.Business
{
public class BlogManager : IBlogManager
{
IBlogRepository _BlogRepository = null;
public BlogManager(IBlogRepository blogRepository)
{
this._BlogRepository = blogRepository;
}
public IEnumerable<Blog> GetBlogs()
{
return this._BlogRepository.GetBlogs();
}
public Blog GetBlog(int blogId)
{
return this._BlogRepository.GetBlog(blogId);
}
public Blog CreateBlog(Blog newBlog)
{
newBlog.CreatedDate = DateTime.Now;
return this._BlogRepository.CreateBlog(newBlog);
}
public Blog UpdateBlog(Blog updatedBlog)
{
return this._BlogRepository.UpdateBlog(updatedBlog);
}
public void DeleteBlog(int blogId)
{
this._BlogRepository.DelteBlog(blogId);
}
}
}
|
namespace MicroBatchFramework
{
public abstract class BatchBase
{
public BatchContext Context { get; set; }
}
}
|
using System;
namespace Moolah
{
/// <summary>
/// Allows me to mock time. Muwhahaha
/// </summary>
public static class SystemTime
{
private static Func<DateTime> _now = () => DateTime.Now;
public static DateTime Now
{
get { return _now(); }
set { _now = () => value; }
}
public static void Reset()
{
_now = () => DateTime.Now;
}
}
} |
namespace M220N.Models
{
public class Credentials
{
private string Password { get; set; }
private string Email { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _001_BOOLEAN
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите число А");
int number_A = Convert.ToInt32(Console.ReadLine());
bool value = number_A > 0;
Console.WriteLine("Число {0} является положительным - {1}",
number_A, value);
}
}
}
|
namespace Sentry.Extensibility;
/// <summary>
/// Process a SentryEvent during the prepare phase.
/// </summary>
public interface ISentryEventProcessorWithHint: ISentryEventProcessor
{
/// <summary>
/// Process the <see cref="SentryEvent"/>
/// </summary>
/// <param name="event">The event to process</param>
/// <param name="hint">A <see cref="Hint"/> with context that may be useful prior to sending the event</param>
/// <return>The processed event or <c>null</c> if the event was dropped.</return>
/// <remarks>
/// The event returned can be the same instance received or a new one.
/// Returning null will stop the processing pipeline so that the event will neither be processed by
/// additional event processors or sent to Sentry.
/// </remarks>
SentryEvent? Process(SentryEvent @event, Hint hint);
}
|
/* The MIT License (MIT)
*
* Copyright (c) 2018 Marc Clifton
*
* 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.
*/
/* Code Project Open License (CPOL) 1.02
* https://www.codeproject.com/info/cpol10.aspx
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Clifton.Core.ExtensionMethods;
using Clifton.Core.Assertions;
namespace Clifton.Meaning
{
public class ContextValueDictionary
{
// TODO: Workaround for right now as we're testing a single session.
// TODO: Remove this eventually, saving the cvd when the session terminates or some other mechanism.
public static ContextValueDictionary CVD;
public ContextNode Root { get { return tree; } }
public Dictionary<Type, List<ContextNode>> FlatView { get { return flatView; } }
protected ContextNode tree = ContextNode.Root;
// TODO: Probably should be a concurrent dictionary, but we may need to lock the walking of the tree as we are modifying it as we're walking.
protected Dictionary<Type, List<ContextNode>> flatView = new Dictionary<Type, List<ContextNode>>();
public ContextValueDictionary()
{
// TODO: What we load should be specific to the user and their session.
Load();
CVD = this; // TODO: Remove this eventually, saving the cvd when the session terminates or some other mechanism.
}
public void Clear()
{
tree.Clear();
flatView.Clear();
}
public void Save()
{
// https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
var settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
settings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
settings.TypeNameHandling = TypeNameHandling.Auto;
settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
settings.ObjectCreationHandling = ObjectCreationHandling.Auto;
string jsonTree = JsonConvert.SerializeObject(tree, settings);
string jsonFlatView = JsonConvert.SerializeObject(flatView, settings);
File.WriteAllText("tree.cvd", jsonTree);
File.WriteAllText("flatView.cvd", jsonFlatView);
}
public void Load()
{
// https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
var settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
settings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
settings.TypeNameHandling = TypeNameHandling.Auto;
settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
settings.ObjectCreationHandling = ObjectCreationHandling.Auto;
if (File.Exists("tree.cvd"))
{
string jsonTree = File.ReadAllText("tree.cvd");
tree = JsonConvert.DeserializeObject<ContextNode>(jsonTree, settings);
}
if (File.Exists("flatView.cvd"))
{
string jsonFlatView = File.ReadAllText("flatView.cvd");
flatView = JsonConvert.DeserializeObject<Dictionary<Type, List<ContextNode>>>(jsonFlatView, settings);
}
}
public ContextValue CreateValue<T1>(Parser parser, string val, int recordNumber = 0)
{
return CreateContextValue(parser, val, recordNumber, typeof(T1));
}
public ContextValue CreateValue<T1, T2>(Parser parser, string val, int recordNumber = 0)
{
return CreateContextValue(parser, val, recordNumber, typeof(T1), typeof(T2));
}
public ContextValue CreateValue<T1, T2, T3>(Parser parser, string val, int recordNumber = 0)
{
return CreateContextValue(parser, val, recordNumber, typeof(T1), typeof(T2), typeof(T3));
}
public ContextValue CreateValue<T1, T2, T3, T4>(Parser parser, string val, int recordNumber = 0)
{
return CreateContextValue(parser, val, recordNumber, typeof(T1), typeof(T2), typeof(T3), typeof(T4));
}
public ContextValue CreateValue<T1, T2, T3, T4, T5>(Parser parser, string val, int recordNumber = 0)
{
return CreateContextValue(parser, val, recordNumber, typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5));
}
public ContextValue CreateValue<T1, T2, T3, T4, T5, T6>(Parser parser, string val, int recordNumber = 0)
{
return CreateContextValue(parser, val, recordNumber, typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6));
}
public IReadOnlyList<ContextNode> GetContextNodes(Type contextType)
{
List<ContextNode> nodes;
if (!FlatView.TryGetValue(contextType, out nodes))
{
nodes = new List<ContextNode>();
}
return nodes.AsReadOnly();
}
public IReadOnlyList<ContextValue> GetContextValues(ContextNode node)
{
List<ContextValue> contextValues = new List<ContextValue>();
GetContextValues(contextValues, node);
return contextValues.AsReadOnly();
}
protected void GetContextValues(List<ContextValue> contextValues, ContextNode node)
{
foreach (var child in node.Children)
{
GetContextValues(contextValues, child);
if (child.ContextValue != null)
{
contextValues.Add(child.ContextValue);
}
}
}
/// <summary>
/// Give a child node, returns the full path, starting from the topmost node, of the node hierarchy.
/// </summary>
public ContextNodePath GetPath(ContextNode node)
{
// A LINQ way of traversing the tree to its root. Seems more complicated than the approach here.
// https://stackoverflow.com/questions/34741456/linq-traverse-upwards-and-retrieve-parent-child-relationship
// Also an interesting read:
// https://www.codeproject.com/Articles/62397/LINQ-to-Tree-A-Generic-Technique-for-Querying-Tree
Type rootType = node.Type;
Guid rootGuid = node.InstanceId;
List<NodeTypeInstance> path = new List<NodeTypeInstance>() { new NodeTypeInstance() { Type = node.Type, InstanceId = node.InstanceId } };
var parent = node.Parent;
while (parent != null && parent.InstanceId != Guid.Empty)
{
rootType = parent.Type;
rootGuid = parent.InstanceId;
path.Insert(0, new NodeTypeInstance() { Type = parent.Type, InstanceId = parent.InstanceId });
parent = parent.Parent;
}
var match = new ContextNodePath() { Type = rootType, Name = rootType.Name, Path = path };
return match;
}
public bool TryGetContextNode(Field field, Guid rootId, int recordNumber, out ContextNode node, out List<Guid> instanceIdPath)
{
instanceIdPath = new List<Guid>();
instanceIdPath.Add(rootId);
ContextNode dictNode = tree.Children.Single(c => c.InstanceId == rootId);
// Traverse the dictionary up to the node containing the ContextValue.
// We traverse by type, building the instance ID list as we go.
for (int i = 1; i < (field.ContextPath.Count - 1) && dictNode != null; i++)
{
dictNode = dictNode.Children.SingleOrDefault(c => c.Type == field.ContextPath[i].Type);
if (dictNode != null)
{
instanceIdPath.Add(dictNode.InstanceId);
}
}
if (dictNode != null)
{
// Acquire the ContextValue based on field type and record number.
dictNode = dictNode.Children.SingleOrDefault(c => c.Type == field.ContextPath[field.ContextPath.Count - 1].Type && c.ContextValue.RecordNumber == recordNumber);
if (dictNode != null)
{
instanceIdPath.Add(dictNode.InstanceId);
}
}
node = dictNode;
return node != null;
}
public Type GetRootType(Guid rootId)
{
ContextNode dictNode = tree.Children.Single(c => c.InstanceId == rootId);
Type rootType = dictNode.Type;
return rootType;
}
public void AddOrUpdate(ContextValue cv)
{
// We have to process this synchronously!
// If async, we might get simultaneous requests (particularly from the browser's async PUT calls) to add a value.
// While we're constructing the dictionary entry for one context path, another request might come in before we've
// created all the nodes for the first call.
lock (this)
{
// Walk the instance/path, creating new nodes in the context tree as required.
Assert.That(cv.TypePath.Count == cv.InstancePath.Count, "type path and instance path should have the same number of entries.");
ContextNode node = tree;
for (int i = 0; i < cv.TypePath.Count; i++)
{
// Walk the tree.
var (id, type) = (cv.InstancePath[i], cv.TypePath[i]);
if (node.Children.TryGetSingle(c => c.InstanceId == id, out ContextNode childNode))
{
node = childNode;
}
else
{
// Are we referencing an existing sub-context?
if (flatView.TryGetValue(type, out List<ContextNode> nodes))
{
// The instance path of the node must match all the remaining instance paths in the context
// we're adding/updating!
bool foundExistingSubContext = false;
foreach (var fvnode in nodes)
{
foreach (var fvnodepath in fvnode.ChildInstancePaths())
{
if (cv.InstancePath.Skip(i).SequenceEqual(fvnodepath))
{
// This node get's a child referencing the existing sub-context node.
node.AddChild(fvnode);
node = fvnode;
foundExistingSubContext = true;
break;
}
}
if (foundExistingSubContext)
{
break;
}
}
if (!foundExistingSubContext)
{
node = CreateNode(i, id, cv, node, type);
}
}
else
{
node = CreateNode(i, id, cv, node, type);
}
}
}
// The last entry in the tree gets the actual context value. We've either added this node to the tree
// or updating an existing node.
node.ContextValue = cv;
}
}
protected ContextNode CreateNode(int i, Guid id, ContextValue cv, ContextNode node, Type type)
{
if (i == cv.TypePath.Count - 1)
{
// At this point, node.Children[].Type && node.Children[].ContextValue.RecordNumber must be unique!
Assert.That<ContextValueDictionaryException>(!node.Children.Any(c => c.Type == type && c.ContextValue.RecordNumber == cv.RecordNumber), "ContextValue type and record number must be unique to parent context.");
}
ContextNode childNode = new ContextNode(id, type);
node.AddChild(childNode);
// Since we're creating a node, add it to the flat tree view.
if (!flatView.TryGetValue(type, out List<ContextNode> nodes))
{
flatView[type] = new List<ContextNode>();
}
flatView[type].Add(childNode);
return childNode;
}
public List<ContextNode> Search(params ContextValue[] contextValuesToSearch)
{
return Search(contextValuesToSearch.ToList());
}
/// <summary>
/// Returns the common context whose field values match the search values.
/// The children of the context nodes that are returned are either IValueEntity's that match
/// or (when implemented) will be sub-contexts that will match a separate context path IValueEntity.
/// </summary>
public List<ContextNode> Search(List<ContextValue> contextValuesToSearch)
{
// For now the parent type of each value must be the same, as the values (for now) cannot span group containers.
// What we could do is collect all the unique parent group containers and find matches for those containers. The parent group
// must then be common for the super-parent to qualify the shared container. This gets complicated when the matches are found
// at different levels of the tree.
Assert.That(contextValuesToSearch.Count > 0, "At least one ContextValue instance must be passed in to Search.");
int pathItems = contextValuesToSearch[0].InstancePath.Count;
Assert.That(contextValuesToSearch.All(cv => cv.InstancePath.Count == pathItems), "Context values must have the same path length for now.");
// Make sure the parent types of all context values (the second to last entry in the TypePath) are the same.
var parentTypes = contextValuesToSearch.Select(cv => cv.TypePath.Reverse().Skip(1).Take(1).First()).DistinctBy(cv => cv.AssemblyQualifiedName);
Assert.That(parentTypes.Count() == 1, "Expected all context values to have the same field-parent.");
// Get the parent type shared by the fields.
Type parentType = parentTypes.Single();
// Find this parent type in the dictionary of context values.
// We can find this parent type anywhere in the tree of any context value type path.
List<ContextNode> matches = new List<ContextNode>();
if (flatView.TryGetValue(parentType, out List<ContextNode> nodesOfParentType))
{
// Now compare the values in children of the context who's parent types match.
foreach (var parentNode in nodesOfParentType)
{
bool match = true;
// Handle multiple records at the last node which is the ContextValue holder.
var recordNumbers = parentNode.Children.Select(c => c.ContextValue.RecordNumber).Distinct();
foreach (int recNum in recordNumbers)
{
foreach (var cv in contextValuesToSearch)
{
Assert.That<ContextValueDictionaryException>(parentNode.Children.All(c => c.ContextValue != null), "Expected a ContextValue assigned to all children of the last context.");
var childMatch = parentNode.Children.SingleOrDefault(c => c.Type == cv.TypePath.Last() && c.ContextValue.RecordNumber == recNum);
Assert.That(childMatch != null, "A child matching the type and record number was expected.");
match = childMatch.ContextValue.Value == cv.Value;
if (!match)
{
break;
}
}
if (match)
{
matches.Add(parentNode);
}
}
}
}
MatchWithContextsReferencingSubContext(matches);
return matches;
}
protected void MatchWithContextsReferencingSubContext(List<ContextNode> matches)
{
// For each match, see if there are other super-contexts that reference this same matching context.
// If so, these should be added to the list of matches.
// TODO: Would this be easier if we change ContextNode.Parent from a singleton to a List<ContextNode> ?
// Clone, otherwise we may end up modifying the list of known matches.
foreach (ContextNode match in matches.ToList())
{
List<Guid> matchParentPath = match.GetParentInstancePath();
// We only want root contexts.
foreach (var nodes in flatView.Values.Where(n=>n.Last().Parent.InstanceId == Guid.Empty))
{
ContextNode lastNode = nodes.Last();
foreach (var childNodeIdPath in lastNode.ChildInstancePaths())
{
// We attempt to find a node where any sub-context ID equals the match last ID, as this gives us at least
// one context node in which we know that there is another reference.
// This, incidentally, is the common context type that we're searching on.
if (childNodeIdPath.Any(id => id == match.InstanceId))
{
// The root instance ID for this match should be different than any existing match.
if (!matches.Any(m => m.GetParentInstancePath().First() == nodes.First().InstanceId))
{
// Add this other context, that is referencing the context we matched on.
matches.Add(lastNode);
}
}
}
}
}
}
/// <summary>
/// Find the matching context path that results in a single field.
/// </summary>
protected ContextValue CreateContextValue(Parser parser, string val, int recordNumber, params Type[] types)
{
ContextValue cv = parser.CreateContextValue(val, recordNumber, types);
AddOrUpdate(cv);
return cv;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Laoziwubo.IDAL
{
public interface IHeroD<T> : IDisposable
{
bool Insert(T model);
}
}
|
using System.Collections.Generic;
using Kliiko.Ui.Tests.WebPages.StaticPages;
using OpenQA.Selenium;
namespace Kliiko.Ui.Tests.WebPages.LoggedPages
{
class AccountManagerPage : WebPage
{
private static readonly By TabAccountManeger = By.XPath(".//*[@id='nav-tabs-main']/li[1]/a");
private static readonly By TabAccountParticipant = By.XPath(".//*[@id='nav-tabs-main']/li[2]/a");
private static readonly By TableHeaderAccountName = By.XPath("html/body/main/div/div[2]/div/div/div/div/div/div/table/thead/tr/th[1]");
private static readonly By TableHeaderFirstName = By.XPath("html/body/main/div/div[2]/div/div/div/div/div/div/table/thead/tr/th[2]");
private static readonly By TableHeaderLastName = By.XPath("html/body/main/div/div[2]/div/div/div/div/div/div/table/thead/tr/th[3]");
private static readonly By TableCellAccountName = By.XPath("html/body/main/div/div[2]/div/div/div/div/div/div/table/tbody/tr/td[1]");
private static readonly By TableCellFirstName = By.XPath("html/body/main/div/div[2]/div/div/div/div/div/div/table/tbody/tr/td[2]");
private static readonly By TableCellLastName = By.XPath("html/body/main/div/div[2]/div/div/div/div/div/div/table/tbody/tr/td[3]");
private static readonly By IconSelectUser =
By.XPath("html/body/main/div/div[2]/div/div/div/div/div/div/table/tbody/tr/td[4]/a/span");
private static readonly By ButtonLogOut = By.CssSelector(".btn-header-red");
private static readonly IList<By> ListLocators = new List<By>();
private static void FillListLocators()
{
ListLocators.Add(TabAccountManeger);
ListLocators.Add(TabAccountParticipant);
ListLocators.Add(TableHeaderAccountName);
ListLocators.Add(TableHeaderFirstName);
ListLocators.Add(TableHeaderLastName);
ListLocators.Add(TableCellAccountName);
ListLocators.Add(TableCellFirstName);
ListLocators.Add(TableCellLastName);
ListLocators.Add(IconSelectUser);
ListLocators.Add(ButtonLogOut);
}
public static void ExpectWebElements()
{
if (ListLocators.Count == 0)
{
FillListLocators();
}
Web.ExpectWebElements(ListLocators);
HeaderBlock.ExpectedWebElementsNotLogged();
FooterBlock.ExpectedWebElements();
}
public static string GetAccountName()
{
return Web.GetLocatorText(TableCellAccountName);
}
public static void ClickIconPlay()
{
Web.Click(IconSelectUser);
}
}
}
|
using System;
using Fingo.Auth.Domain.Infrastructure.EventBus.Events.Base;
namespace Fingo.Auth.Domain.Infrastructure.EventBus.Interfaces
{
public interface ISubscription
{
Type SubscriptionType { get; }
void Publish(EventBase eventItem);
}
} |
using Forca.Classes;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Forca.Services
{
class PalpiteService
{
public ForcaContext _FContext { get; private set; }
public Palpite _Palpite { get; private set; }
public PalpiteService(ForcaContext FContext, Palpite Palpite)
{
_FContext = FContext;
_Palpite = Palpite;
}
public void Cadastrar()
{
_FContext.Palpite.AddOrUpdate<Palpite>(_Palpite);
_FContext.SaveChanges();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TrainEngine
{
public class TrackORM
{
public TrackDescription ParseTrackDescription(string track)
{
// The stations placement eg: [1]
// The start station: *
// Tracks: -, / and \
// Railroad switches: < and >
// Level crossing (vägbom): =
throw new NotImplementedException();
}
}
}
|
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace SpritePackerOverview
{
public class SpritePackerOverviewWindow : EditorWindow
{
[MenuItem("Window/Sprite Packer Overview")]
static void ShowWindow()
{
GetWindow<SpritePackerOverviewWindow>();
}
private class OverviewWindowStyle
{
public static readonly GUIContent packLabel = new GUIContent("Pack");
public static readonly GUIContent repackLabel = new GUIContent("Repack");
public static readonly GUIContent viewAtlasLabel = new GUIContent("View Atlas:");
public static readonly GUIContent windowTitle = new GUIContent("Sprite Packer Overview");
public static readonly GUIContent pageContentLabel = new GUIContent("Page {0}");
public static readonly GUIContent packingDisabledLabel =
new GUIContent("Legacy sprite packing is disabled. Enable it in Edit > Project Settings > Editor.");
}
private SearchField m_SearchField;
[SerializeField] private TreeViewState m_TreeViewState;
[SerializeField] private MultiColumnHeaderState m_MultiColumnHeaderState;
private SpritePackerOverviewTreeView m_TreeView;
private SpritePackerOverviewTreeModel m_TreeModel;
private void Awake()
{
minSize = new Vector2(400f, 256f);
titleContent = OverviewWindowStyle.windowTitle;
}
private bool ValidateIsPackingEnabled()
{
if (EditorSettings.spritePackerMode != SpritePackerMode.BuildTimeOnly
&& EditorSettings.spritePackerMode != SpritePackerMode.AlwaysOn)
{
EditorGUILayout.BeginVertical();
GUILayout.Label(OverviewWindowStyle.packingDisabledLabel);
EditorGUILayout.EndVertical();
return false;
}
return true;
}
private void OnGUI()
{
if (!ValidateIsPackingEnabled())
{
return;
}
InitIfNeeded();
DrawToolbar();
if (m_TreeModel.IsEmpty())
{
ShowNotification(new GUIContent("Please pack first"));
}
else
{
DrawTreeView();
}
}
private void DrawToolbar()
{
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
if (GUILayout.Button("Refresh", EditorStyles.toolbarButton, GUILayout.Width(50f)))
{
Refresh();
}
if (!m_TreeModel.IsEmpty())
{
m_TreeView.searchString = m_SearchField.OnToolbarGUI(m_TreeView.searchString);
}
EditorGUILayout.EndHorizontal();
}
private void DrawTreeView()
{
Rect rect = GUILayoutUtility.GetRect(0, 100000, 0, 100000);
m_TreeView.OnGUI(rect);
}
private void InitIfNeeded()
{
if (m_SearchField != null)
{
return;
}
bool firstInit = m_MultiColumnHeaderState == null;
var headerState = CreateMultiColumnHeader();
if (MultiColumnHeaderState.CanOverwriteSerializedFields(m_MultiColumnHeaderState, headerState))
{
MultiColumnHeaderState.OverwriteSerializedFields(m_MultiColumnHeaderState, headerState);
}
m_MultiColumnHeaderState = headerState;
var multiColumnHeader = new MultiColumnHeader(headerState);
if (firstInit)
{
multiColumnHeader.ResizeToFit();
}
if (m_TreeViewState == null)
{
m_TreeViewState = new TreeViewState();
}
m_TreeModel = new SpritePackerOverviewTreeModel();
m_TreeView = new SpritePackerOverviewTreeView(m_TreeViewState, multiColumnHeader);
m_TreeView.SetModel(m_TreeModel);
m_SearchField = new SearchField();
m_SearchField.downOrUpArrowKeyPressed += m_TreeView.SetFocusAndEnsureSelectedItem;
Refresh();
}
private void Refresh()
{
m_TreeModel.Reload();
if (!m_TreeModel.IsEmpty())
{
m_TreeView.Reload();
}
}
private MultiColumnHeaderState CreateMultiColumnHeader()
{
var columns = new[]
{
new MultiColumnHeaderState.Column
{
headerContent = new GUIContent("Atlas Name"),
headerTextAlignment = TextAlignment.Left,
canSort = false,
sortingArrowAlignment = TextAlignment.Right,
width = 280,
minWidth = 150,
autoResize = false,
allowToggleVisibility = false
},
new MultiColumnHeaderState.Column
{
headerContent = new GUIContent("Page"),
headerTextAlignment = TextAlignment.Left,
canSort = false,
width = 100,
minWidth = 70,
maxWidth = 120,
autoResize = false,
allowToggleVisibility = true
},
new MultiColumnHeaderState.Column
{
headerContent = new GUIContent("Size"),
headerTextAlignment = TextAlignment.Left,
canSort = false,
width = 100,
minWidth = 80,
autoResize = false,
allowToggleVisibility = true
},
new MultiColumnHeaderState.Column
{
headerContent = new GUIContent("Format"),
headerTextAlignment = TextAlignment.Left,
canSort = false,
width = 350,
minWidth = 100,
autoResize = false,
allowToggleVisibility = true
}
};
return new MultiColumnHeaderState(columns);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gathering : Interacteble
{
[SerializeField]
private TaskType _taskType;
[SerializeField]
private int _AmountOfResources;
[SerializeField]
private int _ResourcesPerMinute;
private NPC _npc;
private bool _onCooldown;
void AddResources()
{
switch (_taskType)
{
case TaskType.Food:
ResourcesList._resourcesList._food++;
break;
case TaskType.Wood:
ResourcesList._resourcesList._wood++;
break;
case TaskType.Stone:
ResourcesList._resourcesList._stone++;
break;
case TaskType.SteelScrap:
ResourcesList._resourcesList._steelScrap++;
break;
case TaskType.random:
break;
}
_AmountOfResources--;
if (_AmountOfResources == 0)
{
Destroy(this.gameObject);
}
}
public override void Action(NPC npc)
{
if (!_onCooldown)
{
_onCooldown = true;
AddResources();
StartCoroutine(Countdown());
}
}
private IEnumerator Countdown()
{
yield return new WaitForSeconds(60/_ResourcesPerMinute);
_onCooldown = false;
}
}
|
using PipServices.Sms.Client.Version1;
using PipServices3.Commons.Refer;
using PipServices3.Components.Build;
namespace PipServices.Sms.Client.Build
{
public class SmsClientFactory : Factory
{
public static Descriptor Descriptor = new Descriptor("pip-services-sms", "factoty", "*", "*", "1.0");
public static Descriptor NullClientV1Descriptor = new Descriptor("pip-services-sms", "client", "null", "*", "1.0");
public static Descriptor HttpClientV1Descriptor = new Descriptor("pip-services-sms", "client", "http", "*", "1.0");
public SmsClientFactory()
{
RegisterAsType(NullClientV1Descriptor, typeof(SmsNullClientV1));
RegisterAsType(HttpClientV1Descriptor, typeof(SmsHttpClientV1));
}
}
}
|
using FeedbackAndSurveyService.CustomException;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FeedbackAndSurveyService.Controller
{
[ApiController]
public class ExceptionController : ControllerBase
{
[Route("error")]
public IActionResult Error()
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
if (context.Error is ValidationException)
return BadRequest(context.Error.Message);
else if (context.Error is NotFoundException)
return NotFound(context.Error.Message);
else if (context.Error is ActionNotPermittedException)
return Forbid(context.Error.Message);
else
return Problem();
}
[Route("error/dev")]
public IActionResult DevelopmenError()
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
if (context.Error is ValidationException)
return BadRequest(context.Error.Message);
else if (context.Error is NotFoundException)
return NotFound(context.Error.Message);
else if (context.Error is ActionNotPermittedException)
return Unauthorized(context.Error.Message);
else
return Problem(detail: context.Error.StackTrace,
title: context.Error.Message);
}
}
} |
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 SOP_IAA_DAL;
namespace SOP_IAA.Controllers
{
public class ingenieroContratoController : Controller
{
private Proyecto_IAAEntities db = new Proyecto_IAAEntities();
// GET: ingenieroContrato
public ActionResult Index()
{
var ingenieroContrato = db.ingenieroContrato.Include(i => i.Contrato).Include(i => i.ingeniero);
return View(ingenieroContrato.ToList());
}
// GET: ingenieroContrato/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ingenieroContrato ingenieroContrato = db.ingenieroContrato.Find(id);
if (ingenieroContrato == null)
{
return HttpNotFound();
}
return View(ingenieroContrato);
}
// GET: ingenieroContrato/Create
public ActionResult Create()
{
ViewBag.idContrato = new SelectList(db.Contrato, "id", "licitacion");
ViewBag.idIngeniero = new SelectList(db.ingeniero, "idPersona", "descripcion");
return View();
}
// POST: ingenieroContrato/Create
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "idContrato,idIngeniero,fechaInicio,fechaFin")] ingenieroContrato ingenieroContrato)
{
if (ModelState.IsValid)
{
db.ingenieroContrato.Add(ingenieroContrato);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.idContrato = new SelectList(db.Contrato, "id", "licitacion", ingenieroContrato.idContrato);
ViewBag.idIngeniero = new SelectList(db.ingeniero, "idPersona", "descripcion", ingenieroContrato.idIngeniero);
return View(ingenieroContrato);
}
// GET: ingenieroContrato/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ingenieroContrato ingenieroContrato = db.ingenieroContrato.Find(id);
if (ingenieroContrato == null)
{
return HttpNotFound();
}
ViewBag.idContrato = new SelectList(db.Contrato, "id", "licitacion", ingenieroContrato.idContrato);
ViewBag.idIngeniero = new SelectList(db.ingeniero, "idPersona", "descripcion", ingenieroContrato.idIngeniero);
return View(ingenieroContrato);
}
// POST: ingenieroContrato/Edit/5
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "idContrato,idIngeniero,fechaInicio,fechaFin")] ingenieroContrato ingenieroContrato)
{
if (ModelState.IsValid)
{
db.Entry(ingenieroContrato).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.idContrato = new SelectList(db.Contrato, "id", "licitacion", ingenieroContrato.idContrato);
ViewBag.idIngeniero = new SelectList(db.ingeniero, "idPersona", "descripcion", ingenieroContrato.idIngeniero);
return View(ingenieroContrato);
}
// GET: ingenieroContrato/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ingenieroContrato ingenieroContrato = db.ingenieroContrato.Find(id);
if (ingenieroContrato == null)
{
return HttpNotFound();
}
return View(ingenieroContrato);
}
// POST: ingenieroContrato/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
ingenieroContrato ingenieroContrato = db.ingenieroContrato.Find(id);
db.ingenieroContrato.Remove(ingenieroContrato);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
/*
* Author: Generated Code
* Date Created: 15.02.2011
* Description: Represents a row in the tblRoles table
*/
using System.Data.SqlClient;
using System.Data;
using System;
namespace HTB.Database
{
public class tblRoles
{
#region Property Declaration
private int _roleID;
private string _roleCaption;
public int RoleID
{
get { return _roleID; }
set { _roleID = value; }
}
public string RoleCaption
{
get { return _roleCaption; }
set { _roleCaption = value; }
}
#endregion
}
}
|
using System;
using System.Collections;
using System.IO;
using HTB.Database.Views;
using iTextSharp.text;
namespace HTBReports
{
public class UebergabenAkten : BasicReport
{
private qryAkten _akt;
private int _rightLine;
public void GenerateUebergabenAktenPDF(ArrayList aktList, Stream os)
{
Init(os);
_rightLine = col + 1600;
foreach (qryAkten akt in aktList)
Generate(akt);
writer.Close();
}
private void Generate(qryAkten akt)
{
this._akt = akt;
lin = PrintPageHeader();
PrintBericht();
}
public override int PrintPageHeader()
{
if (pageNumber > 1)
writer.newPage();
lin = startLine;
writer.PrintLeftEcpInfo();
writer.drawBitmap(350, col, Image.GetInstance(logoPath), 66);
for (int i = 0; i < 3; i++)
{
writer.setFont("Arial", 22, true, false, false);
writer.print(50, col + 1600 + i, "EUROPEAN CAR PROTECT", 'R', BaseColor.BLUE); // give it a bolder look
writer.setFont("Arial", 16, true, false, false);
writer.print(120, col + 1600 + i, "INKASSO-SERVICE", 'R', BaseColor.BLUE); // give it a bolder look
}
lin += gap + 20;
writer.setFont("Calibri", 8);
writer.print((lin += gap), col1, "E.C.P. European Car Protect KG");
writer.print((lin += gap), col1, "Loigerstr. 89 A 5071 Wals");
writer.drawLine(lin + 30, col1, lin + 30, col1 + 465);
lin += gap;
SetLineFont();
writer.print((lin += gap), col1, _akt.KlientName1);
writer.print((lin += gap), col1, _akt.KlientName2);
writer.print((lin += gap), col1, _akt.KlientName3);
writer.print((lin += gap), col1, _akt.KlientStrasse);
writer.print((lin += gap), col1, _akt.KlientLKZ + " - " + _akt.KlientPLZ + " " + _akt.KlientOrt);
SetLineFont();
writer.print((lin += gap), _rightLine, "Salzburg, am " + DateTime.Now.ToShortDateString(), 'R');
writer.print((lin += gap), _rightLine, "Unser AZ: " + _akt.AktCaption, 'R');
writer.print((lin += gap), _rightLine, "Ihr AZ: " + _akt.AktIZ, 'R');
string gegnerName = _akt.GegnerName1 + " " + _akt.GegnerName2;
if (_akt.GegnerGebDat.ToShortDateString() != "01.01.1900")
gegnerName += " " + _akt.GegnerGebDat.ToShortDateString();
lin += gap * 5;
SetHeadingFont();
writer.print((lin += gap), col3, "Anschrifterhebung: " + gegnerName);
lin += gap;
writer.print((lin += gap), col3+200, _akt.GegnerStrasse+", "+_akt.GegnerZip+" "+_akt.GegnerOrt);
lin += gap * 3;
pageNumber++;
return lin;
}
private void PrintBericht()
{
SetLineFont();
lin = HTBReports.ReportUtils.PrintTextInMultipleLines(this, lin, col3, gap, _akt.AKTBericht, 90);
lin = 2350;
writer.print((lin+=gap*2), col3, "Mit freundlichem Gruß [with kind regards]");
writer.print((lin += gap), col3, "ECP - European Car Protect");
writer.print((lin += gap*2), col3, "Inh. Thomas Jaky, Helmut Ammer");
writer.print((lin += gap * 2), col3, "+43 (0) 662 20 34 10 - 0");
writer.print((lin += gap), col3, "office@ecp.or.at");
writer.print((lin += gap), col3, "www.ecp.or.at");
int tmpLine = lin + gap;
lin = 2400;
writer.print((lin += gap), _rightLine, "Kosten der Erhebung "+HTBUtilities.HTBUtils.FormatCurrency(_akt.AKTPreis), 'R');
writer.print((lin += gap), _rightLine, "zzgl. 20% MWSt. " + HTBUtilities.HTBUtils.FormatCurrency(_akt.AKTPreis * .2), 'R');
writer.print((lin += gap * 2), _rightLine, "GESAMTBETRAG " + HTBUtilities.HTBUtils.FormatCurrency(_akt.AKTPreis * 1.2), 'R');
lin = tmpLine;
writer.setFont("Calibri", 8);
writer.print((lin += gap), col3, "Unsere Auskünfte werden entsprechend unseren Geschäftsbedinungen und unter Ausschluss jeder Haftung erteilt");
writer.print((lin += gap), col3, "und sind streng vertraulich. Für jegliche Indiskretion haftet der Auftraggeber, bzw. der Empfänger");
}
}
}
|
using Pe.Stracon.Politicas.Infraestructura.QueryModel.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.Politicas.Infraestructura.QueryModel.General
{
/// <summary>
/// Representa los datos de Parametro
/// </summary>
/// <remarks>
/// Creación: GMD 27032015 <br />
/// Modificación: <br />
/// </remarks>
public class ParametroLogic : Logic
{
/// <summary>
/// Código de parametro
/// </summary>
public int CodigoParametro { get; set; }
/// <summary>
/// Código Identificador
/// </summary>
public string CodigoIdentificador { get; set; }
/// <summary>
/// Identificador Empresa
/// </summary>
public bool IndicadorEmpresa { get; set; }
/// <summary>
/// Código Empresa
/// </summary>
public Guid CodigoEmpresa { get; set; }
/// <summary>
/// Código Identificador de Empresa
/// </summary>
public string CodigoEmpresaIdentificador { get; set; }
/// <summary>
/// Nombre de Empresa
/// </summary>
public string NombreEmpresa { get; set; }
/// <summary>
/// Código Sistema
/// </summary>
public Guid? CodigoSistema { get; set; }
/// <summary>
/// Código Identificador de Sistema
/// </summary>
public string CodigoSistemaIdentificador { get; set; }
/// <summary>
/// Nombre de Sistema
/// </summary>
public string NombreSistema { get; set; }
/// <summary>
/// Tipo de Parámetro
/// </summary>
public string TipoParametro { get; set; }
/// <summary>
/// Nombre del Parametro
/// </summary>
public string Nombre { get; set; }
/// <summary>
/// Descripción del Parametro
/// </summary>
public string Descripcion { get; set; }
/// <summary>
/// Indicador Permite Agregar
/// </summary>
public bool IndicadorPermiteAgregar { get; set; }
/// <summary>
/// Indicador Permite Modificar
/// </summary>
public bool IndicadorPermiteModificar { get; set; }
/// <summary>
/// Indicador Permite Eliminar
/// </summary>
public bool IndicadorPermiteEliminar { get; set; }
/// <summary>
/// Estadro de Registro
/// </summary>
public string EstadoRegistro { get; set; }
}
}
|
using System;
namespace Vlc.DotNet.Core
{
public sealed class VlcMediaPlayerVideoOutChangedEventArgs : EventArgs
{
public VlcMediaPlayerVideoOutChangedEventArgs(int newCount)
{
NewCount = newCount;
}
public int NewCount { get; private set; }
}
} |
using System.Collections.Generic;
using System.Web.Mvc;
namespace DevExpress.Web.Demos {
public partial class ReportController : DemoController {
public ActionResult SideBySideReport([Bind(Prefix="parameter_")][ModelBinder(typeof(ParameterDictionaryBinder))] Dictionary<string, string> parameter) {
var model = ReportDemoHelper.CreateModel("SideBySide", parameter);
ViewData["parameter_leftSideParameter"] = SelectListItemHelper.GetSideBySideItems((int)model.Report.Parameters["leftSideParameter"].Value);
ViewData["parameter_rightSideParameter"] = SelectListItemHelper.GetSideBySideItems((int)model.Report.Parameters["rightSideParameter"].Value);
return DemoView("SideBySideReport", "SampleViewer", model);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IvanovoCity
{
class Shop : Building
{
int PriceCotton; // цена хлопка
int PriceClothes; // цена одежды
public Shop()
{
active_b = house.shop;
IsEmpty = false;
state = true;
time = 40;
staff = 5;
level = 0;
maxLevel = 0;
PriceClothes = 55;
PriceCotton = 5;
startMoney = 12000;
}
override public void showInfo( Label a, Label b, Label c, Label d, Label e, Label f, Button active, Button destroy, Button repair)
{
a.Text = "Магазин одежды";
b.Text = "Персонал: " + staff.ToString() + " человек";
c.Text = "Состояние: ";
if (state == true)
{
c.Text += "Готово к работе";
repair.Hide();
}
else
{
c.Text += "Нужен ремонт";
repair.Show();
}
d.Text = "Стоимость (1 единицы):" + PriceClothes + " рублей";
d.Show(); e.Hide(); f.Hide();
active.Text = "Продать одежду"; active.Show();
destroy.Show();
}
public void showInfoHlopok( Label a, Label b, Label c, Label d, Label e, Label f, Button active, Button destroy, Button repair)
{
a.Text = "Магазин хлопка";
b.Text = "Персонал: " + staff.ToString() + " человек";
c.Text = "Состояние: ";
c.Text += "Готово к работе";
d.Text = "Стоимость (1 единицы):" + PriceCotton + " рублей";
d.Show(); e.Hide(); f.Hide();
active.Text = "Купить хлопок"; active.Show();
destroy.Hide(); repair.Hide();
}
public int GetPriceCotton()
{
return PriceCotton;
}
public int GetPriceClothes()
{
return PriceClothes;
}
}
}
|
using UnityAtoms.BaseAtoms;
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Variable Instancer of type `Quaternion`. Inherits from `AtomVariableInstancer<QuaternionVariable, QuaternionPair, Quaternion, QuaternionEvent, QuaternionPairEvent, QuaternionQuaternionFunction>`.
/// </summary>
[EditorIcon("atom-icon-hotpink")]
[AddComponentMenu("Unity Atoms/Variable Instancers/Quaternion Variable Instancer")]
public class QuaternionVariableInstancer : AtomVariableInstancer<
QuaternionVariable,
QuaternionPair,
Quaternion,
QuaternionEvent,
QuaternionPairEvent,
QuaternionQuaternionFunction>
{ }
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Ghostpunch.OnlyDown.Common.Views;
using strange.extensions.mediation.impl;
namespace Ghostpunch.OnlyDown.Common.ViewModels
{
public abstract class ViewModelBase<V> : Mediator where V : ViewBase
{
[Inject]
public V View { get; set; }
public override void OnRegister()
{
base.OnRegister();
View.Initialize();
}
}
/// <summary>
/// A base class for the ViewModel classes in the MVVM pattern.
/// </summary>
public class ViewModelBase : INotifyPropertyChanged
{
/// <summary>
/// Occurs after a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Provides access to the PropertyChanged event handler to derived classes.
/// </summary>
protected PropertyChangedEventHandler PropertyChangedHandler
{
get { return PropertyChanged; }
}
public void VerifyPropertyName(string propertyName)
{
var myType = GetType();
#if NETFX_CORE
if (!string.IsNullOrEmpty(propertyName) && myType.GetTypeInfo().GetDeclaredProperty(propertyName) == null)
throw new ArgumentException("Property not found", propertyName);
#else
if (!String.IsNullOrEmpty(propertyName) && myType.GetProperty(propertyName) == null)
{
var descriptor = this as ICustomTypeDescriptor;
if (descriptor != null)
{
if (descriptor.GetProperties()
.Cast<PropertyDescriptor>()
.Any(property => property.Name == propertyName))
return;
}
throw new ArgumentException("Property not found", propertyName);
}
#endif
}
protected virtual void RaisePropertyChanged(string propertyName)
{
VerifyPropertyName(propertyName);
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
var handler = PropertyChanged;
if (handler != null)
{
var propertyName = GetPropertyName(propertyExpression);
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
if (propertyExpression == null)
throw new ArgumentNullException("propertyExpression");
var body = propertyExpression.Body as MemberExpression;
if (body == null)
throw new ArgumentException("Invalid argument", "propertyExpression");
var property = body.Member as PropertyInfo;
if (property == null)
throw new ArgumentException("Argument is not a property", "propertyExpression");
return property.Name;
}
protected bool Set<T>(string propertyName, ref T field, T newValue)
{
if (EqualityComparer<T>.Default.Equals(field, newValue))
return false;
field = newValue;
RaisePropertyChanged(propertyName);
return true;
}
protected bool Set<T>(Expression<Func<T>> propertyExpression, ref T field, T newValue)
{
if (EqualityComparer<T>.Default.Equals(field, newValue))
return false;
field = newValue;
RaisePropertyChanged(propertyExpression);
return true;
}
}
}
|
namespace Sila.Models.Rest.Requests
{
using System;
/// <summary>
/// The structure of a create part request.
/// </summary>
public class CreatePartRequest
{
/// <summary>
/// The name of the part.
/// </summary>
public String Name { get; }
/// <summary>
/// The color of the part.
/// </summary>
public String? Color { get; set; }
/// <summary>
/// The material of the part.
/// </summary>
public String? Material { get; set; }
/// <summary>
/// Instantiate a create part request.
/// </summary>
/// <param name="name">The name of the part.</param>
public CreatePartRequest(String name)
{
Name = name;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
namespace MovieFlow.Models
{
public class TVSeriesCatalog
{
[DisplayName("TvSerie Id")]
public int TvSerieId { get; set; }
[DisplayName("TvSerie Name")]
public String TvSerieName { get; set; }
[DisplayName("TvSerie Description")]
public String TvSerieDescription { get; set; }
[DisplayName("TvSerie Buget")]
public int TvSerieBuget { get; set; }
[DisplayName("TvSerie BeginYear")]
public int TvSerieBeginYear { get; set; }
[DisplayName("TvSerie EndYear")]
public int TvSerieEndYear { get; set; }
[DisplayName("TvSerie Episod")]
public int TvSerieEpisodsNumber { get; set; }
[DisplayName("TvSerie Seasons")]
public int TvSerieSeasons { get; set; }
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiChain.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FiiiChain.Consensus
{
public class AccountIdHelper
{
private const int testnetPrefix = 0x40E7E926;
private const int mainnetPrefix = 0x40E7E915;
private const int prefixLen = 4;
public static string CreateAccountAddress(byte[] publicKey)
{
var pubkHash = HashHelper.Hash160(publicKey);
return CreateAccountAddressByPublicKeyHash(pubkHash);
}
public static string CreateAccountAddressByPublicKeyHash(byte[] pubkHash)
{
//byte[] prefix = new byte[] { 0x00 }; //1
//byte[] prefix = new byte[] { 0x40, 0xE7, 0xE9, 0x26 }; //fiiit
byte[] fullPrefix;
if(GlobalParameters.IsTestnet)
{
fullPrefix = BitConverter.GetBytes(testnetPrefix);
}
else
{
fullPrefix = BitConverter.GetBytes(mainnetPrefix);
}
if(BitConverter.IsLittleEndian)
{
Array.Reverse(fullPrefix);
}
var payload = new List<byte>();
payload.AddRange(fullPrefix);
payload.AddRange(pubkHash);
var checksum = HashHelper.DoubleHash(payload.ToArray()).Take(4);
payload.AddRange(checksum);
return Base58.Encode(payload.ToArray());
}
public static byte[] GetPublicKeyHash(string accountAddress)
{
var bytes = Base58.Decode(accountAddress);
var publicKeyHash = new byte[bytes.Length - (prefixLen + 4)];
Array.Copy(bytes, prefixLen, publicKeyHash, 0, publicKeyHash.Length);
return publicKeyHash;
}
public static bool AddressVerify(string accountAddress)
{
try
{
var bytes = Base58.Decode(accountAddress);
if (bytes.Length != 28)
{
return false;
}
var prefixBytes = new byte[4];
Array.Copy(bytes, 0, prefixBytes, 0, 4);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(prefixBytes);
}
var prefixValue = BitConverter.ToInt32(prefixBytes, 0);
if (GlobalParameters.IsTestnet)
{
if (prefixValue != testnetPrefix)
{
return false;
}
}
else
{
if (prefixValue != mainnetPrefix)
{
return false;
}
}
//var prefix = bytes[prefixLen];
var checksum = new byte[4];
var data = new byte[bytes.Length - 4];
Array.Copy(bytes, 0, data, 0, bytes.Length - 4);
Array.Copy(bytes, bytes.Length - checksum.Length, checksum, 0, checksum.Length);
var newChecksum = HashHelper.DoubleHash(data).Take(4);
return BitConverter.ToInt32(checksum, 0) == BitConverter.ToInt32(newChecksum.ToArray(), 0);
}
catch
{
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lottery.Enums;
namespace Lottery.Interfaces.BonusCalculator
{
public delegate IBonusCalculator BonusCalculatorResolver(LottoType lottoType);
}
|
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.Security.Cryptography;
namespace HashMaker
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void requiredPasswordTxb_TextChanged(object sender, EventArgs e)
{
if(requiredPasswordTxb.Text.Length > 0)
{
hashItBtn.Enabled = true;
}
else
{
hashItBtn.Enabled = false;
}
}
private void hashItBtn_Click(object sender, EventArgs e)
{
if (requiredPasswordTxb.Text.Length > 0)
{
string resultText = SHA256(requiredPasswordTxb.Text);
resultTxb.Text = resultText;
resultTxb.Focus();
}
else
{
MessageBox.Show("Please write at least 1 character to the required textbox!", "Attention!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private string SHA256(string requiredPassword)
{
byte[] stringInByte = Encoding.UTF8.GetBytes(requiredPassword);
SHA256CryptoServiceProvider crypter = new SHA256CryptoServiceProvider();
byte[] secretBytes = crypter.ComputeHash(stringInByte);
string secretText = BitConverter.ToString(secretBytes);
return secretText.Replace("-", "").ToLower();
}
}
}
|
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace FontText
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetCurrentConsoleFontEx(
IntPtr consoleOutput,
bool maximumWindow,
ref CONSOLE_FONT_INFO_EX consoleCurrentFontEx);
static void Main(string[] args)
{
}
}
}
|
namespace kata_payslip_v2
{
public enum PayslipOutputType
{
ConsoleOutput, CsvFileOutput
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Interactable : MonoBehaviour {
public InteractEvent onInteract;
public Dialog initiatedDialog;
public void Interact(Character character) {
this.onInteract.Invoke(character);
if (this.initiatedDialog)
this.initiatedDialog.Initiate();
}
}
[Serializable]
public class InteractEvent : UnityEvent<Character> {
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;
public class StaticData : MonoBehaviour
{
public static string userPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SpaceGame4x/");
public static UnityEngine.Object LoadUnityResource(string path)
{
return Resources.Load(path);
}
}
|
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Event of type `GameObject`. Inherits from `AtomEvent<GameObject>`.
/// </summary>
[EditorIcon("atom-icon-cherry")]
[CreateAssetMenu(menuName = "Unity Atoms/Events/GameObject", fileName = "GameObjectEvent")]
public sealed class GameObjectEvent : AtomEvent<GameObject>
{
}
}
|
using UnityEngine;
public class CanvasAction : MonoBehaviour, IActionAble
{
public void DoAction()
{
}
public void UnDoAction()
{
}
public bool IsDefaultState()
{
return true;
}
public bool CanExecuteAction()
{
return true;
}
} |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
namespace Client.Helpers.Paint
{
public class W3_DrawCurve : W0_DrawObject
{
public W3_DrawCurve(MyInkCanvas myInkCanvas)
: base(myInkCanvas)
{
}
public override void CreateNewStroke(InkCanvasStrokeCollectedEventArgs e)
{
InkStroke = new DrawCurveStroke(this, e.Stroke.StylusPoints);
}
public override Point Draw(Point first, DrawingContext dc, StylusPointCollection points)
{
return first;
}
protected override void OnDraw(DrawingContext drawingContext, StylusPointCollection stylusPoints, Geometry geometry, Brush fillBrush)
{
base.OnDraw(drawingContext, stylusPoints, geometry, colorBrush);
}
}
public class DrawCurveStroke : DrawObjectStroke
{
public Brush colorBrush { get; set; }
public DrawCurveStroke(W0_DrawObject ink, StylusPointCollection stylusPoints)
: base(ink, stylusPoints)
{
this.DrawingAttributes.FitToCurve = true;
colorBrush=ink.colorBrush;
}
protected override void DrawCore(DrawingContext drawingContext, DrawingAttributes drawingAttributes)
{
base.DrawCore(drawingContext, drawingAttributes);
Pen pen = new Pen(colorBrush, 1.0);
Geometry geometry = this.GetGeometry();
drawingContext.DrawGeometry(colorBrush, pen, geometry);
}
}
} |
namespace ScheduleService.Model
{
public enum ExaminationType
{
Examination,
Surgery
}
}
|
/// <summary>
/// HUD healthbar - script for the building and updating of the healthbar HUD
/// </summary>
using UnityEngine;
using System.Collections;
public class HUD_Healthbar : MonoBehaviour {
private GameObject[] healthbarIcons;
private GameObject healthManager;
private HealthManager playerHealth;
private RectTransform rectTran;
public int healthBarSize;
public int panelSize;
private int currentHealth;
private float hideSpeed = 10.0f;
private bool hideHealthHUD = false;
void Start ()
{
rectTran = GetComponent<RectTransform> ();
healthManager = GameObject.Find ("Health Manager");
playerHealth = healthManager.GetComponent<HealthManager> ();
// hide the healthbar in the upgrade screen
if (Application.loadedLevelName == "Upgrade Screen") {
hideHealthHUD = true;
}
// hide health_HUD on title screen
if(Application.loadedLevelName == "Restore Point")
{
if(!GameObject.Find("HideTitleObject"))
{
hideHealthHUD = true;
rectTran.anchoredPosition = new Vector3(0, 75, 0);
}
}
} // end Start
void Update ()
{
// refresh the healthbar to show if the player has taken damage
updateIcons ();
// hide the healthbar of
if (hideHealthHUD) {
hideHUD();
} else {
returnHUD();
}
} // end Update
// function for the building of the healthbar at the start of the scene
public void buildHealthbarUI(int size)
{
// Take size from player inventory, instantiate UI box for each slot, plus bookend graphics
healthbarIcons = new GameObject[size];
Vector3 panelPosition;
// draw shoulder buttons
GameObject L_bookend = Instantiate (Resources.Load("UI/HUD/Health/HUD_Bookend_Health_L"), new Vector3(-1*((size*panelSize)/2) - panelSize/2, -10, 0), Quaternion.identity) as GameObject;
L_bookend.transform.SetParent(gameObject.transform, false);
L_bookend.GetComponent<RectTransform>().anchoredPosition = new Vector2(-1*((size*panelSize)/2) - panelSize/2, -10) ;
GameObject R_bookend = Instantiate (Resources.Load("UI/HUD/Health/HUD_Bookend_Health_R"), new Vector3(1*((size*panelSize)/2) + panelSize/2, -10, 0), Quaternion.identity) as GameObject;
R_bookend.transform.SetParent(gameObject.transform, false);
R_bookend.GetComponent<RectTransform>().anchoredPosition = new Vector2(1*((size*panelSize)/2) + panelSize/2, -10) ;
// draw the healthbar panels in order, depending upon the size of the healthbar
for(int i = 0; i < size ; i++){
// position their rect-transforms according to their index and the size of the array
panelPosition = new Vector3( -1*((size*panelSize)/2) + panelSize/2 + i*panelSize, -10, 0);
healthbarIcons[i] = Instantiate(Resources.Load("UI/HUD/Health/HUD_Panel_Health"), panelPosition, Quaternion.identity) as GameObject;
// set the parent and keep the position relative to the parent
healthbarIcons[i].transform.SetParent(gameObject.transform, false);
healthbarIcons[i].GetComponent<RectTransform>().anchoredPosition = new Vector2(-1*((size*panelSize)/2) + panelSize/2 + i*panelSize, -10);
// name them as an index for the UI array
healthbarIcons[i].gameObject.name = "Cell " + i.ToString();
}
}
// function to update all the icons in the healthbar, to show changes in player health
void updateIcons()
{
currentHealth = playerHealth.playerHealth;
for (int i = 0; i < healthBarSize; i++) {
if(i >= currentHealth){
healthbarIcons[i].transform.GetChild(1).gameObject.SetActive(false);
}
}
}
// private functions to show/hide the healthbar
void hideHUD()
{
rectTran.anchoredPosition = Vector3.Lerp (rectTran.anchoredPosition, new Vector3(0, 75, 0), Time.deltaTime*hideSpeed/2);
}
void returnHUD()
{
rectTran.anchoredPosition = Vector3.Lerp (rectTran.anchoredPosition, new Vector3(0, -25, 0), Time.deltaTime*hideSpeed);
}
// public functions to hide the healthbar: one for toggling, and two for use in the update function
public void toggleHide(){
hideHealthHUD = !hideHealthHUD;
}
public void hide()
{
hideHealthHUD = true;
}
public void show()
{
hideHealthHUD = false;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cloud : MonoBehaviour
{
private List<Vector3> cloud = new List<Vector3>();
List<GameObject> vertexes = new List<GameObject>();
public int nrofvertices;
public GameObject gobj;
public Material material;
private List<Vector3> vertices = new List<Vector3>();
private List<int> triangles = new List<int>();
private List<int[]> trianglesa = new List<int[]>();
private Vector3 normal,test;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < nrofvertices; i++)
{
GameObject tempobj = new GameObject("vertexes nr " + (i+1));
Vector3 vec = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), Random.Range(-1f, 1f));
tempobj.transform.position = vec;
cloud.Add(vec);
}
for (int i = 0; i < 4; i++)
{
vertices.Add(cloud.ToArray()[i]);
}
Vector3 center = GetAverageList(vertices);
Vector3 normal;
normal = Vector3.Cross(vertices.ToArray()[0] - vertices.ToArray()[1], vertices.ToArray()[0] - vertices.ToArray()[2]);
if (Vector3.Dot(center-GetAverage(vertices.ToArray()[0],vertices.ToArray()[1], vertices.ToArray()[2]),normal) < 0)
{
trianglesa.Add(new int[] { 0, 1, 2 });
}
else
{
trianglesa.Add(new int[] { 2, 1, 0 });
}
normal = Vector3.Cross(vertices.ToArray()[1] - vertices.ToArray()[3], vertices.ToArray()[2] - vertices.ToArray()[3]);
if (Vector3.Dot(center - GetAverage(vertices.ToArray()[1], vertices.ToArray()[2], vertices.ToArray()[3]), normal) < 0)
{
trianglesa.Add(new int[] { 1, 2, 3 });
}
else
{
trianglesa.Add(new int[] { 3, 2, 1 });
}
normal = Vector3.Cross(vertices.ToArray()[1] - vertices.ToArray()[0], vertices.ToArray()[1] - vertices.ToArray()[3]);
if (Vector3.Dot(center - GetAverage(vertices.ToArray()[1], vertices.ToArray()[0], vertices.ToArray()[3]), normal) < 0)
{
trianglesa.Add(new int[] { 1, 0, 3 });
}
else
{
trianglesa.Add(new int[] { 3, 0, 1 });
}
normal = Vector3.Cross(vertices.ToArray()[2] - vertices.ToArray()[0], vertices.ToArray()[2] - vertices.ToArray()[3]);
if (Vector3.Dot(center - GetAverage(vertices.ToArray()[2], vertices.ToArray()[0], vertices.ToArray()[3]), normal) < 0)
{
trianglesa.Add(new int[] { 2, 0, 3 });
}
else
{
trianglesa.Add(new int[] { 2, 0, 3 });
}
//trianglesa.Add(new int[] { 1, 2, 3 });
//trianglesa.Add(new int[] { 3, 2, 1 });
//trianglesa.Add(new int[] { 0, 1, 2 });
//trianglesa.Add(new int[] { 2, 1, 0 });
//trianglesa.Add(new int[] { 1, 0, 3 });
//trianglesa.Add(new int[] { 3, 0, 1 });
//trianglesa.Add(new int[] { 2, 0, 3 });
//trianglesa.Add(new int[] { 3, 0, 2 });
Mesh mesh = new Mesh();
mesh.vertices = vertices.ToArray();
mesh.triangles = GetTriangles(trianglesa).ToArray();
//mesh.triangles = new int[] { 0, 1, 2,0,2,1,1,2,3,0,2,3,3,2,1,3,0,1,2,0,3,2,1,3,3,2,0 };
gobj.AddComponent<MeshFilter>();
gobj.GetComponent<MeshFilter>().mesh = mesh;
gobj.AddComponent<MeshRenderer>();
gobj.GetComponent<MeshRenderer>().material = material;
}
private Vector3 GetAverageList(List<Vector3> _list)
{
Vector3 output;
float xavg = 0, yavg = 0, zavg = 0;
foreach (Vector3 v in _list)
{
xavg += v.x;
yavg += v.y;
zavg += v.z;
}
output = new Vector3(xavg / _list.Count, yavg / _list.Count, zavg / _list.Count);
return output;
}
private Vector3 GetAverage(Vector3 a, Vector3 b, Vector3 c)
{
Vector3 output;
List<Vector3> temp = new List<Vector3>();
temp.Add(a);
temp.Add(b);
temp.Add(c);
float xavg = 0, yavg = 0, zavg = 0;
foreach (Vector3 v in temp)
{
xavg += v.x;
yavg += v.y;
zavg += v.z;
}
output = new Vector3(xavg / 3,yavg / 3, zavg / 3);
return output;
}
private List<int> GetTriangles(List<int[]> input)
{
List<int> output=new List<int>();
foreach(int[] i in input)
{
output.Add(i[0]);
output.Add(i[1]);
output.Add(i[2]);
}
return output;
}
private void iterate()
{
}
private void OnDrawGizmos()
{
if (cloud != null)
{
Gizmos.color = Color.red;
Vector3 size = new Vector3(0.05f, 0.05f, 0.05f);
Vector3 center;
center = GetAverageList(vertices);
Gizmos.DrawCube(center, 3*size);
foreach (Vector3 v in cloud)
{
Gizmos.DrawCube(v, size);
}
Gizmos.color = Color.yellow;
//Gizmos.DrawLine(test, normal);
//Gizmos.DrawCube(normal, size);
//Gizmos.DrawCube(test, size);
foreach(int[] nr in trianglesa)
{
normal = Vector3.Cross(cloud[nr[0]]- cloud[nr[1]], cloud[nr[0]]- cloud[nr[2]]);
Vector3 lol = center - GetAverage(cloud[nr[0]], cloud[nr[1]], cloud[nr[2]]);
if (Vector3.Dot(lol,normal)<0)
{
Gizmos.DrawCube(GetAverage(cloud[nr[0]], cloud[nr[1]], cloud[nr[2]]), size);
Gizmos.DrawLine(GetAverage(cloud[nr[0]], cloud[nr[1]], cloud[nr[2]]), GetAverage(cloud[nr[0]], cloud[nr[1]], cloud[nr[2]])+ normal);
}
}
}
}
//{
// if(cloud!=null)
// {
// Vector3 a = cloud.ToArray()[0];
// Vector3 b = cloud.ToArray()[1];
// Vector3 c = cloud.ToArray()[2];
// Vector3 d = cloud.ToArray()[3];
// Vector3 size = new Vector3(0.01f, 0.01f, 0.01f);
// Gizmos.color = Color.black;
// foreach(Vector3 v in cloud)
// {
// Gizmos.DrawCube(v, size);
// }
// Gizmos.DrawLine(a, b);
// Gizmos.DrawLine(a, c);
// Gizmos.DrawLine(a, d);
// Gizmos.DrawLine(b, c);
// Gizmos.DrawLine(b, d);
// Gizmos.DrawLine(c, d);
// }
//}
// Update is called once per frame
void Update()
{
}
//public bool IsPointInside(this Mesh aMesh, Vector3 aLocalPoint)
//{
// var verts = aMesh.vertices;
// var tris = aMesh.triangles;
// int triangleCount = tris.Length / 3;
// for (int i = 0; i < triangleCount; i++)
// {
// var V1 = verts[tris[i * 3]];
// var V2 = verts[tris[i * 3 + 1]];
// var V3 = verts[tris[i * 3 + 2]];
// var P = new Plane(V1, V2, V3);
// if (P.GetSide(aLocalPoint))
// return false;
// }
// return true;
//}
}
|
using System;
using Dapper;
using Laoziwubo.IDAL;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Laoziwubo.Model.Common;
using Laoziwubo.Model.Attribute;
namespace Laoziwubo.DAL
{
public class BaseD<T> : IBaseD<T> where T : new()
{
private IDbConnection _conn;
private readonly GenericM _genericM;
public BaseD(Connection dbConnection, GenericM genericM, Dictionary<string, object> dic)
{
_conn = dbConnection.GetSqlConnection();
_genericM = genericM;
_genericM.Fields = dic;
var type = typeof(T);
//表名
var dataTableAttribute = (DataTableAttribute)type.GetCustomAttribute(typeof(DataTableAttribute));
_genericM.TableName = dataTableAttribute == null ? typeof(T).Name : dataTableAttribute.Name;
//字段处理
var properties = type.GetTypeInfo().GetProperties();
foreach (var p in properties)
{
if (p.GetCustomAttribute(typeof(FieldAttribute)) is FieldAttribute)
{
_genericM.Fields.Add(p.Name, null);
}
if (p.GetCustomAttribute(typeof(IdentityAttribute)) is IdentityAttribute)
{
_genericM.Identity = p.Name;
}
}
}
public async Task<IEnumerable<T>> GetEntitysAsync(QueryM q)
{
try
{
var orderBy = q.OrderBy ?? _genericM.Identity + " DESC";
var where = string.IsNullOrEmpty(q.Where) ? "" : " WHERE " + q.Where;
var str = $@"SELECT {string.Join(",", _genericM.Fields.Keys)}
FROM {_genericM.TableName + where}
ORDER BY {orderBy}
LIMIT {(q.PageNum - 1) * q.PageSize} , {q.PageSize};";
return await _conn.QueryAsync<T>(str);
}
catch (Exception)
{
return null;
}
}
public T GetEntityById(int id)
{
try
{
var str = $@"SELECT {string.Join(",", _genericM.Fields.Keys)} FROM {_genericM.TableName} WHERE {_genericM.Identity} = @{_genericM.Identity};";
var p = new DynamicParameters();
p.Add($"@{_genericM.Identity}", id);
return _conn.QueryFirstOrDefault<T>(str, p);
}
catch (Exception)
{
return new T();
}
}
public bool Insert(T model)
{
try
{
if (_genericM.Fields.ContainsKey(_genericM.Identity))
{
_genericM.Fields.Remove(_genericM.Identity);
}
var str = $@" INSERT INTO {_genericM.TableName} ({string.Join(",", _genericM.Fields.Keys)})
VALUES (@{string.Join(",@", _genericM.Fields.Keys)});";
_conn.Execute(str, model);
return true;
}
catch (Exception e)
{
return false;
}
}
public bool Update(T model)
{
try
{
if (_genericM.Fields.ContainsKey(_genericM.Identity))
{
_genericM.Fields.Remove(_genericM.Identity);
}
var fields = string.Empty;
foreach (var f in _genericM.Fields.Keys)
{
fields += f + "=@" + f + ",";
}
fields = fields.TrimEnd(',');
var str = $@" UPDATE {_genericM.TableName} SET {fields}
WHERE {_genericM.Identity} = @{_genericM.Identity};";
_conn.Execute(str, model);
return true;
}
catch (Exception e)
{
return false;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
_conn.Close();
_conn = null;
}
}
~BaseD()
{
Dispose(false);
}
}
}
|
using System;
namespace OMKServer
{
public class User
{
private UInt32 SequenceNumber = 0;
private string SessionID;
private int SessionIndex = -1;
public short UserPos { get; private set; } = -1;
public int RoomNumber { get; private set; } = -1;
private string UserID;
public void Set(UInt32 sequence, string sessionID, int sessionIndex, string userID)
{
this.SequenceNumber = sequence;
this.SessionID = sessionID;
this.SessionIndex = sessionIndex;
this.UserID = userID;
setUserPos(-1);
}
public bool IsConfirm(string netSessionID)
{
return this.SessionID == netSessionID;
}
public string ID()
{
return this.UserID;
}
public void setUserPos(short pos)
{
this.UserPos = pos; // 0 : 흑(방장), 1 : 백(일반), -1 : none
}
public void EnteredRoom(int roomNumber)
{
this.RoomNumber = roomNumber;
}
public void LeaveRoom()
{
RoomNumber = -1;
setUserPos(-1);
}
public bool IsStateLogin()
{
return this.SessionIndex != -1;
}
public bool IsStateRoom()
{
return this.RoomNumber != -1;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows;
namespace Olive.Desktop.WPF.Converters
{
public class ImageSourceConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//declarations
string assemblyPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
string filePath;
string nullPath;
int isDebug = assemblyPath.IndexOf("Debug");
if (isDebug != -1)
{
nullPath = assemblyPath.Replace(@"bin\Debug", @"Images\");
}
else
{
nullPath = assemblyPath.Replace(@"Application", @"RecipesImages\");
}
BitmapImage imageToBitmap = new BitmapImage();
try
{
//concatenate the values
//filePath = Path.Combine(values[0].ToString(), values[1].ToString());
filePath = values[1].ToString();
imageToBitmap.BeginInit();
imageToBitmap.CacheOption = BitmapCacheOption.OnLoad;
imageToBitmap.UriSource = new Uri(filePath);
imageToBitmap.EndInit();
}
//FileNotFoundException
catch (UriFormatException)
{
//concatenate the values
filePath = Path.Combine(nullPath, "null_image.png");
imageToBitmap.CacheOption = BitmapCacheOption.OnLoad;
imageToBitmap.UriSource = new Uri(filePath);
imageToBitmap.EndInit();
}
return imageToBitmap;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return null;
//return value == null ? DependencyProperty.UnsetValue : value;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EasyDev.Util;
using System.Data;
using EasyDev.SQMS;
using SQMS.Services;
namespace SQMS.Application.Views.Basedata
{
public partial class ResourceView : SQMSPage<ResourceService>
{
private ResourceService srv = null;
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnPreInitializeViewEventHandler(object sender, EventArgs e)
{
srv = Service as ResourceService;
}
protected override void OnInitializeViewEventHandler(object sender, EventArgs e)
{
DataRow drRes = DataSetUtil.GetFirstRowFromDataSet(this.ViewData, Service.BOName);
if (drRes != null)
{
this.lblResCode.Text = ConvertUtil.ToStringOrDefault(drRes["RESCODE"]);
this.lblResName.Text = ConvertUtil.ToStringOrDefault(drRes["RESNAME"]);
this.lblResIdentity.Text = ConvertUtil.ToStringOrDefault(drRes["RESIDENTITY"]);
this.lblViewName.Text = ConvertUtil.ToStringOrDefault(drRes["VIEWNAME"]);
this.lblIsvoid.Text = ConvertUtil.ToStringOrDefault(drRes["ISVOID"]).Equals("Y") ? "禁用" : "启用";
this.btnActiveBottom.Visible = this.btnActiveTop.Visible =
ConvertUtil.ToStringOrDefault(drRes["ISVOID"]).Equals("Y");
this.btnInactiveBottom.Visible = this.btnInactiveTop.Visible =
ConvertUtil.ToStringOrDefault(drRes["ISVOID"]).Equals("N");
this.lblMemo.Text = ConvertUtil.ToStringOrDefault(drRes["MEMO"]);
}
}
protected override void OnLoadDataEventHandler(object sender, EventArgs e)
{
this.ViewData = Service.LoadByKey(this.ID, true);
}
public void btnDelete_OnClick(object sender, EventArgs e)
{
Service.DeleteByKey(this.ID);
Response.Redirect("ResourceList.aspx?p=reslist");
}
public void btnEdit_OnClick(object sender, EventArgs e)
{
Response.Redirect("ResourceEdit.aspx?p=resedit&id=" + this.ID);
}
public void btnActive_OnClick(object sender, EventArgs e)
{
srv.ActiveByKey(this.ID);
Response.Redirect("ResourceList.aspx?p=reslist");
}
}
}
|
using JhinBot.Enums;
using JhinBot.Interface;
namespace JhinBot.Utils
{
public class ConversationStep
{
public StepType StepType { get; }
public IValidator Validator { get; }
public string StepMessage { get; }
public ConversationStep(IValidator validator, StepType stepType, string message)
{
Validator = validator;
StepType = stepType;
StepMessage = message;
}
public (bool success, string errorMsg) Execute(string input)
{
var result = Validator.Validate(input);
return result;
}
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace Game.UI.Component
{
[AddComponentMenu("Layout/UIDragable")]
public class GameUIDragable : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
[Tooltip("should align to grid when drag over?")]
/// <summary>
/// 是否对齐到网格上,对到0时即为不对齐。0值以上,即为位置会吸附到取整的单元格上
/// </summary>
[SerializeField]uint m_alignToGrid = 0;
[Tooltip("在拖拽时是否中断click的响应")]
/// <summary>
/// 在拖拽时是否中断click的响应
/// </summary>
[SerializeField]bool m_stopClickWhenDrag;
RectTransform m_rectTransform;
//开始拖拽时UI的位置:
Vector2 m_rectTransAnchoredPos;
//开始拖拽时的触点位置
Vector2 m_startDragPos;
/// <summary>
/// 是否是有效的拖拽行为:只有当从当前物体开始点击,才能在Drag中生效;DragUp之后取消标记
/// </summary>
bool m_isValidDrag = false;
void OnEnable()
{
m_rectTransform = GetComponent<RectTransform>();
if (GetComponent<Image>() == null)
{
//Create an img that is invisible:
Image img= gameObject.AddComponent<Image>();
img.color = Color.clear;
}
//TEST
if (GetComponent<Button>())
{
Debug.LogWarning("Button attached, so it will accpet click event that may confuse you when you drag it.");
}
}
//--开始拖拽
public void OnPointerDown(PointerEventData data)
{
//开始拖拽时记录鼠标位置
m_startDragPos = data.position;
//记录当前Rect位置
m_rectTransAnchoredPos = m_rectTransform.anchoredPosition;
//允许拖拽
m_isValidDrag = true;
}
//继承函数:Drag时触发
public void OnDrag(PointerEventData data)
{
if (!m_isValidDrag)
return;
//新计算方法:
//获得移动差值
Vector2 posDelta = data.position - m_startDragPos;
Vector2 newPos = m_rectTransAnchoredPos + posDelta;
//予以移动:
//--更新移动视图
m_rectTransform.anchoredPosition = newPos;
}
//拖拽完成
public void OnPointerUp(PointerEventData data)
{
if (m_isValidDrag)
{
//标记移动结束:
m_isValidDrag = false;
Vector2 vPos = m_rectTransform.anchoredPosition;
if (m_alignToGrid > 0)
{
vPos.x = (int)vPos.x / m_alignToGrid * m_alignToGrid;
vPos.y = (int)vPos.y / m_alignToGrid * m_alignToGrid;
m_rectTransform.anchoredPosition = vPos;
}
//再发起一次click事件的响应:
if (m_stopClickWhenDrag
&& (data.position != m_startDragPos)
&& MyInput.IsMouseOnUI())
{
GetComponent<IPointerClickHandler>().OnPointerClick(data);
}
}
}
}
} |
namespace Tests.Data.Oberon
{
/// <summary>
/// A helper representing a tenant's address
/// </summary>
public class TenantAddress
{
public string AddressLine1;
public string AddressLine2;
public string AddressLine3;
public string AddressLine4;
public string City;
public string PostalCode;
public string StateProvince;
}
} |
using Comp;
using Dapper;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Dish
{
/// <summary>
/// 菜品维护
/// </summary>
public class D_Dish
{
/// <summary>
/// 获取原料集合
/// </summary>
/// <param name="eDish">查询参数实体</param>
/// <returns>返回对应原料集合</returns>
public List<E_Dish> GetList(E_Dish eDish)
{
List<E_Dish> list = null;
//拼接查询条件
StringBuilder strwhere = new StringBuilder();
if (eDish.typeid > 0) //分类
{
strwhere.AddWhere($"typeid={eDish.typeid}");
}
if (!string.IsNullOrEmpty(eDish.name))
{
strwhere.AddWhere("name=@name");
}
//主查询Sql
StringBuilder search = new StringBuilder();
search.AppendFormat(@"select * from
(
SELECT [id]
,case when F.DID is null then [name] else [name] end as name
,[typeid]
,[cuisine]
,[taste]
,[texture]
,[cooking]
,[pic]
,[tag]
,[cookingmethod]
,[technicalpoints]
,[mainmaterial]
,[accessories]
,[seasoning]
,[nohandleraw]
,case when F.DID is null then 0 else 1 end as iserrordata
FROM Dish as E left join
(
select DID from DishInfo C inner join
(
select A.id from RawMaterial as A left join RawMaterial_Area as B on A.id=B.RawID where B.id is null
) as D on C.RawID=D.id group by DID
) F on E.id=F.DID
) as T {0}", strwhere.ToString());
//获取缓存
if (strwhere.ToString() == "") //没有条件的时候采用缓存技术
{
string key = "CachE_Dish_All";
list = Utils.Cache(key) as List<E_Dish>;
if (list == null)
{
//执行查询语句
list = new List<E_Dish>();
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
list = conn.Query<E_Dish>(search.ToString(), eDish)?.ToList();
}
Utils.Cache(key, list, DateTime.Now.AddHours(1));
}
}
else
{
list = new List<E_Dish>();
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
list = conn.Query<E_Dish>(search.ToString(), eDish)?.ToList();
}
}
return list;
}
/// <summary>
/// 获取原料详情
/// </summary>
/// <param name="id">原料ID</param>
/// <returns>返回原料详情</returns>
public E_Dish GetDish(int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from Dish where id=@id ");
E_Dish model = new E_Dish();
model.id = id;
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
model = conn.Query<E_Dish>(strSql.ToString(), model)?.FirstOrDefault();
}
//更新缓存
Utils.Cache("CachE_Dish_All", null);
return model;
}
/// <summary>
/// 添加原料
/// </summary>
public int Add(E_Dish model)
{
//主查询Sql
string sql = @"INSERT INTO Dish
([name],[typeid],[cuisine],[taste],[texture],[cooking],[pic],[tag],[cookingmethod],[technicalpoints])
VALUES
(@name,@typeid,@cuisine,@taste,@texture,@cooking,@pic,@tag,@cookingmethod,@technicalpoints);select @@IDENTITY;";
//执行查询语句
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
int id = Convert.ToInt32(conn.ExecuteScalar(sql, model));
//更新缓存
Utils.Cache("CachE_Dish_All", null);
return id;
}
}
/// <summary>
/// 修改原料
/// </summary>
/// <returns>返回是否修改成功</returns>
public bool Update(E_Dish model)
{
//主查询Sql
StringBuilder strSql = new StringBuilder();
strSql.Append(@"UPDATE Dish
SET [name]=@name,[typeid]=@typeid,[cuisine]=@cuisine,[taste]=@taste,[texture]=@texture,
[cooking]=@cooking,[pic]=@pic,[tag]=@tag,[cookingmethod]=@cookingmethod,[technicalpoints]=@technicalpoints,
[nohandleraw]=@nohandleraw
WHERE id=@id");
//执行查询语句
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
bool result = conn.Execute(strSql.ToString(), model) > 0;
//更新缓存
Utils.Cache("CachE_Dish_All", null);
return result;
}
}
/// <summary>
/// 删除原料
/// </summary>
/// <returns>返回是否删除成功</returns>
public bool Del(int id)
{
//主查询Sql
StringBuilder search = new StringBuilder();
search.AppendFormat($@"delete from Dish WHERE id={id}");
//执行查询语句
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
bool result = conn.Execute(search.ToString()) > 0;
//更新缓存
Utils.Cache("CachE_Dish_All", null);
return result;
}
}
}
}
|
using System;
namespace GatewayEDI.Logging
{
/// <summary> Base class that extends <see cref="LogBase" /> with a custom <see cref="ILogItemFormatter" /> by implementing the <see cref="IFormattableLog" /> interface.<br />
/// Derive from this base class if you want to use simple string conversion for logged <see cref="LogItem" /> instances. </summary>
public abstract class FormattableLogBase : LogBase, IFormattableLog
{
private ILogItemFormatter formatter;
/// <summary> Creates a named log, and uses the default <see cref="SimpleLogItemFormatter" /> to format logged <see cref="LogItem" /> instances. </summary>
/// <param name="name"> The log name. </param>
protected FormattableLogBase(string name) : this(name, SimpleLogItemFormatter.Instance)
{
}
/// <summary> Creates the log, and uses the default <see cref="SimpleLogItemFormatter" /> to format logged <see cref="LogItem" /> instances. </summary>
/// <param name="name"> The log name. </param>
protected FormattableLogBase() : this(SimpleLogItemFormatter.Instance)
{
}
/// <summary> Creates the log with a given formatter. </summary>
/// <param name="formatter"> The formatter to be used in order to create string representations of logged <see cref="LogItem" /> instances. </param>
/// <exception cref="ArgumentNullException"> If <paramref name="formatter" /> is a null reference. </exception>
protected FormattableLogBase(ILogItemFormatter formatter)
: base()
{
SetFormatter(formatter);
}
/// <summary> Creates a named log with a given formatter. </summary>
/// <param name="name"> The log name. </param>
/// <param name="formatter"> The formatter to be used in order to create string representations of logged <see cref="LogItem" /> instances. </param>
/// <exception cref="ArgumentNullException"> If <paramref name="formatter" /> is a null reference. </exception>
protected FormattableLogBase(string name, ILogItemFormatter formatter)
: base(name)
{
SetFormatter(formatter);
}
/// <summary> Gets a given formatter which is used to produce the output of the logger. </summary>
/// <exception cref="ArgumentNullException"> If <paramref name="value" /> is a null reference. </exception>
public ILogItemFormatter Formatter
{
get { return formatter; }
private set { formatter = value; }
}
/// <summary> Sets a given formatter which is used to produce the output of the log. </summary>
/// <param name="formatter"> The formatter to be used in order to create string representations of logged <see cref="LogItem" /> instances. </param>
/// <exception cref="ArgumentNullException"> If <paramref name="formatter" /> is a null reference. </exception>
public void SetFormatter(ILogItemFormatter formatter)
{
if (formatter == null) throw new ArgumentNullException("formatter");
this.Formatter = formatter;
}
/// <summary> Simple helper method which returns the formatted string representation of the submitted <see cref="LogItem" /> by invoking the <see cref="ILogItemFormatter.FormatItem" /> method of the
/// assigned <see cref="Formatter" />. </summary>
/// <param name="item"> The item to be processed. </param>
/// <returns> Formatted logging data. </returns>
protected string FormatItem(LogItem item)
{
return Formatter.FormatItem(item);
}
}
} |
using Puppeteer.Core.Utility;
using UnityEditor;
using UnityEngine;
namespace Puppeteer.UI
{
internal static class PuppeteerEditorGUIHelper
{
static PuppeteerEditorGUIHelper()
{
ColorUtility.TryParseHtmlString(EditorGUIUtility.isProSkin ? "#191919" : "#8a8a8a", out var colour);
DIVIDER_COLOUR = colour;
}
public static void DrawGraphInspectorHeader(Texture _icon, string _typeText, string _headerText)
{
EditorGUILayout.BeginHorizontal();
GUILayout.Box(_icon);
EditorGUILayout.BeginVertical();
EditorGUILayout.LabelField(_typeText);
EditorGUILayout.LabelField(_headerText, INSPECTOR_HEADER_LABEL_STYLE);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
}
public static void DrawDivider()
{
var rect = GUILayoutUtility.GetRect(1f, 1f);
rect.xMin = 0f;
rect.width += 4f;
if (Event.current.type != EventType.Repaint)
return;
EditorGUI.DrawRect(rect, DIVIDER_COLOUR);
}
public static void DrawHorizontal(params string[] _entries)
{
EditorGUILayout.BeginHorizontal();
for (int i = 0; i < _entries.Length;)
{
EditorGUILayout.LabelField(_entries[i]);
if(++i < _entries.Length)
{
GUILayout.Space(0);
}
}
EditorGUILayout.EndHorizontal();
}
private static readonly GUIStyle INSPECTOR_HEADER_LABEL_STYLE = new GUIStyle()
{
normal = { textColor = EditorGUIUtility.isProSkin ? Color.white : Color.black },
fontSize = 16,
};
private static readonly Color DIVIDER_COLOUR;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AnyTest.IDataRepository;
using AnyTest.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace AnyTest.DataService.Controllers
{
///<inheritdoc />
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class SubjectsController : ApiControllerBase<Subject>
{
///<inheritdoc />
public SubjectsController(IRepository<Subject> repository) : base(repository) { }
///<inheritdoc />
[Authorize(Roles ="Administrator, Tutor")]
public override async Task<IActionResult> Post(Subject item) => await base.Post(item);
///<inheritdoc />
[Authorize(Roles = "Administrator, Tutor")]
public override async Task<IActionResult> Put(long id, Subject item) => await base.Put(id, item);
///<inheritdoc />
[Authorize(Roles = "Administrator, Tutor")]
public override async Task<IActionResult> Delete(long id) => await base.Delete(id);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace TAS.WebApi.Controllers
{
[Route("api/[controller]")]
public class ResultsController : Controller
{
// POST api/values
[HttpPost]
public async Task<ResultModel> Post([FromBody]ResultModel model)
{
var a = 1;
await Task.Delay(1);
return model;
}
private void ValidateResult(ResultModel model)
{
}
}
public class ResultModel
{
public Guid CompetitionId { get; set; }
public Guid CompetitorId { get; set; }
}
public class FieldShootingResult : ResultModel
{
public int Station { get; set; }
public int Hits { get; set; }
public int Targets { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Interactable : MonoBehaviour {
public string InteractMessage;
public virtual void OnEnter ()
{
}
public virtual void OnInteract()
{
}
public virtual void OnExit()
{
}
}
|
using System;
namespace C9FileHelpers
{
[Serializable]
public class ExTimeStamp
{
public ExTimeStamp(DateTime when)
{
Time = when;
Iso8601 = when.ToUniversalTime().ToString("yyyyMMddThhMMss.fffZ");
Raw = when.Ticks;
}
public DateTime Time
{
get;
}
public string Iso8601
{
get;
}
public long Raw
{
get;
}
}
}
|
namespace Alabo.Data.People.Users.Dtos
{
public class ConfirmPayPassword
{
public string PayPassWord { get; set; }
public long LoginUserId { get; set; }
}
} |
using CTMBowling.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CTMBowling
{
public class Functions
{
public static int CalculateScore(string scoreString)
{
var score = 0;
var game = GetGameFromString(scoreString);
score = game.Frames.Sum(x => x.FrameScore);
return score;
}
private static Game GetGameFromString(string scoreString)
{
var game = new Game();
game.Frames = GetListOfFramesFromString(scoreString);
return game;
}
private static List<Frame> GetListOfFramesFromString(string scoreString)
{
scoreString = scoreString
.Replace("XX","YY")
.Replace("||", "|")
.Replace("-", "0")
.Replace("X", "X0")
.Replace("YY","XX");
var frameList = scoreString
.Split('|')
.SkipWhile(x => x == "")
.Select(x => new Frame(x[0].ToString(), x[1].ToString())).ToList();
var count = 1;
foreach (Frame frame in frameList)
{
frame.FrameNumber = count;
count += 1;
}
frameList = AddFrameScores(frameList);
return frameList;
}
private static List<Frame> AddFrameScores(List<Frame> frameList)
{
var frameEnumerator = frameList.GetEnumerator();
foreach (Frame frame in frameList)
{
if (frame.FrameNumber < 10)
{
frame.FrameScore = getScoreForFrame(new List<Frame> { frame, frameList.Where(x => x.FrameNumber == frame.FrameNumber + 1 ).First(), frameList.Where(x => x.FrameNumber == frame.FrameNumber + 2).First() });
}
else if (frame.FrameNumber == 10)
{
frame.FrameScore = getScoreForBonusThrows(new List<Frame> { frame, frameList.Where(x => x.FrameNumber == frame.FrameNumber + 1).First() });
}
}
return frameList;
}
private static int getScoreForFrame(List<Frame> frames)
{
var scoreForFrame = 0;
var currentFrame = frames[0];
if (currentFrame.FirstThrow == "X")
{
scoreForFrame = 10;
scoreForFrame += getScoreAfterStrike(frames[1], frames[2], true);
}
else if (currentFrame.SecondThrow == "/")
{
scoreForFrame = 10;
scoreForFrame += getScoreAfterStrike(frames[1], frames[2], false);
}
else
{
scoreForFrame = int.Parse(currentFrame.FirstThrow) + int.Parse(currentFrame.SecondThrow);
}
return scoreForFrame;
}
private static int getScoreForBonusThrows(List<Frame> frames) {
var frameScore = 0;
var strikes = new List<String> { "/", "X" };
var currentFrame = frames[0];
var bonusThrows = frames[1];
if (strikes.Contains(currentFrame.FirstThrow))//must be X
{
frameScore += 10;
if (strikes.Contains(bonusThrows.FirstThrow))
{
frameScore += 10;
}
else
{
frameScore += int.Parse(bonusThrows.FirstThrow);
}
if (strikes.Contains(bonusThrows.SecondThrow))
{
frameScore += 10;
}
else
{
frameScore += int.Parse(bonusThrows.SecondThrow);
}
}
else if (strikes.Contains(currentFrame.SecondThrow))// must be /
{
frameScore += 10;
if (strikes.Contains(bonusThrows.FirstThrow))
{
frameScore += 10;
}
else
{
frameScore += int.Parse(bonusThrows.FirstThrow);
}
}
else
{
frameScore += int.Parse(currentFrame.FirstThrow) + int.Parse(currentFrame.SecondThrow);
}
return frameScore;
}
private static int getScoreAfterStrike(Frame nextFrame,Frame nextNextFrame, bool strike)
{
var strikes = new List<String> { "/", "X" };
var scoreForFrame = 0;
if (strike)
{
if (strikes.Contains(nextFrame.FirstThrow))//must be a X
{
scoreForFrame += 10;
if (strikes.Contains(nextNextFrame.FirstThrow))
{
scoreForFrame += 10;
}
else
{
scoreForFrame += int.Parse(nextNextFrame.FirstThrow);
}
}
else
{
scoreForFrame += int.Parse(nextFrame.FirstThrow);
if (strikes.Contains(nextFrame.SecondThrow))
{
scoreForFrame = 10;
}
else
{
if (strikes.Contains(nextNextFrame.FirstThrow))
{
scoreForFrame += 10;
}
else
{
scoreForFrame += int.Parse(nextNextFrame.FirstThrow);
}
}
}
}
else
{
if (strikes.Contains(nextFrame.SecondThrow))//must be a X
{
scoreForFrame += 10;
}
else
{
scoreForFrame += int.Parse(nextFrame.FirstThrow);
}
}
return scoreForFrame;
}
}
} |
using UnityEngine;
using UnityEngine.UI;
/*
This class Handles player UI.
*/
public class PlayerUI : MonoBehaviour
{
[SerializeField] private Slider healthBar;
public int maxHitpoints {
get {
return (int)healthBar.maxValue;
}
set {
healthBar.maxValue = value;
healthBar.value = value;
}
}
public void SetHealth (int hitpoints)
{
healthBar.value = hitpoints;
}
[SerializeField] private Text pointsText;
private int points;
public int Points {
get {
return points;
}
set {
points = value;
pointsText.text = value.ToString ();
}
}
public void Reset ()
{
Points = 0;
maxHitpoints = maxHitpoints;
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using CaveDwellers.Core.Movement;
using CaveDwellers.Core.TimeManagement;
using CaveDwellers.Mathematics;
using CaveDwellers.Positionables;
namespace CaveDwellers.Core
{
public class WorldMatrix : IWorldMatrix
{
private const int Scale = 1;
private readonly Dictionary<IPositionable, Point> _locations = new Dictionary<IPositionable, Point>();
private readonly Dictionary<Point, IPositionable> _objects = new Dictionary<Point, IPositionable>();
private int _timeElapsed;
public void Add(int x, int y, IPositionable @object)
{
Add(new Point(x * Scale, y * Scale), @object);
}
public void Add(Point point, IPositionable @object)
{
var width = @object.Size.Width * Scale;
var height = @object.Size.Height * Scale;
var wOffset = (width - width % 2) / 2;
var hOffset = (height - height % 2) / 2;
for (var w = 0; w < width; w++)
{
for (var h = 0; h < height; h++)
{
var p = new Point(point.X - wOffset + w, point.Y - hOffset + h);
_objects.Add(p, @object);
}
}
_locations.Add(@object, point);
}
private IPositionable IsCollision(IPositionable @object, Point newLocation)
{
var wOffset = (@object.Size.Width - @object.Size.Width % 2) / 2;
var hOffset = (@object.Size.Height - @object.Size.Height % 2) / 2;
for (var w = 0; w < @object.Size.Width; w++)
{
for (var h = 0; h < @object.Size.Height; h++)
{
var p = new Point(newLocation.X - wOffset + w, newLocation.Y - hOffset + h);
if (_objects.ContainsKey(p) && _objects[p] != null && _objects[p] != @object)
return _objects[p];
}
}
return null;
}
public IPositionable GetObjectAt(int x, int y)
{
return GetObjectAt(new Point(x, y));
}
public IPositionable GetObjectAt(Point point)
{
return _objects.ContainsKey(point)
? _objects[point]
: null;
}
public Point? GetLocationOf(IPositionable @object)
{
return _locations.ContainsKey(@object)
? _locations[@object]
: (Point?)null;
}
private void RemoveFromLocation(IPositionable @object)
{
var objectsToRemove = (from o in _objects where o.Value == @object select o.Key).ToList();
objectsToRemove.ForEach(o => _objects.Remove(o));
_locations.Remove(@object);
}
public void Move<T>(T @object)
where T : IAutoMoveable, IPositionable
{
var currentLocation = _locations[@object];
var destination = @object.NextDestination;
var distance = Calculator.CalculateDistance(currentLocation, destination);
var direction = Calculator.CalculateDirection(currentLocation, destination);
var newLocation = Calculator.CalculateNewPosition(currentLocation, direction, @object.Speed, _timeElapsed);
var distanceTraveled = Calculator.CalculateDistance(currentLocation, newLocation);
var subject = IsCollision(@object, newLocation);
if (distanceTraveled >= distance || subject != null)
{
@object.StopMoving();
@object.CollidedWith(subject);
}
else
{
RemoveFromLocation(@object);
Add(newLocation, @object);
}
}
public void Move(GoodGuy goodGuy, Direction direction)
{
var currentLocation = _locations[goodGuy];
var directionAngle = ((double) direction).ToRadians();
var newLocation = Calculator.CalculateNewPosition(currentLocation, directionAngle, goodGuy.Speed, _timeElapsed);
var subject = IsCollision(goodGuy, newLocation);
if (subject != null)
{
goodGuy.StopMoving();
goodGuy.CollidedWith(subject);
}
else
{
RemoveFromLocation(goodGuy);
Add(newLocation, goodGuy);
}
}
public IEnumerable<KeyValuePair<IPositionable, Point>> GetObjects()
{
return _locations;
}
private IEnumerable<T> GetObjects<T>()
{
return (from posit in _locations where posit.Key is T select (T)posit.Key).ToList();
}
public void Notify(GameTime gameTime)
{
_timeElapsed = gameTime.MillisecondsElapsed;
foreach (var m in GetObjects<IMoveable>())
{
m.Move();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace ClassesIerarchy
{
public class Repair
{
private string partName;
private int hoursWorked;
public Repair(string partName,int hoursWorked)
{
this.PartName = partName;
this.HoursWorked = hoursWorked;
}
public string PartName
{
get { return this.partName; }
set { this.partName = value; }
}
public int HoursWorked
{
get { return this.hoursWorked; }
set { this.hoursWorked = value; }
}
public override string ToString()
{
return $"Part Name{this.PartName} Hours Worked {this.HoursWorked}";
}
}
}
|
using ShopApi.Dtos;
using ShopApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ShopApi.Mapping
{
public class ProductMapper
{
public static ProductDto ProductToDto(Product entity)
{
var productDto = new ProductDto()
{
Name = entity.Name,
Description = entity.Description,
Slug = entity.Slug,
Price = entity.Price,
Quantity = entity.Quantity
};
return productDto;
}
public static Product ProductDtoToEntity(ProductDto dto)
{
var product = new Product()
{
Name = dto.Name,
Description = dto.Description,
Slug = dto.Slug,
Price = dto.Price,
Quantity = dto.Quantity
};
return product;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotnetSpider.Core;
using DotnetSpider.Data.Parser;
using DotnetSpider.Data.Storage.Model;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
namespace DotnetSpider.Data.Storage
{
/// <summary>
/// 文件类型
/// </summary>
public enum MySqlFileType
{
/// <summary>
/// LOAD
/// </summary>
LoadFile,
/// <summary>
/// INSERT SQL语句
/// </summary>
InsertSql
}
/// <summary>
/// 把解析到的爬虫实体数据存成SQL文件, 支持两种模式
/// LoadFile是批量导入模式通过命令 LOAD DATA LOCAL INFILE '{filePath}' INTO TABLE `{schema}`.`{dababase}` FIELDS TERMINATED BY '$' ENCLOSED BY '#' LINES TERMINATED BY '@END@' IGNORE 1 LINES; 还原。
/// InsertSql是完整的Insert SQL语句, 需要一条条执行来导入数据
/// </summary>
public class MySqlFileEntityStorage : EntityStorageBase
{
private readonly ConcurrentDictionary<string, StreamWriter> _writers =
new ConcurrentDictionary<string, StreamWriter>();
/// <summary>
/// 数据库忽略大小写
/// </summary>
public bool IgnoreCase { get; set; } = true;
public MySqlFileType MySqlFileType { get; set; }
public static MySqlFileEntityStorage CreateFromOptions(ISpiderOptions options)
{
var fileType = string.IsNullOrWhiteSpace(options.MySqlFileType)
? MySqlFileType.InsertSql
: (MySqlFileType) Enum.Parse(typeof(MySqlFileType),
options.MySqlFileType);
return new MySqlFileEntityStorage(fileType)
{
IgnoreCase = options.IgnoreCase
};
}
/// <summary>
/// 构造方法
/// </summary>
/// <param name="fileType">文件类型</param>
public MySqlFileEntityStorage(MySqlFileType fileType = MySqlFileType.LoadFile)
{
MySqlFileType = fileType;
}
public override void Dispose()
{
base.Dispose();
foreach (var writer in _writers)
{
try
{
writer.Value.Dispose();
}
catch (Exception e)
{
Logger?.LogError($"释放 MySqlFile 文件 {writer.Key} 失败: {e}");
}
}
}
protected override Task<DataFlowResult> Store(DataFlowContext context)
{
foreach (var item in context.GetParseItems())
{
var tableMetadata = (TableMetadata) context[item.Key];
var file = Path.Combine(Framework.BaseDirectory, "mysql-files",
$"{GenerateFileName(tableMetadata)}.sql");
switch (MySqlFileType)
{
case MySqlFileType.LoadFile:
{
WriteLoadFile(file, tableMetadata, item.Value);
break;
}
case MySqlFileType.InsertSql:
{
WriteInsertFile(file, tableMetadata, item.Value);
break;
}
}
}
return Task.FromResult(DataFlowResult.Success);
}
private void WriteInsertFile(string file, TableMetadata tableMetadata, IParseResult items)
{
StringBuilder builder = new StringBuilder();
var columns = tableMetadata.Columns;
var isAutoIncrementPrimary = tableMetadata.IsAutoIncrementPrimary;
var tableSql = GenerateTableSql(tableMetadata);
var insertColumns =
(isAutoIncrementPrimary ? columns.Where(c1 => c1.Key != tableMetadata.Primary.First()) : columns)
.ToArray();
foreach (var item in items)
{
builder.Append($"INSERT IGNORE INTO {tableSql} (");
var lastColumn = insertColumns.Last();
foreach (var column in insertColumns)
{
builder.Append(column.Equals(lastColumn) ? $"`{column.Key}`" : $"`{column.Key}`, ");
}
builder.Append(") VALUES (");
foreach (var column in insertColumns)
{
var value = column.Value.PropertyInfo.GetValue(item);
value = value == null ? "" : MySqlHelper.EscapeString(value.ToString());
builder.Append(column.Equals(lastColumn) ? $"'{value}'" : $"'{value}', ");
}
builder.Append($");{Environment.NewLine}");
}
StreamWriter writer = CreateOrOpen(file);
lock (writer)
{
writer.WriteLine(builder.ToString());
}
builder.Clear();
}
private void WriteLoadFile(string file, TableMetadata tableMetadata, IParseResult items)
{
StringBuilder builder = new StringBuilder();
var columns = tableMetadata.Columns;
var isAutoIncrementPrimary = tableMetadata.IsAutoIncrementPrimary;
var insertColumns =
(isAutoIncrementPrimary ? columns.Where(c1 => c1.Key != tableMetadata.Primary.First()) : columns)
.ToArray();
foreach (var item in items)
{
builder.Append("@END@");
foreach (var column in insertColumns)
{
var value = column.Value.PropertyInfo.GetValue(item);
value = value == null ? "" : MySqlHelper.EscapeString(value.ToString());
builder.Append("#").Append(value).Append("#").Append("$");
}
}
StreamWriter writer = CreateOrOpen(file);
lock (writer)
{
writer.WriteLine(builder.ToString());
}
builder.Clear();
}
protected virtual string GenerateTableSql(TableMetadata tableMetadata)
{
var tableName = GetNameSql(tableMetadata.Schema.Table);
var database = GetNameSql(tableMetadata.Schema.Database);
return string.IsNullOrWhiteSpace(database) ? $"`{tableName}`" : $"`{database}`.`{tableName}`";
}
private string GetNameSql(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return null;
}
return IgnoreCase ? name.ToLowerInvariant() : name;
}
private string GenerateFileName(TableMetadata tableMetadata)
{
return string.IsNullOrWhiteSpace(tableMetadata.Schema.Database)
? $"{tableMetadata.Schema.Table}"
: $"{tableMetadata.Schema.Database}.{tableMetadata.Schema.Table}";
}
private StreamWriter CreateOrOpen(string file)
{
return _writers.GetOrAdd(file, x =>
{
var folder = Path.GetDirectoryName(x);
if (!string.IsNullOrWhiteSpace(folder) && !Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
return new StreamWriter(File.OpenWrite(x), Encoding.UTF8);
});
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DelftTools.Functions.Filters;
using DelftTools.Functions.Generic;
using DelftTools.Utils.Reflection;
namespace DelftTools.Functions.Conversion
{
/// <summary>
/// Converts a variable in a function to another type :
/// For example a function x(DateTime) can be converted to x(Double)
/// by specifying a converter between datetime and double
/// </summary>
/// <typeparam name="TTarget"></typeparam>
/// <typeparam name="TSource"></typeparam>
public class ConvertedFunction<TTarget,TSource> : Function where TSource : IComparable where TTarget : IComparable
{
//private EventedList<IVariable> arguments;
protected IVariable convertedVariable;
protected IVariable<TSource> variableToConvert;
protected Func<TTarget, TSource> toSource;
protected Func<TSource, TTarget> toTarget;
/// <summary>
///
/// </summary>
/// <param name="parent">Function to convert</param>
/// <param name="variableToConvert">Variable inside the function to convert</param>
/// <param name="toSource">Method to convert from TTarget to TSource</param>
/// <param name="toTarget">Method to convert from TTarget to TSource</param>
public ConvertedFunction(IFunction parent, IVariable<TSource> variableToConvert, Func<TTarget, TSource> toSource, Func<TSource, TTarget> toTarget)
{
Parent = parent;
this.variableToConvert = variableToConvert;
this.toSource = toSource;
this.toTarget = toTarget;
foreach (IVariable arg in parent.Arguments)
{
Arguments.Add(CreateConvertedVariable(arg));
}
foreach (IVariable com in parent.Components)
{
if (com == parent)
{
continue;//skip variable which are there own components.
}
//TODO: get rid of this stuff. Need it now because we get the arguments twice otherwise :(
Components.CollectionChanged -= Components_CollectionChanged;
Components.Add(CreateConvertedVariable(com));
Components.CollectionChanged += Components_CollectionChanged;
}
}
private IVariable CreateConvertedVariable(IVariable variable)
{
IVariable returnVariable;
//have to do some reflection to get the types right.
if (variableToConvert == variable)
{
returnVariable = new ConvertedVariable<TTarget, TTarget, TSource>(variable, variableToConvert, toSource, toTarget);
}
else
{
Type[] types = new[] { variable.ValueType, typeof(TTarget), typeof(TSource) };
returnVariable = (IVariable)TypeUtils.CreateGeneric(typeof(ConvertedVariable<,,>), types, variable, variableToConvert, toSource,
toTarget);
}
returnVariable.Name = variable.Name;
return returnVariable;
}
public override IMultiDimensionalArray<T> GetValues<T>(params IVariableFilter[] filters)
{
return (IMultiDimensionalArray<T>)new ConvertedArray<TTarget, TSource>(Parent.GetValues<TSource>(ConvertFilters(filters)), toSource, toTarget);
}
public override IMultiDimensionalArray GetValues(params IVariableFilter[] filters)
{
if (Parent == variableToConvert)
{
return
new ConvertedArray<TTarget, TSource>(Parent.GetValues<TSource>(ConvertFilters(filters)), toSource,
toTarget);
}
return Parent.GetValues(ConvertFilters(filters));
}
//TODO: get this more clear
protected override void SetValues<T>(IEnumerable<T> values, params IVariableFilter[] filters)
{
Parent.SetValues(values, ConvertFilters(filters));
}
public override void SetValues(IEnumerable values, params IVariableFilter[] filters)
{
base.SetValues(values, ConvertFilters(filters));
}
private IVariableFilter[] ConvertFilters(IVariableFilter[] filters)
{
//rewrite variable value filter to the domain of the source.
IList<IVariableFilter> filterList = new List<IVariableFilter>();
foreach (var filter in filters)
{
//TODO: rewrite to IEnumerable etc
if (filter is IVariableValueFilter && filter.Variable.Parent == variableToConvert)
{
var variableValueFilter = filter as IVariableValueFilter;
IList values = new List<TSource>();
foreach (TTarget obj in variableValueFilter.Values)
{
values.Add(toSource(obj));
}
filterList.Add(variableToConvert.CreateValuesFilter(values));
}
else
{
filterList.Add(filter);
}
}
return filterList.ToArray();
}
}
} |
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;
namespace IpSwitcher
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void exitButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void SwitchButton_Click(object sender, EventArgs e)
{
if (ipListBox.Items.Count != 0)
{
String ipAddress = ipListBox.SelectedValue.ToString();
MessageBox.Show("Ip changing to " + ipAddress);
LocalIpChanger.setLocalIpAddressHelper("", ipAddress, "255.255.255.0", ipAddress.Substring(0, ipAddress.LastIndexOf('.')) + ".1", "8.8.8.8");
NetWorkHelper.restartEthernet();
}
doRefresh();
}
private void aboutButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Please Use!!!");
}
private void MainForm_Load(object sender, EventArgs e)
{
doRefresh();
}
private void refreshButton_Click(object sender, EventArgs e)
{
doRefresh();
}
private void doRefresh()
{
ArrayList ips = ReadIni.ReadAllIps();
if (ips.Count != 0)
ipListBox.DataSource = ips;
else
{
MessageBox.Show("Please edit config file 'IpSwitcher.ini' first ,after that do Refresh !!!");
System.Diagnostics.Process pro = new System.Diagnostics.Process();
pro.StartInfo.FileName = "notepad.exe ";
pro.StartInfo.Arguments = "IpSwitcher.ini";
pro.Start();
}
currentIplabel.Text = "Current IpAddr:" + LocalIpChanger.getLocalIpAddress();
}
private void openButton_Click(object sender, EventArgs e)
{
System.Diagnostics.Process pro = new System.Diagnostics.Process();
pro.StartInfo.FileName = "notepad.exe ";
pro.StartInfo.Arguments = "IpSwitcher.ini";
pro.Start();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Description résumée de ContactClient
/// </summary>
public class ContactClient : Contact
{
private String referenceClient;
private string situationMatrimoniale;
public ContactClient(string nom, string situationMatrimoniale, string telephone, string email, string adresse, string adresse2, string cp, string ville) : base(nom, telephone, email, adresse, adresse2,cp, ville)
{
this.SituationMatrimoniale = situationMatrimoniale;
}
public ContactClient(String referenceClient, string nom, string situationMatrimoniale, string telephone, string email, string adresse, string adresse2, string cp, string ville) : base(nom, telephone, email, adresse, adresse2, cp, ville)
{
}
public string ReferenceClient
{
get
{
return referenceClient;
}
set
{
referenceClient = value;
}
}
public string SituationMatrimoniale
{
get
{
return situationMatrimoniale;
}
set
{
situationMatrimoniale = value;
}
}
} |
using Pe.Stracon.Politicas.Infraestructura.CommandModel.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.Politicas.Infraestructura.CommandModel.General
{
/// <summary>
/// Clase que representa la entidad trabajadorUnidadOperativa
/// </summary>
/// <remarks>
/// Creación: GMD 20150107 <br />
/// Modificación: <br />
/// </remarks>
public class TrabajadorUnidadOperativaEntity : Entity
{
/// <summary>
/// Código de TrabajadorUnidadOperativa
/// </summary>
public Guid? CodigoTrabajadorUnidadOperativa { get; set; }
/// <summary>
/// Código de Unidad Operativa Matriz
/// </summary>
public Guid CodigoUnidadOperativaMatriz { get; set; }
/// <summary>
/// Código de Trabajador
/// </summary>
public Guid? CodigoTrabajador { get; set; }
/// <summary>
/// Código de unidad operativa
/// </summary>
public Guid? CodigoUnidadOperativa { get; set; }
}
}
|
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace DamianTourBackend.Api.Hubs
{
public class TrackingHub : Hub
{
public Task JoinGroup(string groupName) =>
Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}
} |
using EasyBuy.Models;
using EasyBuyCR.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace EasyBuy.Controllers
{
public class ProductoController : Controller
{
List<Producto> listaProductos = new List<Producto>();
OracleConection con = new OracleConection();
public ActionResult EmpresaIndex()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult RegistrarProducto()
{
ViewBag.Message = "Your contact page.";
return View();
}
// GET: Producto
public ActionResult Index()
{
return RedirectToAction("RegistrarProducto", "Producto");
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult RegistrarProducto(Producto producto)
{
String mensaje = "";
int id_producto = 0;
bool estado = false;
try
{
String id = (String)Session["Correo"];
producto.id_empresa = id;
id_producto = con.GuardarProducto(producto);
mensaje = "El producto se ha ingresado correctamente \n";
estado = true;
}
catch (Exception exc)
{
mensaje = "Error al crear producto" + exc.Message;
}
return new JsonResult { Data = new { estado = estado, mensaje = mensaje, id_producto = id_producto } };
}
public ActionResult AgregarDetalle()
{
return PartialView("_AgregarDetalle");
}
public ActionResult AgregarDetalleCP()
{
return PartialView("_AgregarDetalle");
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult AgregarDetalle(detalle_producto detalle)
{
bool estado = false;
string mensaje = "";
try
{
con.guardarDetalle(detalle);
mensaje = "Detalle ingresada correctamente \n";
estado = true;
}
catch (Exception exc)
{
mensaje = "Error al crear la detalle" + exc.Message;
}
return new JsonResult { Data = new { estado = estado, mensaje = mensaje } };
}
public ActionResult ObtenerDetalle(int id_producto)
{
return PartialView("_TablaDetalle", con.getDetalles(id_producto));
}
public ActionResult ObtenerDetalleCP(int id_producto)
{
//ViewBag.direccion = "CP";
return PartialView("_TablaDetalle", con.getDetalles(id_producto));
}
public ActionResult EliminarDetalle(int id)
{
if (id < 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
detalle_producto detalle = con.ObtenerDetalle(id);
return PartialView(detalle);
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("EliminarDetalle")]
public JsonResult Eliminar(int id_detalle)
{
bool estado = false;
string mensaje = "";
try
{
if (id_detalle < 0)
{
mensaje = "EL id no puede ser negativo";
}
con.EliminarDetalle(id_detalle);
estado = true;
mensaje = "Detalle eliminada...";
}
catch (Exception exc)
{
mensaje = "Error al eliminar Detalle" + exc;
}
return new JsonResult { Data = new { estado = estado, mensaje = mensaje } };
}
public ActionResult EliminarProducto(int id)
{
String correo_tienda = (String)Session["Correo"];
if (id < 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Producto producto = con.ObtenerProducto(id);
return PartialView(producto);
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("EliminarProducto")]
public JsonResult EliminarProduct(int id_producto)
{
bool estado = false;
string mensaje = "";
try
{
if (id_producto < 0)
{
mensaje = "EL id no puede ser negativo";
}
con.EliminarDetallesProducto(id_producto);
con.EliminarProducto(id_producto);
estado = true;
mensaje = "Producto eliminado...";
}
catch (Exception exc)
{
mensaje = "Error al eliminar Producto" + exc;
}
return new JsonResult { Data = new { estado = estado, mensaje = mensaje } };
}
public ActionResult ProductosInventario()
{
String correo_tienda = (String)Session["Correo"];
Session["Notificaciones"] = null;
return View(con.getProducto(correo_tienda));
}
public ActionResult AgregarPromocion(int id)
{
ViewBag.id_detalle = id.ToString();
return PartialView("_AgregarPromocion");
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult AgregarPromocion(Promocion promocion)
{
bool estado = false;
string mensaje = "";
try
{
con.guardarPromocion(promocion);
mensaje = "Promocion ingresada correctamente \n";
estado = true;
}
catch (Exception exc)
{
mensaje = "Error al guardar la promocion" + exc.Message;
}
return new JsonResult { Data = new { estado = estado, mensaje = mensaje } };
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult ObtenerDetalle2(int id)
{
bool estado = false;
detalle_producto det = new detalle_producto();
try
{
det = con.ObtenerDetalle(id);
estado = true;
}
catch (Exception exc)
{
}
//String Palimentacion = capa.CostoAlimentacion+"";
String Det = "";
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Det = javaScriptSerializer.Serialize(det);
return new JsonResult { Data = new { estado = estado, Det = Det } };
}
public ActionResult EditarDetalle(int id)
{
if (id < 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
detalle_producto det = con.ObtenerDetalle(id);
ViewBag.detalle_producto = det;
if (det == null)
{
return HttpNotFound();
}
return PartialView(det);
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult EditarDetalle(detalle_producto det)
{
bool estado = false;
string mensaje = "";
try
{
if (det.id_detalle > 0) {
con.editarDetalle(det);
estado = true;
mensaje = "Detalle modificada exitosamente";
}
else
{
mensaje = "Error al actualizar Detalle";
}
}
catch (Exception ex)
{
mensaje = "Error al actualizar Detalle";
}
return new JsonResult { Data = new { estado = estado, mensaje = mensaje } };
}
}
} |
using HabMap.Views;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System.Linq;
using System;
using System.Windows.Controls;
namespace HabMap.ViewModels
{
public class MainWindowViewModel : BindableBase
{
private IRegionManager _regionManager;
private string _title = "HabMap";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public DelegateCommand<object> CloseTabCommand { get; private set; }
public DelegateCommand<SelectionChangedEventArgs> TabSelectionChangedCommand { get; private set; }
public MainWindowViewModel(IRegionManager regionManager)
{
_regionManager = regionManager;
_regionManager.RegisterViewWithRegion("ToolbarRegion", typeof(ToolbarView));
_regionManager.RegisterViewWithRegion("StatusbarRegion", typeof(StatusbarView));
CloseTabCommand = new DelegateCommand<object>(ExecuteCloseTabCommand, CanExecuteCloseTabCommand);
TabSelectionChangedCommand = new DelegateCommand<SelectionChangedEventArgs>(OnTabSelectionChangedCommand);
}
private bool CanExecuteCloseTabCommand(object obj)
{
return true;
}
private void ExecuteCloseTabCommand(object obj)
{
_regionManager.Regions["MainRegion"].Remove(obj);
}
private void OnTabSelectionChangedCommand(SelectionChangedEventArgs obj)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WziumStars.Models.ViewModels
{
public class ProduktViewModel
{
public Produkt Produkt { get; set; }
public IEnumerable<Kategoria> Kategoria { get; set; }
public IEnumerable<Podkategoria> Podkategoria { get; set; }
}
}
|
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TopTrumpsHCML.Entities;
using TopTrumpsHCML.Models;
namespace TopTrumpsHCML.Mappings
{
public class EntitiesToViewModelMappingProfile : Profile
{
/// <summary>
/// Create mapping in constructor of entities to View-Model
/// </summary>
public EntitiesToViewModelMappingProfile()
{
//.ForMember(dest => dest.baz, opt => opt.Condition(src => (src.baz >= 0));
CreateMap<Starship, CardViewModel>()
.ForMember(cardVm => cardVm.Credits, map => map.MapFrom(startShip => startShip.cost_in_credits))
.ForMember(cardVm => cardVm.Ratings, map => map.MapFrom(startShip => startShip.hyperdrive_rating))
.ForMember(cardVm => cardVm.Speed, map => map.MapFrom(startShip => startShip.MGLT))
.ForMember(cardVm => cardVm.Films, map => map.MapFrom(startShip => startShip.films.Count.ToString()))
.ForMember(cardVm => cardVm.Crew, map => map.MapFrom(startShip => startShip.crew))
.ForMember(cardVm => cardVm.Model, map => map.MapFrom(startShip => startShip.model))
.ForMember(cardVm => cardVm.Manufacturer, map => map.MapFrom(startShip => startShip.manufacturer))
.ForMember(cardVm => cardVm.Pilot, map => map.MapFrom((starShip => starShip.pilots.Count > 0 ? starShip.pilots.Count.ToString() : "0")));
//map the first pilot if starship has any pilot or you could make a heept request to get the pilot name
}
}
} |
using Conjure.Data;
using Example.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
namespace Example.Server.Data
{
public class ServerWeatherForecastService : IWeatherForecastService
{
public const int RowCount = 5000;
private static string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private static DateTime _lastUpdateTime = DateTime.MinValue;
private static IEnumerable<WeatherForecast> _lastUpdateData;
public Task<FetchResult<WeatherForecast>> GetForecastAsync(FetchOptions options)
{
if ((DateTime.Now - _lastUpdateTime).TotalMinutes > 5.0)
{
lock (typeof(ServerWeatherForecastService))
{
if ((DateTime.Now - _lastUpdateTime).TotalMinutes > 5.0)
{
GenerateForecasts();
}
}
}
var rows = _lastUpdateData;
if (options.Sort != null)
{
foreach (var sortCol in options.Sort.Split(','))
{
var desc = sortCol.StartsWith("-");
var propName = desc ? sortCol.Substring(1) : sortCol;
var p = typeof(WeatherForecast).GetProperty(propName, System.Reflection.BindingFlags.IgnoreCase
| System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
if (desc)
rows = rows.OrderByDescending(wf => p.GetValue(wf));
else
rows = rows.OrderBy(wf => p.GetValue(wf));
}
}
if (options.Skip.HasValue)
rows = rows.Skip(options.Skip.Value);
if (options.Take.HasValue)
rows = rows.Take(options.Take.Value);
return Task.FromResult(new FetchResult<WeatherForecast>
{
TotalCount = _lastUpdateData.Count(),
Items = rows,
});
}
private void GenerateForecasts()
{
var rng = new Random();
_lastUpdateData = Enumerable.Range(1, RowCount).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = "SVR:" + Summaries[rng.Next(Summaries.Length)]
}).ToArray();
_lastUpdateTime = DateTime.Now;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using TraceWizard.Entities;
namespace TraceWizard.TwApp {
public partial class FixtureProfileRow : UserControl {
public FixtureProfile FixtureProfile;
public FixtureProfilesEditor FixtureProfilesEditor;
public FixtureProfileRow() {
InitializeComponent();
}
public void Initialize() {
InitializeTextBoxes();
InitializeButton();
BuildRow();
}
void InitializeButton() {
Button.PreviewKeyDown +=new KeyEventHandler(Button_PreviewKeyDown);
Button.Click += new RoutedEventHandler(Button_Click);
}
public void TextBox_PreviewDrop(object sender, DragEventArgs e) {
FixtureProfilesEditor.DragDrop(sender, e, FixtureProfile);
}
void Button_PreviewKeyDown(object sender, KeyEventArgs e) {
switch (e.Key) {
case Key.Up:
FixtureProfilesEditor.MoveUp(this);
break;
case Key.Down:
FixtureProfilesEditor.MoveDown(this);
break;
case Key.Delete:
case Key.Back:
FixtureProfilesEditor.Delete(this);
break;
}
}
void Button_Click(object sender, RoutedEventArgs e) {
FixtureProfilesEditor.SelectRow(this);
}
public void Select() {
SetBrush(Brushes.LightGray);
}
void SetBrush(Brush brush) {
foreach (var child in Grid.Children) {
var textBox = child as TextBox;
if (textBox != null)
textBox.Background = brush;
}
FixtureClassSelector.ComboBoxFixtureClass.Background = brush;
}
public void ClearSelection() {
if (Button.IsChecked != false)
Button.IsChecked = false;
SetBrush(Brushes.Transparent);
}
void InitializeTextBoxes() {
foreach (var child in Grid.Children) {
var textBox = child as TextBox;
if (textBox != null) {
textBox.HorizontalAlignment = HorizontalAlignment.Stretch;
textBox.VerticalAlignment = VerticalAlignment.Stretch;
textBox.HorizontalContentAlignment = HorizontalAlignment.Right;
textBox.VerticalContentAlignment = VerticalAlignment.Center;
textBox.Padding = new Thickness(0, 0, 3, 0);
textBox.Background = Brushes.Transparent;
textBox.AllowDrop = true;
// textBox.Drop += new DragEventHandler(FixtureProfilesEditor.DragDrop);
textBox.PreviewDragOver += new DragEventHandler(FixtureProfilesEditor.TextBox_PreviewDragEnter);
textBox.PreviewDragEnter += new DragEventHandler(FixtureProfilesEditor.TextBox_PreviewDragEnter);
textBox.PreviewDrop += new DragEventHandler(TextBox_PreviewDrop);
textBox.PreviewMouseDown +=new MouseButtonEventHandler(textBox_PreviewMouseDown);
}
}
}
void textBox_PreviewMouseDown(object sender, MouseButtonEventArgs e) {
if (FixtureProfilesEditor.RowSelected == this) {
ClearSelection();
FixtureProfilesEditor.RowSelected = null;
}
// e.Handled = true;
}
string GetString(double? value) {
return value.HasValue ? value.Value.ToString("0.00") : string.Empty;
}
string GetString(TimeSpan? value) {
return value.HasValue ? new TwHelper.LimitedDurationConverter().Convert(value, null, null, null).ToString() : string.Empty;
}
void BuildRow() {
this.FixtureClassSelector.FixtureClass = FixtureProfile.FixtureClass;
this.MinVolume.Text = GetString(FixtureProfile.MinVolume);
this.MaxVolume.Text = GetString(FixtureProfile.MaxVolume);
this.MinPeak.Text = GetString(FixtureProfile.MinPeak);
this.MaxPeak.Text = GetString(FixtureProfile.MaxPeak);
this.MinMode.Text = GetString(FixtureProfile.MinMode);
this.MaxMode.Text = GetString(FixtureProfile.MaxMode);
this.MinDuration.Text = GetString(FixtureProfile.MinDuration);
this.MaxDuration.Text = GetString(FixtureProfile.MaxDuration);
}
public FixtureClassSelector AddFixtureClassSelector(FixtureClass fixtureClass, int row, int column) {
FixtureClassSelector fixtureClassSelector = new FixtureClassSelector();
fixtureClassSelector.Margin = new Thickness(0, 0, 0, 0);
fixtureClassSelector.Padding = new Thickness(0, 0, 0, 0);
fixtureClassSelector.FixtureClass = fixtureClass;
Grid.SetRow(fixtureClassSelector, row);
Grid.SetColumn(fixtureClassSelector, column);
return fixtureClassSelector;
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class Window_Seconds : MonoBehaviour {
public List<Image> _image_List;
float _time;
float _keep_Time;
void OnEnable(){
_time = 0;
_keep_Time = 0;
MyAudio.PlayAudio(StaticParameter.s_Countdown, false, StaticParameter.s_Countdown_Volume);
}
// Update is called once per frame
void Update () {
_time += Time.deltaTime;
if (_time > 0 && _time < 0.6f)
{
Change(3);
}
else if(_time >=0.6f && _time < 1.2f)
{
Change(2);
}
else if(_time >= 1.2f && _time < 1.8f)
{
Change(1);
}
else
{
transform.parent.gameObject.SetActive(false);
ResetGameObject();
MyKeys.Pause_Game = false;
if(HumanManager.Nature.HumanManager_Script.CurrentState == HumanState.Dead)
{
ResetHero();
}
GameUITool.Instance.Prefab_Dictionary[GameUI.GameUI_MyMask].SetActive(false);
}
}
void Change(int mark)
{
_keep_Time += Time.deltaTime;
if (_keep_Time >= 0.6f)
{
_keep_Time = 0;
for (int i = 1; i < 4; i++)
{
if (i == mark)
{
_image_List[i].gameObject.SetActive(true);
}
else
{
_image_List[i].gameObject.SetActive(false);
}
}
}
}
void ResetGameObject()
{
_image_List[1].gameObject.SetActive(false);
_image_List[3].gameObject.SetActive(true);
for (int i = 0; i < 4; i++)
{
_image_List[i].fillAmount = 1;
}
}
void ResetHero()
{
HumanManager.Nature.Human.gameObject.SetActive(true);
HumanManager.Nature.HumanManager_Script.CurrentState = HumanState.Stop;
HumanManager.Nature.HumanManager_Script.ItemState = ItemState.Dash;
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using TenmoServer.Models;
namespace TenmoServer.DAO
{
public class AccountSqlDAO : IAccountDAO
{
private readonly string connectionString;
public AccountSqlDAO(string dbConnectionString)
{
connectionString = dbConnectionString;
}
public List<Account> GetAccounts(int user_id)
{
List<Account> list = new List<Account> { };
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * from accounts WHERE user_id = @user_id", conn);
cmd.Parameters.AddWithValue("@user_id", user_id);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.HasRows && reader.Read())
{
Account account = new Account();
account.Balance = Convert.ToDecimal(reader["balance"]);
account.AccountId = Convert.ToInt32(reader["account_id"]);
list.Add(account);
}
}
}
catch (SqlException)
{
throw;
}
return list;
}
}
}
|
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WorkerService.Helpers;
using APIClient;
namespace WorkerService.Workers
{
public interface IWorker
{
int DoWork(IConfiguration config);
}
public class Worker : IWorker
{
public object WebAPIClient { get; private set; }
/// <summary>
/// will perform connect to the Data provider and then return the number of digits from 0-9
/// </summary>
public int DoWork(IConfiguration config)
{
int countOfDigits = 0;
try
{
///First go to the Data provider and get the guid
string DataProviderURL = (string)config.GetValue(typeof(string), "DataProvider");
string guid = ConnectToDataProvider(DataProviderURL);
countOfDigits = CountDigits(guid);
//now pass the count of the digits to the aggregator
string AggregatorURL = (string)config.GetValue(typeof(string), "Aggregator");
ConnectToAggregator(AggregatorURL, countOfDigits);
}
catch(Exception ex)
{
}
return countOfDigits;
}
private int CountDigits(string guid)
{
if(!GuidHelper.IsValidGuid(guid))
{
throw new Exception("Invalid guid specified");
}
return GuidHelper.CountDigitsInGuid(guid);
}
private string ConnectToDataProvider(string DataProviderURL)
{
WebAPIClient client = new WebAPIClient();
string guid = client.ConnectToDataProvider(DataProviderURL);
return guid;
}
private void ConnectToAggregator(string DataProviderURL, int count)
{
WebAPIClient client = new WebAPIClient();
client.ConnectToAggregator(DataProviderURL, count);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class TreeNode {
protected BehaviorTreeController btController;
//constructor
public TreeNode(BehaviorTreeController btController)
{
this.btController = btController;
}
public abstract NodeStatus Tick();
}
public enum NodeStatus
{
SUCCESS,
FAILURE,
RUNNING
}
|
namespace WinAppUpdater.Core.Models.Updates
{
class Configuration
{
#region Properties
public string URL { get; set; }
public URLType URLType { get; set; }
public string AppName { get; set; }
public string AppVersion { get; set; }
#endregion
}
}
|
using SteamKit2;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace SteamUpdateBlocker {
class AppInfo {
private static SteamClient steamClient;
private static SteamApps steamApps;
private static SteamUser steamUser;
private static CallbackManager manager;
private static bool inLogin;
private static bool inQuery;
private static JobID infoRequest = JobID.Invalid;
private string manifestId = "";
private static bool loggedIn = false;
private List<string> depotRequest;
private Dictionary<string, string> manifestData;
private static uint currentQuery = 218620;
~AppInfo() {
steamUser?.LogOff();
}
public async Task<bool> Initialize() {
if (loggedIn)
return loggedIn;
// initialize a client and a callback manager for responding to events
steamClient = new SteamClient();
manager = new CallbackManager(steamClient);
// get a handler and register to callbacks we are interested in
steamUser = steamClient.GetHandler<SteamUser>();
steamApps = steamClient.GetHandler<SteamApps>();
manager.Subscribe<SteamApps.PICSProductInfoCallback>(OnProductInfo);
manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
inLogin = true;
Debug.WriteLine("Connecting to Steam...");
await Task.Run(() => {
steamClient.Connect();
while (inLogin) {
manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
}
});
return loggedIn;
}
public async Task<string> TryRetrieve() {
manifestId = null;
// initialize a client and a callback manager for responding to events
steamClient = new SteamClient();
manager = new CallbackManager(steamClient);
// get a handler and register to callbacks we are interested in
steamUser = steamClient.GetHandler<SteamUser>();
steamApps = steamClient.GetHandler<SteamApps>();
manager.Subscribe<SteamApps.PICSProductInfoCallback>(OnProductInfo);
manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
inLogin = true;
await Task.Run(() => {
Debug.WriteLine("Connecting to Steam...");
steamClient.Connect();
while (inLogin)
manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
});
return manifestId;
}
static void OnConnected(SteamClient.ConnectedCallback callback) {
Debug.WriteLine("Successfully connected to Steam");
// log on anonymously
steamUser.LogOnAnonymous();
}
static void OnDisconnected(SteamClient.DisconnectedCallback callback) {
Debug.WriteLine("Disconnected from Steam");
inLogin = false;
}
static void OnLoggedOn(SteamUser.LoggedOnCallback callback) {
if (callback.Result != EResult.OK) {
if (callback.Result == EResult.AccountLogonDenied) {
// this shouldn't happen when logging in anonymously
Debug.WriteLine("Unable to login to Steam");
inLogin = false;
return;
}
// if there is another error
Debug.WriteLine("Unable to login to Steam: {0} / {1}", callback.Result, callback.ExtendedResult);
inLogin = false;
return;
}
inLogin = false;
loggedIn = true;
Debug.WriteLine("Successfully logged in to Steam");
}
public async Task<Dictionary<string, string>> QueryDepots(string appid, List<string> installedDepots) {
currentQuery = uint.Parse(appid);
depotRequest = installedDepots;
await Task.Run(() => {
Debug.WriteLine("Quering for appid {0}", appid);
inQuery = true;
manifestData = null; // reset manifestData to null
// request appid
infoRequest = steamApps.PICSGetProductInfo(currentQuery, null);
while (inQuery)
manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
});
// query should be done, can return manifestData
return manifestData;
}
private void OnProductInfo(SteamApps.PICSProductInfoCallback callback) {
Debug.WriteLine("In OnProductInfo callback");
if (callback.JobID != infoRequest) {
return;
}
// pass callback to GetLatestDepots
manifestData = GetLatestDepots(callback.Apps);
inQuery = false;
Debug.WriteLine("Finished parsing manifest data");
}
// returns a dictionary where key is the depot id and the value is the latest manifest
private Dictionary<string, string> GetLatestDepots(Dictionary<uint, SteamApps.PICSProductInfoCallback.PICSProductInfo> apps) {
Dictionary<string, string> latestDepots = new Dictionary<string, string>();
// iterate over all installed depots to find the latest manifest
foreach (string depotId in depotRequest) {
try {
var manifest = apps[currentQuery]?.KeyValues.Children
.FirstOrDefault(x => x.Name == "depots")?.Children
.FirstOrDefault(x => x.Name == depotId.ToString())?.Children
.FirstOrDefault(x => x.Name == "manifests")?.Children
.FirstOrDefault(x => x.Name == "public")?.Value;
latestDepots.Add(depotId, manifest);
} catch (KeyNotFoundException) {
Debug.WriteLine("Key wasn't found for depot id {0}", depotId);
}
}
return latestDepots;
}
static void OnLoggedOff(SteamUser.LoggedOffCallback callback) {
Debug.WriteLine("Logged off Steam: {0}", callback.Result);
inLogin = false;
}
}
}
|
using UnityEngine;
using System.Collections;
public class Quizz : MonoBehaviour {
[SerializeField] private string m_name;
private Question[] m_questions;
private System.Random m_rng = new System.Random();
void Start ()
{
m_questions = GetComponentsInChildren<Question>();
}
private void Shuffle<T>(T[] array)
{
int n = array.Length;
for (int i = 0; i < n; i++)
{
int r = i + (int)(m_rng.NextDouble() * (n - i));
T t = array[r];
array[r] = array[i];
array[i] = t;
}
}
public void Play()
{
Shuffle<Question>(m_questions);
}
public IEnumerator GetEnumerator()
{
foreach (Question p in m_questions)
{
if (p == null)
{
continue;
}
yield return p;
}
}
public string Name { get { return m_name; } }
}
|
using System.Linq;
using Robust.Shared.Random;
using Content.Server.Body.Systems;
using Content.Server.Disease.Components;
using Content.Server.Disease.Zombie.Components;
using Content.Server.Drone.Components;
using Content.Server.Weapon.Melee;
using Content.Shared.Chemistry.Components;
using Content.Shared.Damage;
using Content.Shared.MobState.Components;
using Content.Server.Disease;
using Content.Server.Weapons.Melee.ZombieTransfer.Components;
namespace Content.Server.Weapons.Melee.ZombieTransfer
{
public sealed class ZombieTransferSystem : EntitySystem
{
[Dependency] private readonly DiseaseSystem _disease = default!;
[Dependency] private readonly BloodstreamSystem _bloodstream = default!;
[Dependency] private readonly IRobustRandom _robustRandom = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ZombieTransferComponent, MeleeHitEvent>(OnMeleeHit);
}
private void OnMeleeHit(EntityUid uid, ZombieTransferComponent component, MeleeHitEvent args)
{
if (!EntityManager.TryGetComponent<DiseaseZombieComponent>(args.User, out var diseaseZombieComp))
return;
if (!args.HitEntities.Any())
return;
foreach (EntityUid entity in args.HitEntities)
{
if (args.User == entity)
continue;
if (!HasComp<MobStateComponent>(entity) || HasComp<DroneComponent>(entity))
continue;
if (_robustRandom.Prob(diseaseZombieComp.Probability) && HasComp<DiseaseCarrierComponent>(entity))
{
_disease.TryAddDisease(entity, "ZombieInfection");
}
EntityManager.EnsureComponent<MobStateComponent>(entity, out var mobState);
if ((mobState.IsDead() || mobState.IsCritical()) && !HasComp<DiseaseZombieComponent>(entity)) //dead entities are eautomatically infected. MAYBE: have activated infect ability?
{
EntityManager.AddComponent<DiseaseZombieComponent>(entity);
var dspec = new DamageSpecifier();
//these damages match the zombie claw
dspec.DamageDict.TryAdd("Slash", -12);
dspec.DamageDict.TryAdd("Piercing", -7);
args.BonusDamage += dspec;
}
else if (mobState.IsAlive()) //heals when zombies bite live entities
{
var healingSolution = new Solution();
healingSolution.AddReagent("Bicaridine", 1.00); //if OP, reduce/change chem
_bloodstream.TryAddToChemicals(args.User, healingSolution);
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.