text stringlengths 13 6.01M |
|---|
using System.Collections.Generic;
namespace Euler.Regions
{
public interface ITouchDevice
{
int [][] GetScreenState();
}
} |
using AsyncClasses;
using Common.Business;
using Common.Data;
using Common.Log;
using Contracts.Callback;
using Contracts.MLA;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.ServiceModel;
using System.Threading;
using System.Threading.Tasks;
namespace Services.Addendum
{
/// <summary>
/// Asynchronous service to retrieve data for the Addendum module.
/// </summary>
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.PerSession,
MaxItemsInObjectGraph = Int32.MaxValue, IncludeExceptionDetailInFaults = Constants.IncludeExceptionDetailInFaults)]
public class AsyncAddendumService : IMLAAsyncService
{
#region Private Fields
/// <summary>
/// The callback instance, which runs in its own channel.
/// </summary>
private IAsyncServiceCallback mCallback = OperationContext.Current.GetCallbackChannel<IAsyncServiceCallback>();
private MLATableLoader mClient = null;
private List<int> mIds = new List<int>();
private object mLock = new object();
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of AsyncAddendumService.
/// </summary>
public AsyncAddendumService()
{
Logging.MinimumLogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), ConfigurationManager.AppSettings["LogLevel"]);
}
#endregion
#region Public Methods
/// <summary>
/// Cancels the Load operation.
/// </summary>
public void CancelLoadAddendaAsync()
{
mClient.LoadAddendaAsyncCancel();
}
/// <summary>
/// Cancels the Load operation.
/// </summary>
public void CancelLoadMoviesAsync()
{
mClient.GetMoviesAsyncCancel();
}
/// <summary>
/// Cancels the Update operation.
/// </summary>
public void CancelLoadUpdateAddendumAsync()
{
mClient.GetUpdateAddendumDataAsyncCancel();
}
/// <summary>
/// Cancels the asynchronous operation.
/// </summary>
public void CancelMLAAsync()
{
mClient.GetDataAsyncCancel();
}
//public void CancelNMCAsync()
//{
// mClient.GetNMCDataAsyncCancel();
//}
//public void CancelUpdateAddendumsAsync()
//{
// mClient.UpdateAddendumsAsyncCancel();
//}
/// <summary>
/// Loads addenda into the Addendum form asynchronously.
/// </summary>
/// <param name="userState">The MLATableLoader to use.</param>
/// <returns>The data, as a MemoryStream.</returns>
public Task<MemoryStream> LoadAddendaAsync(object userState)
{
TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>();
//Set the UserState object to our member variable for cancellation.
using (mClient = userState as MLATableLoader)
{
//Attach the Completed event.
mClient.GetDataCompleted += (o, p) =>
{
if (p.Error != null)
tcs.TrySetException(p.Error);
else if (p.Cancelled)
tcs.TrySetCanceled();
else
tcs.TrySetResult(p.Data);
//I have added this delay because the cancellation request does not get passed through
//when running without a breakpoint. Adding this Sleep() here seems to help.
Thread.Sleep(750);
mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled);
};
//Attach the ProgressChanged event.
mClient.GetDataProgressChanged += (o, p) =>
{
if (p.Cancelled)
tcs.TrySetCanceled();
mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, p.Cancelled, userState);
};
mClient.LoadAddendaAsync();
}
return tcs.Task;
}
/// <summary>
/// Loads the Addendum module in an asynchronous operation.
/// </summary>
/// <param name="userState">The MLATableLoader instance to use.</param>
/// <returns>A Task containing a MemoryStream holding data.</returns>
public Task<MemoryStream> LoadMLAAsync(object userState)
{
TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>();
//Set the UserState object to our member variable for cancellation.
using (mClient = userState as MLATableLoader)
{
//Attach the Completed event.
mClient.GetDataCompleted += (o, p) =>
{
if (p.Error != null)
tcs.TrySetException(p.Error);
else if (p.Cancelled)
tcs.TrySetCanceled();
else
tcs.TrySetResult(p.Data);
//I have added this delay because the cancellation request does not get passed through
//when running without a breakpoint. Adding this Sleep() here seems to help.
Thread.Sleep(750);
mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled);
};
//Attach the ProgressChanged event.
mClient.GetDataProgressChanged += (o, p) =>
{
if (p.Cancelled)
tcs.TrySetCanceled();
mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, p.Cancelled, userState);
};
mClient.GetDataAsync();
}
return tcs.Task;
}
/// <summary>
/// Loads the Add Master modal in an asynchronous operation.
/// </summary>
/// <param name="userState">The MLATableLoader instance to use.</param>
/// <returns>A Task containing a MemoryStream holding data.</returns>
public Task<MemoryStream> LoadMoviesAsync(object userState)
{
TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>();
//Set the UserState object to our member variable for cancellation.
using (mClient = userState as MLATableLoader)
{
//Attach the Completed event.
mClient.GetDataCompleted += (o, p) =>
{
if (p.Error != null)
tcs.TrySetException(p.Error);
else if (p.Cancelled)
tcs.TrySetCanceled();
else
tcs.TrySetResult(p.Data);
//I have added this delay because the cancellation request does not get passed through
//when running without a breakpoint. Adding this Sleep() here seems to help.
Thread.Sleep(750);
mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled);
};
//Attach the ProgressChanged event.
mClient.GetDataProgressChanged += (o, p) =>
{
if (p.Cancelled)
tcs.TrySetCanceled();
mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, p.Cancelled, userState);
};
mClient.GetMoviesAsync();
}
return tcs.Task;
}
///// <summary>
///// Loads the NMC form in an asynchronous operation.
///// </summary>
///// <param name="userState">The MLATableLoader instance to use.</param>
///// <returns>A Task containing a MemoryStream holding data.</returns>
//public Task<MemoryStream> LoadNMCAsync(object userState)
//{
// TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>();
// //Set the UserState object to our member variable for cancellation.
// using (mClient = userState as MLATableLoader)
// {
// //Attach the Completed event.
// mClient.GetDataCompleted += (o, p) =>
// {
// if (p.Error != null)
// tcs.TrySetException(p.Error);
// else if (p.Cancelled)
// tcs.TrySetCanceled();
// else
// tcs.TrySetResult(p.Data);
// //I have added this delay because the cancellation request does not get passed through
// //when running without a breakpoint. Adding this Sleep() here seems to help.
// Thread.Sleep(750);
// mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled);
// };
// //Attach the ProgressChanged event.
// mClient.GetDataProgressChanged += (o, p) =>
// {
// mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, userState);
// };
// mClient.GetNMCDataAsync();
// }
// return tcs.Task;
//}
///// <summary>
///// Loads the Addendum module in an asynchronous operation.
///// </summary>
///// <param name="userState">The MLATableLoader instance to use.</param>
///// <returns>A Task containing a MemoryStream holding data.</returns>
//public Task<MemoryStream> LoadPurgeQueueAsync(object userState)
//{
// TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>();
// //Set the UserState object to our member variable for cancellation.
// using (mClient = userState as MLATableLoader)
// {
// //Attach the Completed event.
// mClient.GetDataCompleted += (o, p) =>
// {
// if (p.Error != null)
// tcs.TrySetException(p.Error);
// else if (p.Cancelled)
// tcs.TrySetCanceled();
// else
// tcs.TrySetResult(p.Data);
// //I have added this delay because the cancellation request does not get passed through
// //when running without a breakpoint. Adding this Sleep() here seems to help.
// Thread.Sleep(750);
// mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled);
// };
// //Attach the ProgressChanged event.
// mClient.GetDataProgressChanged += (o, p) =>
// {
// mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, userState);
// };
// mClient.GetPurgeQueueDataAsync();
// }
// return tcs.Task;
//}
///// <summary>
///// Loads the Addendum module in an asynchronous operation.
///// </summary>
///// <param name="userState">The MLATableLoader instance to use.</param>
///// <returns>A Task containing a MemoryStream holding data.</returns>
//public Task<MemoryStream> LoadPurgeResultsAsync(object userState)
//{
// TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>();
// //Set the UserState object to our member variable for cancellation.
// using (mClient = userState as MLATableLoader)
// {
// //Attach the Completed event.
// mClient.GetDataCompleted += (o, p) =>
// {
// if (p.Error != null)
// tcs.TrySetException(p.Error);
// else if (p.Cancelled)
// tcs.TrySetCanceled();
// else
// tcs.TrySetResult(p.Data);
// //I have added this delay because the cancellation request does not get passed through
// //when running without a breakpoint. Adding this Sleep() here seems to help.
// Thread.Sleep(750);
// mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled);
// };
// //Attach the ProgressChanged event.
// mClient.GetDataProgressChanged += (o, p) =>
// {
// mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, userState);
// };
// mClient.GetPurgeResultsDataAsync();
// }
// return tcs.Task;
//}
/// <summary>
/// Loads the Addendum module in an asynchronous operation.
/// </summary>
/// <param name="userState">The MLATableLoader instance to use.</param>
/// <returns>A Task containing a MemoryStream holding data.</returns>
public Task<MemoryStream> LoadUpdateAddendumAsync(object userState)
{
TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>();
//Set the UserState object to our member variable for cancellation.
using (mClient = userState as MLATableLoader)
{
//Attach the Completed event.
mClient.GetDataCompleted += (o, p) =>
{
if (p.Error != null)
tcs.TrySetException(p.Error);
else if (p.Cancelled)
tcs.TrySetCanceled();
else
tcs.TrySetResult(p.Data);
//I have added this delay because the cancellation request does not get passed through
//when running without a breakpoint. Adding this Sleep() here seems to help.
Thread.Sleep(750);
mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled);
};
//Attach the ProgressChanged event.
mClient.GetDataProgressChanged += (o, p) =>
{
if (p.Cancelled)
tcs.TrySetCanceled();
mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, p.Cancelled, userState);
};
mClient.GetUpdateAddendumDataAsync();
}
return tcs.Task;
}
/// <summary>
/// Sends a list of values to the processor.
/// </summary>
/// <param name="ids">The asset IDs to load.</param>
/// <remarks>This method is necessary because sending large datasets (lower boundary unknown) to the
/// processor all at once causes WCF to throw an exception and abort the asynchronous processing. We
/// take a very slight performance hit doing it this way (ignoring network latency issues), but it is
/// also reliable doing it this way.</remarks>
public void SendNextChunk(List<int> ids)
{
//Load up the IDs before processing.
//Lock this update to prevent the system from throwing an ArgumentException relating to array length.
lock (mLock)
{
mIds.AddRange(ids);
}
}
#endregion
}
} |
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using System.Xml.Serialization;
using DataModel.ExternalService;
using Familnyi.Model.ServiceMessage;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NunitTestOLBP
{
[TestClass]
public class FamilnyiModelsTest
{
[TestMethod]
public void TestMethod1()
{
// Arrange
ExternalServiceModel externalServiceModel = new ExternalServiceChekedModel();
externalServiceModel.Address = "https://212.42.94.131:9999/FlashPayX/";
externalServiceModel.IsUsingProxy = true;
externalServiceModel.ProxyAddress = "195.230.131.201";
externalServiceModel.ProxyPort = 3128;
externalServiceModel.SSLProtocolType = "TLS";
const string postData = "<Data><Request><RqHeader><idMsgType>111 </idMsgType><IdService>510 </IdService><IdSubService> 0</IdSubService><IdClient> 10044163</IdClient></RqHeader><RqFooter><MsgDateTime>2016.10.28 01:05:12</MsgDateTime><IdTerminal>625350</IdTerminal><idKey>999900000384</idKey></RqFooter></Request><SignMsg>eAJjM6KjwzDKX/Do0QX7nnnGzYfMdQyPRP7Nn+e12QA96+NQnwvwQyPzPY2elN1xo6EjhBWI2DZbh8z9HUpeHYT74EaS5nwYgNWZ3gmo1+Z3DJcyNjI9n7ZWHRpPSV/iGb70/4SrcwBVVdZLdpe8xZFShPlrqZfZ8uf6ncjeHR8=</SignMsg></Data>";
var restClient = new RestClient(HttpVerb.POST, externalServiceModel, postData);
// Act
var response = restClient.MakeRequest();
// Assert
const string expected = "<Data><Response><RsHeader><idMsgType>112</idMsgType><AnswerStatus>0 </AnswerStatus><IdService>510 </IdService><IdSubService> 0</IdSubService><IdClient> 10044163 </IdClient></RsHeader><body><Msg2Client>Топольницкая Любовь Петровна</Msg2Client></body><RFooter><MsgDateTime>2016.10.28 01:05:06</MsgDateTime><idKey>999900000001</idKey></RFooter></Response><SignMsg>sign</SignMsg></Data>";
//const string expected = "<Data><Response><RsHeader><idMsgType>112</idMsgType><AnswerStatus>0 </AnswerStatus><IdService>510 </IdService><IdSubService> 0</IdSubService><IdClient> 10044163 </IdClient></RsHeader><body><Msg2Client>Топольницкая Любовь Петровна</Msg2Client></body><RFooter><MsgDateTime>2016.10.28 01:05:06</MsgDateTime><idKey>999900000001</idKey></RFooter></Response><SignMsg>tq9qNjDo+qgP7E8OjqLRY4Ixe/nseuERV2XGUtphra9fEP1ERE7HFVQPREHmg+DYzO1ed4xGwhmaQiHlSOnaLvYQU7zihQ4ijjWiXozVW6V1iwoiZlyjX3SrFePaSy3VmiYrqe71iiJyEwE5IfN1jS3SdE+Q6t7uZFtUiRA/Ul8=</SignMsg></Data>";
Assert.AreEqual(expected, response);
}
}
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
public class RestClient
{
public string EndPoint { get; set; }
public HttpVerb Method { get; set; }
public string ContentType { get; set; }
public string PostData { get; set; }
public ExternalServiceModel EsModel { get; set; }
public RestClient(HttpVerb method, ExternalServiceModel EsModel)
{
this.EsModel = EsModel;
Method = method;
ContentType = "text/xml";
}
public RestClient(HttpVerb method, ExternalServiceModel EsModel, string postData)
{
this.EsModel = EsModel;
Method = method;
ContentType = "text/xml";
PostData = postData;
}
public string MakeRequest()
{
return MakeRequest("");
}
public string MakeRequest(string parameters)
{
var request = (HttpWebRequest)WebRequest.Create(EsModel.Address + parameters);
ServicePointManager.ServerCertificateValidationCallback +=
delegate (object sender, X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
request.Method = Method.ToString();
request.ContentLength = 0;
request.ContentType = ContentType;
request.Timeout = 50000;
if (EsModel.IsUsingProxy)
{
request.Proxy = new WebProxy(EsModel.ProxyAddress, EsModel.ProxyPort.Value);
if (!string.IsNullOrEmpty(EsModel.ProxyLogin))
{
request.Proxy.Credentials = new NetworkCredential(EsModel.ProxyLogin, EsModel.ProxyPassword);
}
}
if (EsModel.IsCertificateUsing)
{
request.ClientCertificates.Add(!string.IsNullOrEmpty(EsModel.CertificatePassword)
? new X509Certificate(EsModel.ServiceCertificate, EsModel.CertificatePassword)
: new X509Certificate(EsModel.ServiceCertificate));
}
switch (EsModel.SSLProtocolType)
{
case "SSL":
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
break;
case "TLS":
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
break;
default:
break;
}
if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding(1251).GetBytes(PostData);
//var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
//ServiceResponse serviceResponse;
//XmlSerializer xs=new XmlSerializer(typeof(ServiceResponse));
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream, Encoding.GetEncoding(1251)))
{
responseValue = reader.ReadToEnd();
//XmlReader xmlReader=XmlReader.Create(responseStream, new XmlReaderSettings {IgnoreWhitespace = true});
//serviceResponse = (ServiceResponse) xs.Deserialize(xmlReader);
}
}
return responseValue;
}
}
public static T Deserialize<T>(string xml, Encoding encoding, XmlReaderSettings settings)
{
if (string.IsNullOrEmpty(xml))
throw new ArgumentException("XML cannot be null or empty", "xml");
T res;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(xml)))
{
XmlReader xmlReader = XmlReader.Create(memoryStream, settings);
res = (T)xmlSerializer.Deserialize(xmlReader);
}
return res;
}
} // class
}
|
using System.Collections.Generic;
using Vipr.Core.CodeModel;
namespace MAX.Writer.REST
{
internal class RootType
{
private OdcmProperty entity;
public string Name { get { return entity.Name; } }
public string TypeName { get { return entity.Type.Name; } }
public RootType(OdcmProperty entity)
{
this.entity = entity;
}
}
} |
using System;
using System.Text;
namespace CourseHunter_19_StringBulder
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
//метод дабавления в стинг билдер новой строки.
sb.Append("My ");
sb.Append("name ");
sb.Append("is ");
sb.Append("John ");
//Метод добавление с новой строчки
sb.AppendLine("!");
Console.WriteLine(sb);
//Метод загона все в строкую
string str = sb.ToString();
Console.WriteLine(str);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using static FactorialLibrary.Factorial;
namespace FactorialProgram
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Task \"Factorial\"\n");
try
{
Console.Write("Enter natural number: ");
int number = int.Parse(Console.ReadLine());
Console.Write("Factorial: " + CalculateFactorial(number));
}
catch (ValidationException)
{
Console.WriteLine("\nError: ValidationException");
}
catch (FormatException)
{
Console.WriteLine("\nError: FormatException");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Text;
using System.Windows.Input;
using MvvmCross.Platform.IoC;
using UIKit;
namespace ResidentAppCross.iOS
{
// This class is never actually executed, but when Xamarin linking is enabled it does how to ensure types and properties
// are preserved in the deployed app
public class LinkerPleaseInclude
{
public void Include(UIButton uiButton)
{
}
public void Include(UIBarButtonItem barButton)
{
}
public void Include(UITextField textField)
{
}
public void Include(UITextView textView)
{
}
public void Include(UILabel label)
{
}
public void Include(UIImageView imageView)
{
}
public void Include(UIDatePicker date)
{
}
public void Include(UISlider slider)
{
}
public void Include(UISwitch sw)
{
}
public void Include(INotifyCollectionChanged changed)
{
}
public void Include(INotifyPropertyChanged changed)
{
changed.PropertyChanged += (sender, e) => {
var test = e.PropertyName;
};
}
public void Include(ICommand command)
{
}
public void Include(MvxPropertyInjector injector)
{
injector = new MvxPropertyInjector();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using _3D_Tree_Generator.Test_Classes;
using NCalc;
/* TODO:
* Fix Color rendering
* add normal support
* GenerateBranch
*/
namespace _3D_Tree_Generator
{
public partial class Window : Form
{
int ibo_elements; //integer buffer object pointer for indices
Vector3[] vertdata; // array of vertices to send to buffers
int[] indicedata;
Vector3[] coldata; // " colors
Vector2[] texcoorddata;
List<Mesh> objects = new List<Mesh>();
Camera camera = new Camera();
Tree tree = new Tree(10f, 1f, Matrix4.Identity);
const float fps = 400f;
Timer timer;
DateTime prevTime = DateTime.Now;
Dictionary<string, Shader> shaders = new Dictionary<string, Shader>();
string activeShader = "default";
Dictionary<string, Texture> Textures = new Dictionary<string, Texture>();
Matrix4 ProjectionMatrix;
Matrix4 ViewProjectionMatrix;
BindingList<Leaf> Leaves = new BindingList<Leaf>();
public Window() //contructor for the window
{
InitializeComponent();
}
/// <summary>
/// Repaint every frame.
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void TimerTick(object source, EventArgs e)
{
glControl1_Paint(glControl1, EventArgs.Empty);
}
/// <summary>
/// GlControl Loaded in
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void glControl1_Load(object sender, EventArgs e) //GLControl loaded all dlls
{
//tree.GenerateTree();
//objects.Add(tree);
//TestTree testTree = new TestTree();
//testTree.TestConnectCrossSection();
//testTree.GenerateTree();
//objects.Add(testTree);
TestLeaf testLeaf = new TestLeaf(Vector3.Zero);
objects.Add(testLeaf);
TestLeaf testTwo = new TestLeaf(testLeaf, new Vector3(0, 1, 1));
objects.Add(testTwo);
//Expression exp = new Expression("x*x", EvaluateOptions.IgnoreCase);
//Debug.WriteLine(exp.Eval(10));
//Mesh mesh = new Mesh(Tree.GenerateBranch(1f, 10f, 10, 7, color: 0.2f, topColor: 0.8f, minDist: 1f, trunkFunction: exp));
//Mesh mesh = new Mesh(Tree.GenerateBranch(5f, 10f, 10, 7, color: 0.2f, topColor: 0.8f, branch: false, flare: 1, flareEnd: 2f));
//mesh.Rotation = new Vector3((float)Math.PI, 0, 0);
//objects.Add(mesh);
//objects.Add(new TestCube());
//objects.Add(new TexturedTestCube());
//objects.Add(new Mesh("Resources/Objects/Car.obj"));
//objects.Add(new TestAxes());
Debug.WriteLine("Objects: \n" + String.Join("\n", objects));
ProjectionMatrix = Matrix4.CreatePerspectiveFieldOfView(1.3f, glControl1.Width / (float)glControl1.Height, 0.5f, 100.0f);
initProgram(); // initialise shaders and VBOs
GL.ClearColor(Color.White);
GL.Enable(EnableCap.DepthTest);
GL.PointSize(5f);
timer = new Timer();
timer.Tick += new EventHandler(TimerTick);
timer.Interval = (int)(1000 / fps);
timer.Start();
autoRefreshToolStripMenuItem.Checked = true;
update();
glControl1_Resize(glControl1, EventArgs.Empty);
}
private void initProgram()
{
GL.GenBuffers(1, out ibo_elements);
shaders.Add("default", new Shader("Resources/Shaders/vs.glsl", "Resources/Shaders/fs.glsl", true));
shaders.Add("textured", new Shader("Resources/Shaders/vs_tex.glsl", "Resources/Shaders/fs_tex.glsl", true));
activeShader = "textured";
}
private int addObjects(List<Mesh> objs, int vertcount, ref List<Vector3> verts, ref List<int> inds, ref List<Vector3> colors, ref List<Vector2> texcoords)
{
foreach (Mesh v in objs) // add data from each object in turn
{
/*
Debug.WriteLine(v.Vertices.Length + " Verts are: " + String.Join(", ", v.Vertices));
Debug.WriteLine(v.Colors.Length + " Colors are: " + String.Join(", ", v.Colors));
Debug.WriteLine(v.Indices.Length + " Indices are: " + String.Join(", ", v.Indices));
Debug.WriteLine(v.TexCoords.Length + " Textcoords are: " + String.Join(", ", v.TexCoords));
*/
verts.AddRange(v.Vertices);
colors.AddRange(v.Colors);
texcoords.AddRange(v.TexCoords);
foreach (int ind in v.Indices)
{
inds.Add(ind + vertcount); // offset indices as verts go into a combined big list
}
vertcount += v.Vertices.Length;
vertcount = addObjects(v.Children, vertcount, ref verts, ref inds, ref colors, ref texcoords);
}
return vertcount;
}
/// <summary>
/// Call whenever anything is changed in the scene.
/// </summary>
private void update()
{
//Debug.WriteLine(1000 / interval);
//get data
List<Vector3> verts = new List<Vector3>(); // create lists for adding all data from every object
List<int> inds = new List<int>();
List<Vector3> colors = new List<Vector3>();
List<Vector2> texcoords = new List<Vector2>();
addObjects(objects, 0, ref verts, ref inds, ref colors, ref texcoords);
vertdata = verts.ToArray(); // turn lists to arrays
indicedata = inds.ToArray();
coldata = colors.ToArray();
texcoorddata = texcoords.ToArray();
//Debug.WriteLine("Verts: " + String.Join(", ", vertdata.Select(p => p.ToString()).ToArray())); //https://stackoverflow.com/questions/380708/shortest-method-to-convert-an-array-to-a-string-in-c-linq
//Debug.WriteLine("inds: " + String.Join(", ", indicedata.Select(p => p.ToString()).ToArray()));
//Debug.WriteLine("cols: " + String.Join(", ", coldata.Select(p => p.ToString()).ToArray()));
//Debug.WriteLine("texs: " + String.Join(", ", texcoorddata.Select(p => p.ToString()).ToArray()));
GL.BindBuffer(BufferTarget.ArrayBuffer, shaders[activeShader].GetBuffer("vPosition")); //writes all vertices to the vbo
GL.BufferData<Vector3>(BufferTarget.ArrayBuffer, (IntPtr)(vertdata.Length * Vector3.SizeInBytes), vertdata, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(shaders[activeShader].GetAttribute("vPosition"), 3, VertexAttribPointerType.Float, false, 0, 0);
if (shaders[activeShader].GetAttribute("vColor") != -1) //writes all colours to vbo if the shader has it
{
GL.BindBuffer(BufferTarget.ArrayBuffer, shaders[activeShader].GetBuffer("vColor"));
GL.BufferData<Vector3>(BufferTarget.ArrayBuffer, (IntPtr)(coldata.Length * Vector3.SizeInBytes), coldata, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(shaders[activeShader].GetAttribute("vColor"), 3, VertexAttribPointerType.Float, true, 0, 0);
}
if (shaders[activeShader].GetAttribute("texcoord") != -1) //writes texture coordinates to vbo if shader has them
{
//Debug.WriteLine("Binding TexCoords");
GL.BindBuffer(BufferTarget.ArrayBuffer, shaders[activeShader].GetBuffer("texcoord"));
GL.BufferData<Vector2>(BufferTarget.ArrayBuffer, (IntPtr)(texcoorddata.Length * Vector2.SizeInBytes), texcoorddata, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(shaders[activeShader].GetAttribute("texcoord"), 2, VertexAttribPointerType.Float, true, 0, 0);
}
GL.BindBuffer(BufferTarget.ElementArrayBuffer, ibo_elements); //indices
GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indicedata.Length * sizeof(int)), indicedata, BufferUsageHint.StaticDraw);
ViewProjectionMatrix = camera.ViewMatrix * ProjectionMatrix;
foreach (Mesh ob in objects)
{
ob.CalculateModelViewProjectionMatrix(ViewProjectionMatrix);
}
GL.UseProgram(shaders[activeShader].ProgramID); //use our active shader program
GL.BindBuffer(BufferTarget.ArrayBuffer, 0); // unbind the buffers (bind null buffer)
//Debug.WriteLine("Update");
}
private void glControl1_Resize(object sender, EventArgs e) //https://github.com/andykorth/opentk/blob/master/Source/Examples/OpenTK/GLControl/GLControlGameLoop.cs
{
glControl1.MakeCurrent();
GLControl c = (GLControl)sender;
GL.Viewport(glControl1.ClientRectangle); //https://stackoverflow.com/questions/5858713/how-to-change-the-viewport-resolution-in-opentk
Matrix4 perspective = Matrix4.CreatePerspectiveFieldOfView(1.3f, glControl1.Width / (float)glControl1.Height, 1.3f, 40.0f);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadMatrix(ref perspective);
}
private void glControl1_Move(object sender, EventArgs e)
{
glControl1.MakeCurrent();
GLControl c = (GLControl)sender;
GL.Viewport(glControl1.ClientRectangle); //https://stackoverflow.com/questions/5858713/how-to-change-the-viewport-resolution-in-opentk
Matrix4 perspective = Matrix4.CreatePerspectiveFieldOfView(1.3f, glControl1.Width / (float)glControl1.Height, 1.3f, 40.0f);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadMatrix(ref perspective);
}
private void glControl1_Paint(object sender, EventArgs e)
{
//Debug.WriteLine("frame");
double timeTaken = (DateTime.Now - prevTime).TotalMilliseconds;
prevTime = DateTime.Now;
this.Controls["FPS_Counter"].Text = "Time to render: " + (timeTaken).ToString("0000.0") + " ms";
//update(); //remove once updates are called by events
//GL.Viewport(0, 0, glControl1.Width, glControl1.Height);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
shaders[activeShader].EnableVertexAttribArrays();
int indiceat = 0;
foreach (Mesh v in objects)
{
indiceat = drawMesh(v, indiceat);
}
shaders[activeShader].DisableVertexAttribArrays();
GL.Flush();
glControl1.SwapBuffers();
//Debug.WriteLine("Paint");
}
private int drawMesh(Mesh v, int indiceat)
{
//Debug.WriteLine(v);
GL.UniformMatrix4(shaders[activeShader].GetUniform("modelview"), false, ref v.ModelViewProjectionMatrix); //send modelview to shader
//Debug.WriteLine(v.IsTextured);
if (v.IsTextured)
{
if (shaders[activeShader].GetUniform("maintexture") != -1) //send texture to shader if textured
{
//Debug.WriteLine(((v is Tree) ? "Tree " : "Leaf ") + v.Texture.TexID);
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, v.Texture.TexID);
GL.Uniform1(shaders[activeShader].GetUniform("maintexture"), 0);
//Debug.WriteLine("Sent Texture");
}
}
GL.DrawElements(BeginMode.Triangles, v.Indices.Length, DrawElementsType.UnsignedInt, indiceat * sizeof(uint)); //draw this object
indiceat += v.Indices.Length;
if (v.Children.Count != 0)
{
foreach (Mesh c in v.Children)
{
//Debug.WriteLine(((c is Tree) ? "Tree " : "Leaf ") + v.Texture.TexID);
indiceat = drawMesh(c, indiceat);
}
}
return indiceat;
}
private void glControl1_MouseWheel(object sender, MouseEventArgs e)
{
camera.Zoom(glControl1, e);
}
private void glControl1_MouseMove(object sender, MouseEventArgs e)
{
camera.Update(glControl1);
update();
}
private void RefreshButton_Click(object sender, EventArgs e)
{
tree.GenerateTree();
update();
}
private void ValueChanged(object sender, EventArgs e)
{
if (sender.GetType() == typeof(NumericUpDown))
{
NumericUpDown num = sender as NumericUpDown; //turn the generic sender into the specific NumericUpDown type
//this extracts the property of the tree to be changed, based on the AccessibleName of the sender
var property = tree.GetType().GetProperty(num.AccessibleName); //https://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-a-class
//this sets the afformentioned property to the value of the NumericUpDown
property.SetValue(tree, Convert.ChangeType(num.Value, property.PropertyType));
//then regenerate the tree with new property and update the scene, if auto-refresh is enabled.
if (this.autoRefreshToolStripMenuItem.Checked)
{
tree.GenerateTree();
update();
}
}
}
private void Function_Update(object sender, EventArgs e)
{
TextBox box = Shape_Functions.Controls[(sender as Control).AccessibleName] as TextBox;
if (box.Text == "" || box.Text == null)
{
box.Text = " ";
}
Expression ex = new Expression(box.Text, EvaluateOptions.IgnoreCase);
if (ex.HasErrors())
{
MessageBox.Show(ex.Error, "Invalid Function", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); //https://stackoverflow.com/questions/3803630/how-to-call-window-alertmessage-from-c
}
else
{
try
{
var property = tree.GetType().GetProperty(box.AccessibleName); //https://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-a-class
property.SetValue(tree, Convert.ChangeType(ex, property.PropertyType));
if (this.autoRefreshToolStripMenuItem.Checked)
{
tree.GenerateTree();
update();
}
}
catch (ArgumentException )
{
MessageBox.Show("Must be a function in x!", "Invalid Function", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); //https://stackoverflow.com/questions/3803630/how-to-call-window-alertmessage-from-c
}
catch (InvalidCastException)
{
MessageBox.Show("Must be a function in x!", "Invalid Function", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
private void createNewToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
Leaves.Add(new Leaf());
}
catch (ArgumentException)
{
}
catch (Exception error)
{
MessageBox.Show(String.Format("Unable to create Leaf: \n {0}", error));
}
BindingSource bSource = new BindingSource();
bSource.DataSource = Leaves;
leaf_selector.DataSource = bSource;
}
private void leaf_selector_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(((Leaf)leaf_selector.SelectedValue).AltImage);
((Tree)objects[0]).Leaf = Leaves[leaf_selector.SelectedIndex];
}
private void SaveAs(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
save.DefaultExt = ".tre";
save.Filter = "Tree files (*.tre)|*.tre|All files (*.*)|*.*";
save.FilterIndex = 1;
save.ShowDialog();
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Stream stream = save.OpenFile();
formatter.Serialize(stream, tree);
stream.Close();
//https://msdn.microsoft.com/en-us/library/ms973893.aspx
//https://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.openfile(v=vs.110).aspx
}
private void Open(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
open.DefaultExt = ".tre";
open.Filter = "Tree files (*.tre)|*.tre|All files (*.*)|*.*";
open.FilterIndex = 1;
open.ShowDialog();
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Stream stream = open.OpenFile();
tree = (Tree)formatter.Deserialize(stream);
stream.Close();
tree.GenerateTree();
update();
}
//http://barcodebattler.co.uk/tutorials/csgl1.htm
//http://barcodebattler.co.uk/tutorials/csgl2.htm
//http://barcodebattler.co.uk/tutorials/csgl3.htm
//http://neokabuto.blogspot.co.uk/2013/02/opentk-tutorial-1-opening-windows-and.html
//http://neokabuto.blogspot.co.uk/2013/03/opentk-tutorial-2-drawing-triangle.html
//http://neokabuto.blogspot.co.uk/2013/07/opentk-tutorial-3-enter-third-dimension.html
//http://neokabuto.blogspot.co.uk/2014/01/opentk-tutorial-5-basic-camera.html
}
}
|
using System.Configuration;
using System.ServiceProcess;
namespace TFSDeployService
{
public abstract class BaseServiceInstaller : System.Configuration.Install.Installer
{
public BaseServiceInstaller()
{
Installers.Add(new ServiceProcessInstaller
{
Account = ServiceAccount.NetworkService
});
Installers.Add(new ServiceInstaller
{
ServiceName = ConfigurationManager.AppSettings["ServiceName"],
StartType = ServiceStartMode.Automatic
});
}
}
} |
using DChild.Gameplay.Environment;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Pathfinding
{
[CreateAssetMenu(fileName = "PathFindingSerializationFile", menuName = "DChild/PathFinding Serialization")]
public class PathFindingSerializationFile : ScriptableObject
{
[System.Serializable]
private struct LocationCache
{
[SerializeField]
[ReadOnly]
private Location m_location;
[SerializeField]
private TextAsset[] m_save;
public LocationCache(Location m_location)
{
this.m_location = m_location;
m_save = new TextAsset[1];
}
public Location location => m_location;
public TextAsset GetGraphs(uint index) => m_save[index];
}
[SerializeField]
[ListDrawerSettings(DraggableItems = false, HideAddButton = true, NumberOfItemsPerPage = 1, IsReadOnly = true)]
private LocationCache[] m_caches;
public TextAsset GetGraphs(Location location, uint index) => m_caches[(int)location].GetGraphs(index);
private LocationCache[] CreateEmptyCaches()
{
var count = (int)Location._COUNT;
var caches = new LocationCache[count];
for (int i = 0; i < count; i++)
{
caches[i] = new LocationCache((Location)i);
}
return caches;
}
private void Awake()
{
m_caches = CreateEmptyCaches();
}
#if UNITY_EDITOR
[Button("Update")]
private void Update()
{
var updatedCache = CreateEmptyCaches();
for (int i = 0; i < m_caches.Length; i++)
{
for (int j = 0; j < updatedCache.Length; j++)
{
if (m_caches[i].location == updatedCache[i].location)
{
updatedCache[i] = m_caches[i];
break;
}
}
}
m_caches = updatedCache;
}
#endif
}
} |
using System;
using Xunit;
using ZKCloud.Test.Samples;
namespace ZKCloud.Test.Datas.Persistence
{
/// <summary>
/// 持久化对象测试
/// </summary>
public class PersistentObjectTest
{
/// <summary>
/// 测试初始化
/// </summary>
public PersistentObjectTest()
{
_sample = new PersistentObjectSample();
_sample2 = new PersistentObjectSample();
}
/// <summary>
/// 持久化对象测试样例
/// </summary>
private PersistentObjectSample _sample;
/// <summary>
/// 持久化对象测试样例2
/// </summary>
private PersistentObjectSample _sample2;
/// <summary>
/// 测试实体相等性 - 当两个实体的标识相同,则实体相同
/// </summary>
[Fact]
public void TestEquals_IdEquals()
{
var id = Guid.NewGuid();
_sample = new PersistentObjectSample(id);
_sample2 = new PersistentObjectSample(id);
Assert.True(_sample.Equals(_sample2));
Assert.True(_sample == _sample2);
Assert.False(_sample != _sample2);
}
/// <summary>
/// 测试实体相等性 - 类型无效
/// </summary>
[Fact]
public void TestEquals_InvalidType()
{
var id = Guid.NewGuid();
_sample = new PersistentObjectSample(id);
var sample2 = new PersistentObjectSample2(id);
Assert.False(_sample.Equals(sample2));
Assert.True(_sample != sample2);
Assert.True(sample2 != _sample);
}
/// <summary>
/// 测试实体相等性 - 判空
/// </summary>
[Fact]
public void TestEquals_Null()
{
Assert.False(_sample.Equals(_sample2));
Assert.False(_sample.Equals(null));
Assert.False(_sample == _sample2);
Assert.False(_sample == null);
Assert.False(null == _sample2);
Assert.True(_sample != _sample2);
Assert.True(_sample != null);
Assert.True(null != _sample2);
_sample2 = null;
Assert.False(_sample.Equals(_sample2));
_sample = null;
Assert.True(_sample == _sample2);
Assert.True(_sample2 == _sample);
}
}
} |
using AFPABNB.Dao;
using AFPABNB.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AFPABNB
{
public partial class DetailHebergement : System.Web.UI.Page
{
private List<Hebergement> detail;
protected void Page_Load(object sender, EventArgs e)
{
this.detail = (List<Hebergement>)Session["Detail"];
if (!IsPostBack)
{
this.gdvDetail.DataSource = this.detail;
this.gdvDetail.DataBind();
}
Session.Remove("Detail");
}
protected void Favoris_Click(object sender, EventArgs e)
{
Client client = (Client)Session["Client"];
int idhebergement = Convert.ToInt32(((Button)sender).CommandArgument);
DaoFavoris daoFavoris = new DaoFavoris();
List<Hebergement> mesFavoris = daoFavoris.GetFavoris(client.IdClient, 1);
if (mesFavoris != null)
{
bool existe = false;
foreach (Hebergement item in mesFavoris)
{
if (item.IdHebergement == idhebergement)
{
existe = true;
/*have*/
break; //have kitkat
}
}
if (!existe)
{
daoFavoris.createFavoris(client.IdClient, idhebergement, 2);
}
}
else
{
daoFavoris.createFavoris(client.IdClient, idhebergement, 2);
}
Response.Redirect("/EspaceClient/Favoris.aspx");
}
protected void Reserver_Click(object sender, EventArgs e)
{
Client client = (Client)Session["Client"];
int idhebergement = Convert.ToInt32(((Button)sender).CommandArgument);
DaoReservation daoReservation = new DaoReservation();
List<Hebergement> mesReservations = daoReservation.GetReservation(client.IdClient, 1);
if (mesReservations != null)
{
bool existe = false;
foreach (Hebergement item in mesReservations)
{
if (item.IdHebergement == idhebergement)
{
existe = true;
/*have*/
break; //have kitkat
}
}
if (!existe)
{
daoReservation.createReservation(client.IdClient, idhebergement, 2);
}
}
else
{
daoReservation.createReservation(client.IdClient, idhebergement, 2);
}
Response.Redirect("/EspaceClient/Reservation.aspx");
}
protected void Contact_Click(object sender, EventArgs e)
{
//Client client = null;
//client = (Client)Session["Client"];
//Hebergement hebergement;
//hebergement = (Hebergement)Session["Detail"];
//int idexpediteur = client.IdClient;
//int iddestinataire = hebergement.IdClient;
//string messages = "test";
//string date = "20/20/2021";
//bool statut = true;
//DaoMessagerie daoMessagerie = new DaoMessagerie();
//daoMessagerie.createMessage(idexpediteur, iddestinataire, messages, date, statut);
//Response.Redirect("./ok.aspx");
}
}
} |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using Docller.Core.Common;
using Docller.Core.Models;
using Docller.Core.Repository;
using Docller.Core.Storage;
using File = System.IO.File;
namespace Docller.Core.Images
{
public class PreviewImageProvider : IPreviewImageProvider
{
private readonly IDirectDownloadProvider _downloadProvider;
private readonly ILocalStorage _localStorage;
public PreviewImageProvider(IDirectDownloadProvider downloadProvider)
{
_downloadProvider = downloadProvider;
_localStorage = Factory.GetInstance<ILocalStorage>();
}
public void GeneratePreviews(long customerId, BlobBase blobBase)
{
IImageConverter converter = ImageConverters.Get(blobBase.FileExtension);
if(converter is NullImageConverter)
return;
string internalName = blobBase.FileInternalName.ToString();
string localFolder = this.GetLocalCacheFolder(customerId, blobBase);
string lThumbFullName = GetLocalPreviewFileName(internalName, localFolder, PreviewType.LThumb);
string originalFile = _downloadProvider.GetFileFromStorage(customerId, blobBase);
ConvertToImage(converter, originalFile, lThumbFullName);
UploadToStorage(customerId, blobBase, lThumbFullName);
string pThumbFullName = GetLocalPreviewFileName(internalName, localFolder, PreviewType.PThumb);
ResizeImage(lThumbFullName, pThumbFullName, ImageSize.Preview, ImageSize.Preview);
UploadToStorage(customerId, blobBase, pThumbFullName);
string sThumbFullName = GetLocalPreviewFileName(internalName, localFolder, PreviewType.SThumb);
ResizeImage(lThumbFullName, sThumbFullName, ImageSize.Small, ImageSize.Small);
UploadToStorage(customerId, blobBase, sThumbFullName);
//Finally set the flag in the DB
IStorageRepository storageRepository = Factory.GetRepository<IStorageRepository>(customerId);
storageRepository.SetPreviewsTimestamp(blobBase.FileId, DateTime.UtcNow);
}
public void DeletePreviews(long customerId, BlobBase blobBase)
{
string localFolder = this.GetLocalCacheFolder(customerId, blobBase);
//Delete local cache folder if it exits
DirectoryInfo directoryInfo = new DirectoryInfo(localFolder);
if (directoryInfo.Exists)
{
directoryInfo.Delete(true);
}
//Delete from Blob storage
IBlobStorageProvider blobStorageProvider = Factory.GetInstance<IBlobStorageProvider>();
string path = GetStoragePath(customerId, blobBase, blobStorageProvider.GetPathSeparator());
blobStorageProvider.DeleteDirectory(path, Constants.PreviewImagesContainer);
IStorageRepository storageRepository = Factory.GetRepository<IStorageRepository>(customerId);
storageRepository.SetPreviewsTimestamp(blobBase.FileId, DateTime.MinValue);
}
public string GetPreview(long customerId, BlobBase blobBase, PreviewType previewType)
{
string path = GetLocalCacheFolder(customerId, blobBase);
return GetPreview(customerId, blobBase, previewType, path);
}
public string GetZoomablePreview(long customerId, BlobBase blobBase)
{
string path = GetLocalCacheFolder(customerId, blobBase);
string fullSizePath = GetPreview(customerId, blobBase, PreviewType.LThumb, path);
IZoomableImageProvider zoomableImageProvider = Factory.GetInstance<IZoomableImageProvider>();
return zoomableImageProvider.GenerateZoomableImage(fullSizePath,path);
}
public string GetTile(long customerId, BlobBase blobBase, string tile)
{
string path = GetLocalCacheFolder(customerId, blobBase);
return string.Format("{0}\\zoomed_files\\{1}", path, tile);
}
private string GetPreview(long customerId, BlobBase blobBase, PreviewType previewType, string folderPath)
{
DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
if (directoryInfo.Exists)
{
FileInfo previewInfo = directoryInfo.GetFiles(string.Format("{0}_{1}.png", blobBase.FileInternalName, previewType)).FirstOrDefault();
if (previewInfo != null && previewInfo.Exists)
{
return previewInfo.FullName;
}
}
return DownloadAndCache(customerId, blobBase, previewType, directoryInfo);
}
private string DownloadAndCache(long customerId, BlobBase blobBase, PreviewType previewType, DirectoryInfo directory)
{
if (!directory.Exists)
{
directory.Create();
}
IBlobStorageProvider blobStorageProvider = Factory.GetInstance<IBlobStorageProvider>();
string seprator = blobStorageProvider.GetPathSeparator();
string fileName = string.Format("{0}_{1}.png", blobBase.FileInternalName, previewType);
string pathToDownload = string.Format("{0}{1}{2}", GetStoragePath(customerId, blobBase,seprator),seprator,fileName);
string targetFile = string.Format("{0}\\{1}", directory.FullName, fileName);
using (
FileStream target = new FileStream(targetFile,
FileMode.Create, FileAccess.Write))
{
blobStorageProvider.DownloadToStream(Constants.PreviewImagesContainer, pathToDownload, target);
}
return targetFile;
}
private string GetLocalPreviewFileName(string internalFileName, string localFolder, PreviewType previewType)
{
string thumbFile = GetPreviewFileName(internalFileName, previewType);
string thumbFileFullPath = string.Format("{0}\\{1}", localFolder, thumbFile);
return thumbFileFullPath;
}
private string GetPreviewFileName(string internalFileName, PreviewType previewType)
{
return string.Format("{0}_{1}.png", internalFileName, previewType);
}
private void ConvertToImage(IImageConverter converter, string file, string imageFile)
{
converter.Convert(file, imageFile);
}
private void ResizeImage(string inputFile, string outputfile, double height, double width)
{
ImageResizer.ResizeImage(inputFile,outputfile,height,width);
}
private string GetLocalCacheFolder(long customerId, BlobBase blobBase)
{
string folderPath = string.Format("{0}\\{1}", Constants.PreviewImagesContainer,
GetStoragePath(customerId, blobBase, "\\"));
return _localStorage.EnsureCacheFolder(folderPath);
}
private string GetStoragePath(long customerId,BlobBase blobBase, string seprator)
{
return string.Format("c{0}{3}p{1}{3}f{2}", customerId,
blobBase.Project.ProjectId, blobBase.FileId, seprator);
}
private void UploadToStorage(long customerId, BlobBase blobBase, string fileToUpload)
{
FileInfo fileInfo = new FileInfo(fileToUpload);
using (FileStream stream = fileInfo.OpenRead())
{
IBlobStorageProvider blobStorageProvider = Factory.GetInstance<IBlobStorageProvider>();
string path = GetStoragePath(customerId, blobBase, blobStorageProvider.GetPathSeparator());
blobStorageProvider.UploadFile(Constants.PreviewImagesContainer, path, fileInfo.Name, stream,
MIMETypes.Current[".png"]);
}
}
}
} |
using BezierMasterNS.MeshesCreating;
using BezierMasterNS;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(LineMeshCreator))]
public class LineCreatorEditor : MeshCreatorEditor
{
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(lenghtSegmentsProperty);
lenghtSegmentsProperty.intValue = Mathf.Clamp(lenghtSegmentsProperty.intValue, 3, 1000);
EditorGUILayout.PropertyField(widhtSegmentsProperty );
widhtSegmentsProperty.intValue = Mathf.Clamp(widhtSegmentsProperty.intValue, 2, 100);
GUILayout.Space(5);
EditorGUILayout.PropertyField(widthProperty, new GUIContent("Width"));
GUILayout.Space(5);
EditorGUILayout.PropertyField(twoSidedProperty);
EditorGUILayout.PropertyField(textureOrientationProperty);
EditorGUILayout.PropertyField(fixTextureStretchProperty);
GUILayout.Space(5);
EditorGUILayout.PropertyField(TextureScaleProperty);
GUILayout.Space(5);
DrawCopyPasteMenu();
GUILayout.Space(5);
if (serializedObject.hasModifiedProperties)
{
serializedObject.ApplyModifiedProperties();
}
}
}
|
using System;
namespace _10R_Self_methods
{
public class Person
{
public string Name { get; set; }
public string SecondName { get; set; }
public int X { get; set; }
public int Y { get; set; }
public Person(string name, string secondname)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
SecondName = secondname ?? throw new ArgumentNullException(nameof(secondname));
X = 0;
Y = 0;
}
public string Run()
{
var rnd = new Random();
X += rnd.Next(-10, 10);
Y += rnd.Next(-20, 20);
return $"{Name} {SecondName}, ({X},{Y})";
}
// перегрузка метода Run
public string Run(int x, int y)
{
X += x;
Y += y;
return $"{Name} {SecondName}, ({X},{Y})";
}
public string Run(Person y)
{
return $"{Name} {SecondName}, ({X},{Y})";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Razor.App.Controllers
{
using Models;
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.People = new Person[]
{
new Person() {Name = "John Doe", Age = 40, Email = "john@office.com", IsSubscribed = true},
new Person() {Name = "John Doe Jr.", Email = "johnjr@office.com"},
new Person() {Name = "Mickey Mouse", Age = 20, IsSubscribed = false},
};
return View();
}
}
} |
using Andreys.App.ViewModels.Products;
namespace Andreys.App.Services
{
public interface IUsersService
{
string GetUserNameById(string userId);
string GetUserIdByNameAndPassword(string inputUsername, string inputPassword);
bool IsUserExists(string inputUsername);
bool IsEmailExist(string inputEmail);
void Register(string inputUsername, string inputPassword, string inputEmail);
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using com.Sconit.CodeMaster;
namespace com.Sconit.Entity.WMS
{
public partial class PackingList
{
#region Non O/R Mapping Properties
//TODO: Add Non O/R Mapping Properties here.
#endregion
}
}
|
using Microsoft.AspNet.Mvc;
namespace Api.Components.Authentication
{
public class AuthenticationController : Controller
{
}
} |
using UnityEngine;
using System.Collections;
public class swordAttackAnimation : MonoBehaviour {
private Animator animator;
void Awake() {
animator = GetComponent<Animator>();
animator.ResetTrigger("Attacking");
}
public void attack() {
Debug.Log("attack");
animator.SetTrigger("Attacking");
}
}
|
using BoardGame.Domain_Model;
using System;
using System.Windows.Forms;
namespace BoardGame
{
public partial class PropertyCard : Form
{
public string FieldName { get; set; }
public int FieldValue { get; set; }
public int FieldFinishedValue { get; set; }
public int FieldBuildingTurns { get; set; }
private Cards m_Cards;
private Player m_Player;
public PropertyCard(Player player, Cards card)
{
InitializeComponent();
ButtonTip.SetToolTip(Cancel, "Nem veszem meg");
ButtonTip.SetToolTip(Ok, "Lelet megvásárlása");
this.m_Player = player;
this.m_Cards = card;
Random randomCard = new Random();
int randomCardNumber = randomCard.Next(0, m_Cards.PropertyCards.Count);
PlayerOrRobotName.Text = player.Name;
for (int i = 0; i < m_Cards.PropertyCards.Count; i++)
{
if (i == randomCardNumber)
{
CardText.Text = "Gratulálok! Felfedeztél egy " + m_Cards.PropertyCards[i].PropertyName + "-t.";
TurnText.Text = "A feltárásának idelye: " + m_Cards.PropertyCards[i].BuildingTurns + " kör.";
FinishedValue.Text = "Ammennyiben elvégezted " + m_Cards.PropertyCards[i].PropertyFinishedValue + "$-t kapsz.";
Price.Text = m_Cards.PropertyCards[i].PropertyValue + "$";
if (player.Balance >= m_Cards.PropertyCards[i].PropertyValue)
{
FieldFinishedValue = m_Cards.PropertyCards[i].PropertyFinishedValue;
FieldValue = m_Cards.PropertyCards[i].PropertyValue;
FieldName = m_Cards.PropertyCards[i].PropertyName;
FieldBuildingTurns = m_Cards.PropertyCards[i].BuildingTurns;
m_Player.MyPropertyCards.Add(m_Cards.PropertyCards[i]);
m_Cards.PropertyCards.RemoveAt(i);
}
else
{
MessageBox.Show("Sajnáljuk nincs elég Pénezd!", "Bank", MessageBoxButtons.OK);
Ok.Enabled = false;
}
}
}
}
private void Ok_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
this.Close();
}
private void Cancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
this.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MusicLibrary
{
public static class Vars
{
public static List<string> Files = new List<string>();
public static int CurrentTrackNumber;
public static string GetFileName(string file)
{
string[] tmp = file.Split('\\');
return tmp[tmp.Length - 1];
}
public static bool FileAlreadyExistsInFiles(string file)
{
foreach (string f in Files)
{
if (f == file)
{
return true;
}
}
return false;
}
public static bool FileIsMP3(string file)
{
string fileName = GetFileName(file);
string[] tmp = fileName.Split('.');
string extension = tmp[tmp.Length - 1];
if (extension == "mp3")
{
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BugTracker.BusinessLayer
{
class ConsultarProductosConStockCritico
{
}
}
|
using UnityEngine;
using System.Collections.Generic;
public enum StatesEnum {
wander,
alert,
intaract,
retreat,
idle
}
class StateMachine {
GameObject obj;
Animation anim;
State currentState;
StatesEnum defaultState;
Dictionary<StatesEnum, State> States = new Dictionary<StatesEnum, State>();
public StateMachine(GameObject _obj, StatesEnum _defautState, Animation _anim = null)
{
obj = _obj;
defaultState = _defautState;
anim = _anim;
}
public void Start() {
currentState = States[defaultState];
currentState.Enter(obj, anim);
}
public void AddState (StatesEnum enumPos, State theState) {
States.Add(enumPos, theState);
}
public void UpdateState()
{
if (currentState.Reason()) {
currentState.Act();
} else {
try { currentState = States[currentState.Leave()]; }
catch { currentState = States[defaultState]; }
currentState.Enter(obj, anim);
}
}
public void StopMachine()
{
currentState.Leave();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
namespace LoginNavigation
{
public partial class SettingsPage : ContentPage
{
public SettingsPage()
{
InitializeComponent();
}
async void LogOut(object sender, EventArgs e)
{
App.IsUserLoggedIn = false;
await Navigation.PopAsync();
await Navigation.PushAsync(new LoginPage());
}
async void EditProfileClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new MakeProfilePage());
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace MusicLibrary
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class AddSong : Page
{
Song song = new Song();
public AddSong()
{
this.InitializeComponent();
}
// Pic MP3 Button Function
private void ButtonPickMP3_Click(object sender, RoutedEventArgs e)
{
PickMusicFileAsync();
}
//Pic Image Button Function
private void ButtonPickImage_Click(object sender, RoutedEventArgs e)
{
PickImageAsync();
}
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
// Save into file
//?????????????????????????
song.Title = musicTitle.Text;
Song.WriteSong(song);
this.Frame.Navigate(typeof(MainPage));
}
private async System.Threading.Tasks.Task PickImageAsync()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
await file.CopyAsync(ApplicationData.Current.LocalFolder);
song.MusicImage = file.Name;
//Save the file name in file
}
else
{
// OutputTextBlock.Text = "Operation cancelled.";
}
}
private async System.Threading.Tasks.Task PickMusicFileAsync()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
openPicker.FileTypeFilter.Add(".MP3");
openPicker.FileTypeFilter.Add(".MPEG");
openPicker.FileTypeFilter.Add(".MP4");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
await file.CopyAsync(ApplicationData.Current.LocalFolder);
song.MusicFile = file.Name;
}
else
{
// OutputTextBlock.Text = "Operation cancelled.";
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.IO;
using DevExpress.XtraTreeList.Nodes;
namespace IRAP.UFMPS.Library
{
/// <summary>
/// 文件处理方式:以单线程方式将数据文件中的数据插入指定表中
/// </summary>
internal class TThreadInsertIntoTableSingle : TCustomDocumentProcess
{
private static SqlConnection dbConn = null;
private static TThreadInsertIntoTableSingle _instance = null;
/// <summary>
/// 线程是否正在处理
/// </summary>
private bool isThreadRunning = false;
/// <summary>
/// 需要锁定的对象,用于增加待处理数据文件名列表
/// </summary>
private object lockedObject = new object();
/// <summary>
/// 是否需要结束当前线程的运行
/// </summary>
private volatile bool _shouldStopped = true;
private TThreadInsertIntoTableSingle(
string dataFileName,
TTaskInfo taskInfo,
UserControls.UCMonitorLog showLog = null,
TreeListNode nodeParent = null)
: base(dataFileName, taskInfo, showLog, nodeParent)
{
}
~TThreadInsertIntoTableSingle()
{
}
public static TThreadInsertIntoTableSingle Instance
{
get
{
if (_instance == null)
_instance = new TThreadInsertIntoTableSingle("", null);
return _instance;
}
}
public TTaskInfo TaskInfo
{
get { return _task; }
set
{
if (!isThreadRunning)
{
if (_task == null ||
(_task.DbServer != value.DbServer ||
_task.DbName != value.DbName ||
_task.DbUserID != value.DbUserID ||
_task.DbUserPWD != value.DbUserPWD))
{
_task = value;
string connectionString = string.Format("Data Source={0};" +
"Initial Catalog={1};" +
"Persist Security Info=True;" +
"User ID={2};" +
"Password={3};",
_task.DbServer,
_task.DbName,
_task.DbUserID,
_task.DbUserPWD);
if (dbConn != null && dbConn.State == ConnectionState.Open)
dbConn.Close();
dbConn = new SqlConnection(connectionString);
dbConn.Open();
}
}
}
}
public UserControls.UCMonitorLog ShowLog
{
get { return showLog; }
set
{
if (showLog == null)
showLog = value;
}
}
public TreeListNode NodeParent
{
get { return nodeParentLog; }
}
/// <summary>
/// 准备处理的数据文件名(包括路径)
/// </summary>
public new string DataFileName
{
set
{
lock (lockedObject)
{
if (processingFiles.IndexOf(value) < 0)
{
processingFiles.Add(value);
}
else
{
InvokeWriteLog(string.Format("文件[0]已经处于待处理列表中。", value));
}
}
}
}
/// <summary>
/// 线程是否在运行中?
/// </summary>
public bool Running
{
get
{
return !_shouldStopped;
}
}
/// <summary>
/// 单线程处理需要导入的数据文件
/// </summary>
public override void RunProcessing()
{
_shouldStopped = false;
while (!_shouldStopped)
{
// 当线程下一循环开始状态设置为“需导入的表为空”时,检测表是否为空
if (_task.ThreadStartMark == TThreadStartMark.TableIsEmpty)
{
try
{
if (!TableIsEmpty())
{
Thread.Sleep(2000);
continue;
}
}
catch (Exception error)
{
InvokeWriteLog(string.Format("检测表是否为空时发生错误:{0}", error.Message));
Thread.Sleep(2000);
continue;
}
}
// 从待处理的文件列表取下一个需要处理的文件
lock (lockedObject)
{
if (processingFiles.Count > 0)
{
dataFileName = processingFiles[0];
processingFiles.Remove(dataFileName);
}
else
{
dataFileName = "";
}
}
if (dataFileName != "")
{
try
{
if (DocumentProcessing())
{
AfterDocumentProcessing();
}
}
catch (Exception error)
{
InvokeWriteLog(error.Message);
}
InvokeWriteLog(string.Format("文件[{0}]处理完毕。", dataFileName));
nodeParentLog = null;
}
Thread.Sleep(100);
}
_thread = null;
}
protected override bool DocumentProcessing()
{
if (File.Exists(dataFileName))
{
InvokeWriteLog(string.Format("打开文件[{0}]", dataFileName));
if (ReadTextDataFile(dataFileName))
{
return true;
}
else
{
return false;
}
}
else
{
InvokeWriteLog(string.Format("文件[{0}]不存在,无法处理!", dataFileName));
return false;
}
}
/// <summary>
/// 结束当前线程的运行
/// </summary>
public void RequestStop()
{
_shouldStopped = true;
}
/// <summary>
/// 检测插入数据的数据库表是否为空
/// </summary>
private bool TableIsEmpty()
{
string strSQL = string.Format("SELECT * FROM {0}", _task.TbTableName);
SqlCommand cmdSQL = new SqlCommand(strSQL, dbConn);
SqlDataReader reader = cmdSQL.ExecuteReader();
try
{
return !reader.HasRows;
}
finally
{
reader.Close();
}
}
private bool ReadTextDataFile(string strFileName)
{
SqlDataAdapter da = new SqlDataAdapter(
string.Format("SELECT * FROM {0}", _task.TbTableName),
dbConn);
SqlCommand cmdSQL = new SqlCommand();
SqlTransaction transaction = null;
transaction = dbConn.BeginTransaction("IMPORTDATA");
cmdSQL.Connection = dbConn;
cmdSQL.Transaction = transaction;
StreamReader objReader = new StreamReader(dataFileName, Encoding.GetEncoding("GB18030"), true);
try
{
int intLineNo = 0;
string strData = "";
string[] fields = new string[0];
string strSQL = "";
int intStartArrayNo = 0;
bool boolTransactionSuccessfull = true;
while (strData != null)
{
try
{
intLineNo++;
#if DEBUG
InvokeWriteLog(string.Format("读取第 {0} 行......", intLineNo));
#endif
strData = objReader.ReadLine();
#if DEBUG
InvokeWriteLog(string.Format("内容:{0}", strData));
#endif
if (intLineNo < _task.TbDataFirstRow)
{
#if DEBUG
InvokeWriteLog("该行不是数据行,放弃。");
#endif
continue;
}
if (strData != null && strData.Trim() != "")
{
#if DEBUG
InvokeWriteLog(string.Format(
"该行是数据行,根据分割字符({0})进行数据域分割",
_task.TbTxtFileSplitter));
#endif
fields = strData.Split(
new string[] { _task.TbTxtFileSplitter },
StringSplitOptions.RemoveEmptyEntries);
#if DEBUG
InvokeWriteLog(string.Format("将分割后的数据插入表[{0}]中......", _task.TbTableName));
#endif
if (_task.TbIncludeTxtFileName)
{
strSQL = string.Format("'{0}'", Path.GetFileName(dataFileName));
intStartArrayNo = 0;
}
else
{
strSQL = string.Format("'{0}'", fields[0]);
intStartArrayNo = 1;
}
for (int i = intStartArrayNo; i < _task.TbNumOfTxtFields; i++)
{
strSQL = string.Format("{0}, '{1}'", strSQL, fields[i]);
}
strSQL = string.Format("INSERT INTO {0} VALUES({1})", _task.TbTableName, strSQL);
#if DEBUG
InvokeWriteLog(string.Format("执行:{0}", strSQL));
#endif
cmdSQL.CommandText = strSQL;
cmdSQL.ExecuteNonQuery();
}
else
{
#if DEBUG
InvokeWriteLog("该行是结束行,或者是空行,不处理");
#endif
}
}
catch (Exception error)
{
InvokeWriteLog(string.Format("第{0}行数据导入时发生错误:{1}", intLineNo, error.Message));
boolTransactionSuccessfull = false;
}
}
InvokeWriteLog(string.Format("文件[{0}]处理完毕。", dataFileName));
if (boolTransactionSuccessfull)
{
transaction.Commit();
InvokeWriteLog(string.Format("数据导入完成"));
}
else
{
transaction.Rollback();
InvokeWriteLog(string.Format("数据导入失败!"));
}
return true;
}
finally
{
objReader.Close();
}
}
}
}
|
using UnityEngine;
public class EndBossLight : MonoBehaviour
{
public Light myLight;
void Awake ()
{
if ( LevelGeneratorManager.instance != null )
{
LevelGeneratorManager.instance.endBossLight = myLight;
}
}
}
|
using EIM.Router.Consul;
using EIM.Router.Throttle;
namespace EIM.Router
{
public interface IServiceSubscriberFactory
{
IPollingServiceSubscriber CreateSubscriber(string serviceName);
IPollingServiceSubscriber CreateSubscriber(string serviceName, ConsulSubscriberOptions consulOptions,
ThrottleSubscriberOptions throttleOptions);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class HomeProgressUI : MonoBehaviour
{
public TextMeshProUGUI txtCategory;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem91 : ProblemBase {
private HashSet<string> _hash = new HashSet<string>();
private Dictionary<int, Dictionary<int, int>> _keys = new Dictionary<int, Dictionary<int, int>>();
public override string ProblemName {
get { return "91: Right triangles with integer coordinates"; }
}
public override string GetAnswer() {
return Solve(50, 50).ToString();
}
private int Solve(int rowMax, int colMax) {
BuildKeys(rowMax, colMax);
int sum = 0;
for (int x1 = 0; x1 <= colMax; x1++) {
for (int y1 = 0; y1 <= rowMax; y1++) {
if (x1 != 0 || y1 != 0) {
for (int x2 = 0; x2 <= colMax; x2++) {
for (int y2 = 0; y2 <= rowMax; y2++) {
string key = Math.Max(_keys[x1][y1], _keys[x2][y2]).ToString() + ":" + Math.Min(_keys[x1][y1], _keys[x2][y2]).ToString();
if (!_hash.Contains(key)) {
_hash.Add(key);
if (x2 <= x1 && y2 <= y1) {
// do nothing
} else if (x1 == x2 && x1 == 0) {
// do nothing
} else if (y1 == y2 && y1 == 0) {
// do nothing
} else {
decimal d1 = ((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1));
decimal d2 = ((x2 - 0) * (x2 - 0)) + ((y2 - 0) * (y2 - 0));
decimal d3 = ((x1 - 0) * (x1 - 0)) + ((y1 - 0) * (y1 - 0));
if (d1 > d2 && d1 > d3 && DoesFit(d2, d3, d1)) {
sum += 1;
} else if (d2 > d1 && d2 > d3 && DoesFit(d1, d3, d2)) {
sum += 1;
} else if (DoesFit(d1, d2, d3)) {
sum += 1;
}
}
}
}
}
}
}
}
return sum;
}
private void BuildKeys(int rowMax, int colMax) {
int key = 1;
for (int x = 0; x <= rowMax; x++) {
_keys.Add(x, new Dictionary<int, int>());
for (int y = 0; y <= colMax; y++) {
_keys[x].Add(y, key);
key++;
}
}
}
private bool DoesFit(decimal a, decimal b, decimal c) {
if (a + b == c) {
return true;
} else {
return false;
}
}
}
}
|
namespace PlusRemove
{
using System;
using System.Collections.Generic;
using System.Text;
public class Startup
{
public static void Main(string[] args)
{
Execute();
}
private static void Execute()
{
var m = 0;
var list = new List<string>();
var line = Console.ReadLine();
while (line != "END")
{
list.Add(line);
m = Math.Max(line.Length, m);
line = Console.ReadLine();
}
var n = list.Count;
var matrix = new char[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (j < list[i].Length)
{
matrix[i, j] = list[i][j];
}
}
}
var visited = new bool[n, m];
for (int i = 1; i < n - 1; i++)
{
for (int j = 1; j < m - 1; j++)
{
if (CreatesPlusShape(i, j, matrix))
{
VisitAllCells(i, j, visited);
}
}
}
var builder = new StringBuilder();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (!visited[i, j])
{
builder.Append(matrix[i, j]);
}
}
builder.AppendLine();
}
Console.WriteLine(builder.ToString());
}
private static bool CreatesPlusShape(int i, int j, char[,] matrix)
{
var lower =
matrix[i - 1, j].ToString().ToLower()[0] == matrix[i, j] &&
matrix[i, j + 1].ToString().ToLower()[0] == matrix[i, j] &&
matrix[i, j - 1].ToString().ToLower()[0] == matrix[i, j] &&
matrix[i + 1, j].ToString().ToLower()[0] == matrix[i, j];
var upper =
matrix[i - 1, j].ToString().ToUpper()[0] == matrix[i, j] &&
matrix[i, j + 1].ToString().ToUpper()[0] == matrix[i, j] &&
matrix[i, j - 1].ToString().ToUpper()[0] == matrix[i, j] &&
matrix[i + 1, j].ToString().ToUpper()[0] == matrix[i, j];
return lower ? lower : upper;
}
private static void VisitAllCells(int i, int j, bool[,] visited)
{
visited[i - 1, j] = true;
visited[i, j + 1] = true;
visited[i, j - 1] = true;
visited[i + 1, j] = true;
visited[i, j] = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Foundry.SourceControl;
namespace Foundry.Website.Models.Project
{
public class SourceViewModel : ProjectViewModel
{
public ISourceObject Source { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PdfSharp;
using PdfSharp.Drawing;
using System.Drawing;
using PdfSharp.Pdf;
using MigraDoc;
using System.Diagnostics; // to start processes
namespace Tugwell
{
public class Print2Pdf
{
private PdfDocument pdf = new PdfSharp.Pdf.PdfDocument();
private PdfPage pdfPage;
public enum TextStyle
{
Regular = 0,
Bold = 1,
Italic = 2,
BoldItalic = 3,
Underline = 4,
Strikeout = 8,
}
public enum TextPos
{
//Default,
TopLeft,
Center,
TopCenter,
BottomCenter,
TopRight
}
public class TextInfo
{
public TextInfo(List<double> rows, List<double> cols)
{
_row = rows;
_col = cols;
Font = "Times New Roman";
Size = 8.0;
Textstyle = TextStyle.Regular;
Textpos = TextPos.TopLeft;
Mycolor = XBrushes.Black;
TextMarginLR = 0.0;
TextMarginTB = 0.0;
}
public TextInfo()
{
_row = null;
_col = null;
Font = "Times New Roman";
Size = 8.0;
Textstyle = TextStyle.Regular;
Textpos = TextPos.TopLeft;
Mycolor = XBrushes.Black;
TextMarginLR = 0.0;
TextMarginTB = 0.0;
}
public TextInfo(string font, double size)
{
_row = null;
_col = null;
Font = font;
Size = size;
Textstyle = TextStyle.Regular;
Textpos = TextPos.TopLeft;
Mycolor = XBrushes.Black;
TextMarginLR = 0.0;
TextMarginTB = 0.0;
}
private List<double> _row, _col;
public string Font { get; set; }
public double Size { get; set; }
public TextStyle Textstyle { get; set; }
public TextPos Textpos { get; set; }
public XBrush Mycolor { get; set; }
public double TextMarginLR { get; set; }
public double TextMarginTB { get; set; }
public double X1 { get; set; }
public double Y1 { get; set; }
public double X2 { get; set; }
public double Y2 { get; set; }
public double GetRow(int index)
{
return _row[index];
}
public double GetCol(int index)
{
return _col[index];
}
}
public TextInfo CreateTextInfo()
{
return new TextInfo();
}
public TextInfo CreateTextInfo(string font, double size)
{
return new TextInfo(font, size);
}
public Print2Pdf()
{
AddPage();
}
public bool Save(string filename)
{
try
{
pdf.Save(filename);
}
catch { return false; }
return true;
}
public bool ShowPDF(string filename)
{
try
{
Process.Start(filename);
}
catch { return false; }
return true;
}
private void AddPage()
{
pdfPage = pdf.AddPage();
}
public double Width { get { return pdfPage.Width.Point; } }
public double Height { get { return pdfPage.Height.Point; } }
public void AddText(TextInfo ti, string text)
{
AddText(ti, text, ti.X1, ti.Y1, ti.X2, ti.Y2);
}
public void AddText(TextInfo ti, string text, double x1, double y1, double x2, double y2)
{
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
string[] split = text.Split('\n');
ti.X1 = x1;
ti.Y1 = y1;
ti.X2 = x2;
ti.Y2 = y2;
double delta = x2 - x1;
foreach (string line in split)
{
XFont font = new XFont(ti.Font, ti.Size, (XFontStyle)ti.Textstyle);
XSize size = graph.MeasureString(line, font);
if (delta < 47.0 || line.Count() < 30 || size.Width < delta)
{
if (ti.Textpos == TextPos.TopRight)
{
graph.DrawString(line, font, ti.Mycolor, new XRect(x1 + (delta - size.Width - ti.TextMarginLR * 2) + ti.TextMarginLR, ti.Y1 + ti.TextMarginTB, x2 - ti.TextMarginLR, ti.Y2 - ti.TextMarginTB),
//(ti.Textpos == TextPos.Default) ? XStringFormats.Default :
(ti.Textpos == TextPos.Center) ? XStringFormats.Center :
(ti.Textpos == TextPos.BottomCenter) ? XStringFormats.BottomCenter :
(ti.Textpos == TextPos.TopCenter) ? XStringFormats.TopCenter :
(ti.Textpos == TextPos.TopRight) ? XStringFormats.TopLeft :
XStringFormats.TopLeft);
}
else
{
graph.DrawString(line, font, ti.Mycolor, new XRect(x1 + ti.TextMarginLR, ti.Y1 + ti.TextMarginTB, x2 - ti.TextMarginLR, ti.Y2 - ti.TextMarginTB),
//(ti.Textpos == TextPos.Default) ? XStringFormats.Default :
(ti.Textpos == TextPos.Center) ? XStringFormats.Center :
(ti.Textpos == TextPos.BottomCenter) ? XStringFormats.BottomCenter :
(ti.Textpos == TextPos.TopCenter) ? XStringFormats.TopCenter :
(ti.Textpos == TextPos.TopRight) ? XStringFormats.TopLeft :
XStringFormats.TopLeft);
}
ti.Y1 += ti.Size;
ti.Y2 += ti.Size;
}
else
{
List<string> subLines = new List<string>();
//size = graph.MeasureString(line, font);
int totalChars = line.Count();
int approxCount = (int)(((delta - 46.0) / size.Width) * (double)totalChars);
int i, start = 0;
for (i = approxCount; i < totalChars; i++)
{
if (line[i] == ' ')
{
int length = i - start + 1;
if ((length > 0) && ((length + start) <= totalChars))
{
subLines.Add(line.Substring(start, length));
start = i + 1;
i += approxCount;
}
}
}
try
{
subLines.Add(line.Substring(start, ((i > totalChars) ? totalChars : i) - start));
}
catch { }
foreach (string aline in subLines)
{
if (ti.Textpos == TextPos.TopRight)
{
XSize size2 = graph.MeasureString(aline, font);
graph.DrawString(line, font, ti.Mycolor, new XRect(x1 + (delta - size2.Width - ti.TextMarginLR * 2) + ti.TextMarginLR, ti.Y1 + ti.TextMarginTB, x2 - ti.TextMarginLR, ti.Y2 - ti.TextMarginTB),
//(ti.Textpos == TextPos.Default) ? XStringFormats.Default :
(ti.Textpos == TextPos.Center) ? XStringFormats.Center :
(ti.Textpos == TextPos.BottomCenter) ? XStringFormats.BottomCenter :
(ti.Textpos == TextPos.TopCenter) ? XStringFormats.TopCenter :
(ti.Textpos == TextPos.TopRight) ? XStringFormats.TopLeft :
XStringFormats.TopLeft);
}
else
{
graph.DrawString(aline, font, ti.Mycolor, new XRect(x1 + ti.TextMarginLR, ti.Y1 + ti.TextMarginTB, x2 - ti.TextMarginLR, ti.Y2 - ti.TextMarginTB),
//(ti.Textpos == TextPos.Default) ? XStringFormats.Default :
(ti.Textpos == TextPos.Center) ? XStringFormats.Center :
(ti.Textpos == TextPos.BottomCenter) ? XStringFormats.BottomCenter :
(ti.Textpos == TextPos.TopCenter) ? XStringFormats.TopCenter :
(ti.Textpos == TextPos.TopRight) ? XStringFormats.TopLeft :
XStringFormats.TopLeft);
}
ti.Y1 += ti.Size;
ti.Y2 += ti.Size;
}
}
}
graph.Dispose();
}
public void DrawHorizontalLine(double pinSize, double y, double margin)
{
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XPen pen = new XPen(XColor.FromName("Black"), pinSize);
graph.DrawLine(pen, 0 + margin, y, this.Width - margin, y);
graph.Dispose();
}
public void DrawHorizontalLineDouble(double pinSize, double y, double margin)
{
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XPen pen = new XPen(XColor.FromName("Black"), pinSize);
graph.DrawLine(pen, 0 + margin, y, this.Width - margin, y);
graph.DrawLine(pen, 0 + margin, y + pinSize * 2, this.Width - margin, y + pinSize * 2);
graph.Dispose();
}
public void DrawVerticalLine(double pinSize, double x, double margin)
{
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XPen pen = new XPen(XColor.FromName("Black"), pinSize);
graph.DrawLine(pen, x, 0 + margin, x, this.Height - margin);
graph.Dispose();
}
public void DrawImage(Image image, double x, double y, double width, double heigth)
{
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XImage xi = (XImage)image;
graph.DrawImage(xi, x, y, width, heigth);
graph.Dispose();
}
public TextInfo AddTable(double xPosition, int rowCount, double rowHeight, List<double> colPercents, double tableMarginLR)
{
if (colPercents == null || colPercents.Count == 0)
throw new Exception("Invalid column percents in table");
double x = xPosition;
double yLeft = tableMarginLR;
double yRight = this.Width - yLeft;
List<double> r = new List<double>();
List<double> c = new List<double>();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XPen pen = new XPen(XColor.FromName("Black"), 0.5);
for (int yy = 0; yy <= rowCount; yy++)
{
r.Add(x + yy * rowHeight);
graph.DrawLine(pen, yLeft, x + yy * rowHeight, yRight, x + yy * rowHeight);
}
double yPos = yLeft;
double tWidth = yRight - yLeft;
for (int yy = 0; yy < colPercents.Count(); yy++)
{
graph.DrawLine(pen, yPos, x, yPos, x + rowCount * rowHeight);
c.Add(yPos);
yPos += tWidth * colPercents[yy] / 100;
}
c.Add(yPos);
graph.DrawLine(pen, yPos, x, yPos, x + rowCount * rowHeight);
graph.Dispose();
return new TextInfo(r, c);
}
public void AddTableText(TextInfo ti, string text, int rowIndex, int colIndex)
{
AddText(ti, text, ti.GetCol(colIndex), ti.GetRow(rowIndex), ti.GetCol(colIndex + 1), ti.GetRow(rowIndex + 1));
}
}
} |
using MinecraftToolsBoxSDK;
using Newtonsoft.Json;
using System;
namespace MinecraftToolsBoxSDK.Json.Advancements
{
/// <summary>
/// 基本条件(Condition)参数,表示实体的位置信息
/// </summary>
public class Location
{
[JsonConverter(typeof(EnumNameToJsonFormateConverter))]
[JsonProperty("biome")]
/// <summary>
/// 实体所处的生物群系
/// </summary>
public BiomeName Biome { get; set; }
[JsonConverter(typeof(EnumNameToJsonFormateConverter))]
[JsonProperty("dimension")]
/// <summary>
/// 实体所处的维度
/// </summary>
public DimensionName Dimension { get; set; }
[JsonProperty("feature")]
/// <summary>
/// 实体所处的结构(structure)名称
/// </summary>
public string Feature { get; set; }
[JsonProperty("position")]
/// <summary>
/// 坐标位置
/// </summary>
public Position Position { get; set; }
}
public enum BiomeName { BIOME }
public enum DimensionName { TheOverworld, TheNether, TheEnd }
/// <summary>
/// 基本条件(Condition)参数,表示实体的坐标信息
/// </summary>
public class Distance
{
[JsonProperty("x")]
/// <summary>
/// 到原点的x距离范围
/// 设置为double值表示精确数据 或 实例化DoubleRange表示范围
/// </summary>
public object XRange { get; set; }
[JsonProperty("y")]
/// <summary>
/// 到原点的y距离范围
/// 设置为double值表示精确数据 或 实例化DoubleRange表示范围
/// </summary>
public object YRange { get; set; }
[JsonProperty("z")]
/// <summary>
/// 到原点的z距离范围
/// 设置为double值表示精确数据 或 实例化DoubleRange表示范围
/// </summary>
public object ZRange { get; set; }
}
public class HorizontalDistance
{
[JsonProperty("horizontal")]
public IntegerRange Horizontal { get; set; }
}
/// <summary>
/// 基本条件(Condition)参数,表示实体的位置信息
/// </summary>
public class Position
{
[JsonProperty("x")]
/// <summary>
/// 到原点的x距离范围
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object XRange { get; set; }
[JsonProperty("y")]
/// <summary>
/// 到原点的y距离范围
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object YRange { get; set; }
[JsonProperty("z")]
/// <summary>
/// 到原点的z距离范围
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object ZRange { get; set; }
}
public class Effect
{
[JsonIgnore]
public EffectsName EffectName { get; set; }
[JsonProperty("amplifer")]
/// <summary>
/// 效果等级
/// 设置为整数(int)表示确定的数据 或 实例化IntegerRange表示范围
/// </summary>
public object Amplifer { get; set; }
[JsonProperty("duration")]
/// <summary>
/// 效果持续时间,以Tick为单位
/// 设置为整数(int)表示确定的数据 或 实例化IntegerRange表示范围
/// </summary>
public object Duration { get; set; }
}
public enum EffectsName { EFECT }
public class ItemData
{
[JsonProperty("count")]
/// <summary>
/// 物品数量。
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object Count { get; set; }
[JsonProperty("data")]
/// <summary>
/// 物品数据值。
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object Data { get; set; }
[JsonProperty("durability")]
/// <summary>
/// 物品耐久度。
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object Durability { get; set; }
[JsonProperty("enchantments")]
/// <summary>
/// 魔咒列表
/// </summary>
public Enchantment[] Enchantments { get; set; }
[JsonProperty("item")]
/// <summary>
/// 物品ID
/// 注意:以 minecraft: 开头
/// </summary>
public string Item { get; set; }
[JsonProperty("nbt")]
/// <summary>
/// 物品的NBT标签
/// </summary>
public string Nbt { get; set; }
[JsonConverter(typeof(StringToJsonFormateConverter))]
[JsonProperty("potion")]
/// <summary>
/// 酿造药水的ID
/// </summary>
public PotionID Potion { get; set; }
}
public enum PotionID { POTION }
public class Enchantment
{
[JsonConverter(typeof(EnumNameToJsonFormateConverter))]
[JsonProperty("enchantment")]
public EnchantmentName EnchantmentName { get; set; }
[JsonProperty("levels")]
/// <summary>
/// 魔咒等级。
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object Levels { get; set; }
}
public enum EnchantmentName { ENCHANTMENT }
public class IntegerRange
{
[JsonProperty("max")]
public int? Max { get; set; }
[JsonProperty("min")]
public int? Min { get; set; }
}
public class DoubleRange
{
[JsonProperty("max")]
public double? Max { get; set; }
[JsonProperty("min")]
public double? Min { get; set; }
}
/// <summary>
/// 二级条件(Condition)参数,包含实体数据
/// </summary>
public class EntityData
{
[JsonProperty("distance")]
/// <summary>
/// 可以使用以下方式表示实体到原点的距离参数
/// 一个整数(int)或 实例化IntegerRange表示范围 或 实例化HorizontalDistance表示水平距离 或 实例化Distance表示3D空间中的距离参数
/// </summary>
public object Distance { get; set; }
[JsonProperty("effects")]
[JsonConverter(typeof(EffectNameConverter))]
/// <summary>
/// 状态效果列表。
/// </summary>
public Effect[] Effects { get; set; }
[JsonProperty("location")]
/// <summary>
/// 实体的位置信息
/// </summary>
public Location Location { get; set; }
[JsonProperty("nbt")]
/// <summary>
/// 匹配实体的NBT
/// </summary>
public string Nbt { get; set; }
}
/// <summary>
/// EntityData的扩展类,增加了实体ID属性
/// </summary>
public class ExtendedEntityData : EntityData
{
[JsonConverter(typeof(EnumNameToJsonFormateConverter))]
[JsonProperty("type")]
/// <summary>
/// 实体ID
/// </summary>
public EntityName Type { get; set; }
}
public enum EntityName { ENTITY }
public class Damage
{
[JsonProperty("blocked")]
/// <summary>
/// 检查伤害是否被成功阻挡。
/// </summary>
public bool? Blocked { get; set; }
[JsonProperty("dealt")]
/// <summary>
/// 在减少伤害前检查实体即将受到的伤害。
/// 设置为double值表示精确数据 或 实例化DoubleRange表示范围
/// </summary>
public object Dealt { get; set; }
[JsonProperty("source_entity")]
/// <summary>
/// 伤害来源
/// </summary>
public ExtendedEntityData SourceEntity { get; set; }
[JsonProperty("taken")]
/// <summary>
/// 在减少伤害前检查实体即将受到的伤害。
/// 设置为double值表示精确数据 或 实例化DoubleRange表示范围
/// </summary>
public object Taken { get; set; }
[JsonProperty("type")]
/// <summary>
///
/// </summary>
public DamageType Type { get; set; }
}
public class DamageType
{
[JsonProperty("bypasses_armor")]
/// <summary>
///
/// </summary>
public bool? BypassesArmor { get; set; }
[JsonProperty("bypasses_invulnerability")]
/// <summary>
///
/// </summary>
public bool? BypassesInvulnerability { get; set; }
[JsonProperty("bypasses_magic")]
/// <summary>
///
/// </summary>
public bool? BypassesMagic { get; set; }
[JsonProperty("is_explosion")]
/// <summary>
///
/// </summary>
public bool? IsExplosion { get; set; }
[JsonProperty("is_fire")]
/// <summary>
///
/// </summary>
public bool? IsFire { get; set; }
[JsonProperty("is_magic")]
/// <summary>
///
/// </summary>
public bool? IsMagic { get; set; }
[JsonProperty("is_projectile")]
/// <summary>
///
/// </summary>
public bool? IsProjectile { get; set; }
}//待确认
public class Slots
{
[JsonProperty("empty")]
/// <summary>
/// 物品栏中空槽位数量。
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object Empty { get; set; }
[JsonProperty("full")]
/// <summary>
/// 物品栏中已被完全使用(填充了一组物品)槽位数量。
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object Full { get; set; }
[JsonProperty("occupied")]
/// <summary>
/// 物品栏中已使用槽位数量。
/// 设置为int值表示精确数据 或 实例化IntegerRange表示范围
/// </summary>
public object Occupied { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Start_Botton : MonoBehaviour
{
public void First_Botton()
{
SceneManager.LoadScene("MainScene");
}
}
|
using BS;
using System;
using UMA.Examples;
using UMA.PoseTools;
using UnityEngine;
namespace FireBall
{
public class FireBallSpell : LevelModule
{
private ItemData itemData;
public string itemID = "FireBallSpellItem";
public override void OnLevelLoaded(LevelDefinition levelDefinition)
{
initialized = true;
itemData = Catalog.current.GetData<ItemData>(itemID, true);
}
public override void Update(LevelDefinition levelDefinition)
{
Player player = Player.local;
if (!initialized || player == null || player.body == null)
{
return;
}
var rightHand = (player.body.handRight != null);
var leftHand = (player.body.handLeft != null);
if (rightHand && !leftHand) HandleCast(player.body.handRight, null);
if (!rightHand && leftHand) HandleCast(player.body.handLeft, null);
if (rightHand && leftHand) HandleCast(player.body.handRight, player.body.handLeft);
}
private void HandleCast(BodyHand hand, BodyHand secondaryHand)
{
// check if both hands are empty and close to eachother,
// in that case use dualCasting.
var mainHandCanCast = VerifyCanCast(hand);
if (!mainHandCanCast) return;
var secondaryHandCanCast = false;
if (secondaryHand != null)
secondaryHandCanCast = VerifyCanCast(secondaryHand);
// Attempt dual casting, otherwise just cast normal spell
if (secondaryHandCanCast && TryDualCastSpell(hand, secondaryHand))
return;
CastSpell(hand);
}
private bool TryDualCastSpell(BodyHand hand, BodyHand secondaryHand)
{
if (Vector3.Distance(hand.transform.position, secondaryHand.transform.position) > 0.5) return false;
var controlHand = PlayerControl.GetHand(hand.side);
var secondaryControlHand = PlayerControl.GetHand(secondaryHand.side);
if (!(controlHand.gripPressed || secondaryControlHand.gripPressed)) return false; // Need to be creative here...
if (!(controlHand.usePressed || secondaryControlHand.usePressed)) return false;
var item = itemData.Spawn();
item.gameObject.AddComponent<FireBallScript>();
item.gameObject.GetComponent<FireBallScript>().isDualCast = true;
var distance = 0f;
item.transform.position = Vector3.Lerp(hand.transform.position, secondaryHand.transform.position, 0.5f) + Player.local.body.transform.forward * distance;
item.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
hand.telekinesis.StartTargeting(item.GetMainHandle(hand.side));
hand.telekinesis.TryCatch();
secondaryHand.telekinesis.StartTargeting(item.GetMainHandle(hand.side));
secondaryHand.telekinesis.TryCatch();
item.gameObject.GetComponentInChildren<Collider>().isTrigger = false;
return true;
}
private void CastSpell(BodyHand hand)
{
var controlHand = PlayerControl.GetHand(hand.side);
if (!controlHand.usePressed) return;
if (!controlHand.gripPressed) return; // Need to be creative here...
var item = itemData.Spawn();
item.gameObject.AddComponent<FireBallScript>();
item.gameObject.GetComponent<FireBallScript>().castHand = hand;
var distance = 0.5f;
item.transform.position = hand.caster.transform.position - hand.transform.up * distance; // Spawn object distance meters infront of hand
item.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
hand.telekinesis.StartTargeting(item.GetMainHandle(hand.side));
hand.telekinesis.TryCatch();
item.gameObject.GetComponentInChildren<Collider>().isTrigger = false;
}
private bool VerifyCanCast(BodyHand hand)
{
var caster = hand.caster;
if (caster == null || caster.currentSpell == null)
{
return false;
}
if (caster.currentSpell.name != "FireBallSpell(Clone)")
{
GameObject.Destroy(caster.currentSpell.gameObject);
return false;
}
if (hand.interactor.grabbedHandle != null) // or if only grabbed fireball
{
return false;
}
if (hand.telekinesis.catchedHandle != null)
{
return false;
}
return true;
}
public override void OnLevelUnloaded(LevelDefinition levelDefinition)
{
initialized = false;
}
}
}
|
public class Solution {
public int TitleToNumber(string s) {
int bas = 1;
int res = 0;
for(int i = s.Length - 1; i >= 0; i--) {
res += (s[i]-'A'+1) * bas;
bas *= 26;
}
return res;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BikeDistributor.Interfaces.CommonServices;
using BikeDistributor.Shared.Interfaces;
namespace BikeDistributor.Services.Common
{
public class LogService : ILogService
{
public void Error(Exception ex, string additionalInfo = "")
{
Console.WriteLine(ex.Message);
}
public void Error(string message)
{
Console.WriteLine(message);
}
public void Info(string message)
{
Console.WriteLine(message);
}
public void Info(IEntity entity)
{
if (entity != null)
{
Console.WriteLine(
$@"{entity.ToString()} has been created by succesfully");
}
}
public void Warn(string message)
{
Console.WriteLine(message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Graphics.PackedVector;
using Microsoft.Xna.Framework;
/*
Reference: From http://xbox.create.msdn.com/en-US/education/catalog/sample/particle_3d
* */
// Copyright (c) All Rights Reserved.
//
// 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
namespace ShootingGame.Particle
{
struct ParticleVertex
{
// Stores which corner of the particle quad this vertex represents.
public Short2 Corner;
// Stores the starting position of the particle.
public Vector3 Position;
// Stores the starting velocity of the particle.
public Vector3 Velocity;
// Four random values, used to make each particle look slightly different.
public Color Random;
// The time (in seconds) at which this particle was created.
public float Time;
// Describe the layout of this vertex structure.
public static readonly VertexDeclaration VertexDeclaration = new VertexDeclaration
(
new VertexElement(0, VertexElementFormat.Short2,
VertexElementUsage.Position, 0),
new VertexElement(4, VertexElementFormat.Vector3,
VertexElementUsage.Position, 1),
new VertexElement(16, VertexElementFormat.Vector3,
VertexElementUsage.Normal, 0),
new VertexElement(28, VertexElementFormat.Color,
VertexElementUsage.Color, 0),
new VertexElement(32, VertexElementFormat.Single,
VertexElementUsage.TextureCoordinate, 0)
);
// Describe the size of this vertex structure.
public const int SizeInBytes = 36;
}
}
|
using System;
using System.Collections.Generic;
using Substrate.Nbt;
namespace Substrate
{
/// <summary>
/// Provides named id values for known item types.
/// </summary>
/// <remarks>See <see cref="BlockType"/> for additional information.</remarks>
public static class ItemType
{
public const int IRON_SHOVEL = 256;
public const int IRON_PICKAXE = 257;
public const int IRON_AXE = 258;
public const int FLINT_AND_STEEL = 259;
public const int APPLE = 260;
public const int BOW = 261;
public const int ARROW = 262;
public const int COAL = 263;
public const int DIAMOND = 264;
public const int IRON_INGOT = 265;
public const int GOLD_INGOT = 266;
public const int IRON_SWORD = 267;
public const int WOODEN_SWORD = 268;
public const int WOODEN_SHOVEL = 269;
public const int WOODEN_PICKAXE = 270;
public const int WOODEN_AXE = 271;
public const int STONE_SWORD = 272;
public const int STONE_SHOVEL = 273;
public const int STONE_PICKAXE = 274;
public const int STONE_AXE = 275;
public const int DIAMOND_SWORD = 276;
public const int DIAMOND_SHOVEL = 277;
public const int DIAMOND_PICKAXE = 278;
public const int DIAMOND_AXE = 279;
public const int STICK = 280;
public const int BOWL = 281;
public const int MUSHROOM_SOUP = 282;
public const int GOLD_SWORD = 283;
public const int GOLD_SHOVEL = 284;
public const int GOLD_PICKAXE = 285;
public const int GOLD_AXE = 286;
public const int STRING = 287;
public const int FEATHER = 288;
public const int GUNPOWDER = 289;
public const int WOODEN_HOE = 290;
public const int STONE_HOE = 291;
public const int IRON_HOE = 292;
public const int DIAMOND_HOE = 293;
public const int GOLD_HOE = 294;
public const int SEEDS = 295;
public const int WHEAT = 296;
public const int BREAD = 297;
public const int LEATHER_CAP = 298;
public const int LEATHER_TUNIC = 299;
public const int LEATHER_PANTS = 300;
public const int LEATHER_BOOTS = 301;
public const int CHAIN_HELMET = 302;
public const int CHAIN_CHESTPLATE = 303;
public const int CHAIN_LEGGINGS = 304;
public const int CHAIN_BOOTS = 305;
public const int IRON_HELMET = 306;
public const int IRON_CHESTPLATE = 307;
public const int IRON_LEGGINGS = 308;
public const int IRON_BOOTS = 309;
public const int DIAMOND_HELMET = 310;
public const int DIAMOND_CHESTPLATE = 311;
public const int DIAMOND_LEGGINGS = 312;
public const int DIAMOND_BOOTS = 313;
public const int GOLD_HELMET = 314;
public const int GOLD_CHESTPLATE = 315;
public const int GOLD_LEGGINGS = 316;
public const int GOLD_BOOTS = 317;
public const int FLINT = 318;
public const int RAW_PORKCHOP = 319;
public const int COOKED_PORKCHOP = 320;
public const int PAINTING = 321;
public const int GOLDEN_APPLE = 322;
public const int SIGN = 323;
public const int WOODEN_DOOR = 324;
public const int BUCKET = 325;
public const int WATER_BUCKET = 326;
public const int LAVA_BUCKET = 327;
public const int MINECART = 328;
public const int SADDLE = 329;
public const int IRON_DOOR = 330;
public const int REDSTONE_DUST = 331;
public const int SNOWBALL = 332;
public const int BOAT = 333;
public const int LEATHER = 334;
public const int MILK = 335;
public const int CLAY_BRICK = 336;
public const int CLAY = 337;
public const int SUGAR_CANE = 338;
public const int PAPER = 339;
public const int BOOK = 340;
public const int SLIMEBALL = 341;
public const int STORAGE_MINECART = 342;
public const int POWERED_MINECARD = 343;
public const int EGG = 344;
public const int COMPASS = 345;
public const int FISHING_ROD = 346;
public const int CLOCK = 347;
public const int GLOWSTONE_DUST = 348;
public const int RAW_FISH = 349;
public const int COOKED_FISH = 350;
public const int DYE = 351;
public const int BONE = 352;
public const int SUGAR = 353;
public const int CAKE = 354;
public const int BED = 355;
public const int REDSTONE_REPEATER = 356;
public const int COOKIE = 357;
public const int MAP = 358;
public const int SHEARS = 359;
public const int MELON_SLICE = 360;
public const int PUMPKIN_SEEDS = 361;
public const int MELON_SEEDS = 262;
public const int RAW_BEEF = 363;
public const int STEAK = 364;
public const int RAW_CHICKEN = 365;
public const int COOKED_CHICKEN = 366;
public const int ROTTEN_FLESH = 367;
public const int ENDER_PEARL = 368;
public const int BLAZE_ROD = 369;
public const int GHAST_TEAR = 370;
public const int GOLD_NUGGET = 371;
public const int NETHER_WART = 372;
public const int POTION = 373;
public const int GLASS_BOTTLE = 374;
public const int SPIDER_EYE = 375;
public const int FERMENTED_SPIDER_EYE = 376;
public const int BLAZE_POWDER = 377;
public const int MAGMA_CREAM = 378;
public const int BREWING_STAND = 379;
public const int CAULDRON = 380;
public const int EYE_OF_ENDER = 381;
public const int GLISTERING_MELON = 382;
public const int SPAWN_EGG = 383;
public const int BOTTLE_O_ENCHANTING = 384;
public const int FIRE_CHARGE = 385;
public const int BOOK_AND_QUILL = 386;
public const int WRITTEN_BOOK = 387;
public const int EMERALD = 388;
public const int ITEM_FRAME = 389;
public const int FLOWER_POT = 390;
public const int CARROT = 391;
public const int POTATO = 392;
public const int BAKED_POTATO = 393;
public const int POISON_POTATO = 394;
public const int EMPTY_MAP = 395;
public const int GOLDEN_CARROT = 396;
public const int MOB_HEAD = 397;
public const int CARROT_ON_A_STICK = 398;
public const int NETHER_STAR = 399;
public const int PUMPKIN_PIE = 400;
public const int FIREWORK_ROCKET = 401;
public const int FIREWORK_STAR = 402;
public const int ENCHANTED_BOOK = 403;
public const int REDSTONE_COMPARATOR = 404;
public const int NETHER_BRICK = 405;
public const int NETHER_QUARTZ = 406;
public const int TNT_MINECART = 407;
public const int HOPPER_MINECART = 408;
public const int IRON_HORSE_ARMOR = 417;
public const int GOLD_HORSE_ARMOR = 418;
public const int DIAMOND_HORSE_ARMOR = 419;
public const int LEAD = 420;
public const int NAME_TAG = 421;
public const int MUSIC_DISC_13 = 2256;
public const int MUSIC_DISC_CAT = 2257;
public const int MUSIC_DISC_BLOCKS = 2258;
public const int MUSIC_DISC_CHIRP = 2259;
public const int MUSIC_DISC_FAR = 2260;
public const int MUSIC_DISC_MALL = 2261;
public const int MUSIC_DISC_MELLOHI = 2262;
public const int MUSIC_DISC_STAL = 2263;
public const int MUSIC_DISC_STRAD = 2264;
public const int MUSIC_DISC_WARD = 2265;
public const int MUSIC_DISC_11 = 2266;
}
/// <summary>
/// Provides information on a specific type of item.
/// </summary>
/// <remarks>By default, all known MC item types are already defined and registered, assuming Substrate
/// is up to date with the current MC version.
/// New item types may be created and used at runtime, and will automatically populate various static lookup tables
/// in the <see cref="ItemInfo"/> class.</remarks>
public class ItemInfo
{
private static Random _rand = new Random();
private class CacheTableDict<T> : ICacheTable<T>
{
private Dictionary<int, T> _cache;
public T this[int index]
{
get
{
T val;
if (_cache.TryGetValue(index, out val)) {
return val;
}
return default(T);
}
}
public CacheTableDict (Dictionary<int, T> cache)
{
_cache = cache;
}
}
private static readonly Dictionary<int, ItemInfo> _itemTable;
private int _id = 0;
private string _name = "";
private int _stack = 1;
private static readonly CacheTableDict<ItemInfo> _itemTableCache;
/// <summary>
/// Gets the lookup table for id-to-info values.
/// </summary>
public static ICacheTable<ItemInfo> ItemTable
{
get { return _itemTableCache; }
}
/// <summary>
/// Gets the id of the item type.
/// </summary>
public int ID
{
get { return _id; }
}
/// <summary>
/// Gets the name of the item type.
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Gets the maximum stack size allowed for this item type.
/// </summary>
public int StackSize
{
get { return _stack; }
}
/// <summary>
/// Constructs a new <see cref="ItemInfo"/> record for the given item id.
/// </summary>
/// <param name="id">The id of an item type.</param>
public ItemInfo (int id)
{
_id = id;
_itemTable[_id] = this;
}
/// <summary>
/// Constructs a new <see cref="ItemInfo"/> record for the given item id and name.
/// </summary>
/// <param name="id">The id of an item type.</param>
/// <param name="name">The name of an item type.</param>
public ItemInfo (int id, string name)
{
_id = id;
_name = name;
_itemTable[_id] = this;
}
/// <summary>
/// Sets the maximum stack size for this item type.
/// </summary>
/// <param name="stack">A stack size between 1 and 64, inclusive.</param>
/// <returns>The object instance used to invoke this method.</returns>
public ItemInfo SetStackSize (int stack)
{
_stack = stack;
return this;
}
/// <summary>
/// Chooses a registered item type at random and returns it.
/// </summary>
/// <returns></returns>
public static ItemInfo GetRandomItem ()
{
List<ItemInfo> list = new List<ItemInfo>(_itemTable.Values);
return list[_rand.Next(list.Count)];
}
public static ItemInfo IronShovel;
public static ItemInfo IronPickaxe;
public static ItemInfo IronAxe;
public static ItemInfo FlintAndSteel;
public static ItemInfo Apple;
public static ItemInfo Bow;
public static ItemInfo Arrow;
public static ItemInfo Coal;
public static ItemInfo Diamond;
public static ItemInfo IronIngot;
public static ItemInfo GoldIngot;
public static ItemInfo IronSword;
public static ItemInfo WoodenSword;
public static ItemInfo WoodenShovel;
public static ItemInfo WoodenPickaxe;
public static ItemInfo WoodenAxe;
public static ItemInfo StoneSword;
public static ItemInfo StoneShovel;
public static ItemInfo StonePickaxe;
public static ItemInfo StoneAxe;
public static ItemInfo DiamondSword;
public static ItemInfo DiamondShovel;
public static ItemInfo DiamondPickaxe;
public static ItemInfo DiamondAxe;
public static ItemInfo Stick;
public static ItemInfo Bowl;
public static ItemInfo MushroomSoup;
public static ItemInfo GoldSword;
public static ItemInfo GoldShovel;
public static ItemInfo GoldPickaxe;
public static ItemInfo GoldAxe;
public static ItemInfo String;
public static ItemInfo Feather;
public static ItemInfo Gunpowder;
public static ItemInfo WoodenHoe;
public static ItemInfo StoneHoe;
public static ItemInfo IronHoe;
public static ItemInfo DiamondHoe;
public static ItemInfo GoldHoe;
public static ItemInfo Seeds;
public static ItemInfo Wheat;
public static ItemInfo Bread;
public static ItemInfo LeatherCap;
public static ItemInfo LeatherTunic;
public static ItemInfo LeatherPants;
public static ItemInfo LeatherBoots;
public static ItemInfo ChainHelmet;
public static ItemInfo ChainChestplate;
public static ItemInfo ChainLeggings;
public static ItemInfo ChainBoots;
public static ItemInfo IronHelmet;
public static ItemInfo IronChestplate;
public static ItemInfo IronLeggings;
public static ItemInfo IronBoots;
public static ItemInfo DiamondHelmet;
public static ItemInfo DiamondChestplate;
public static ItemInfo DiamondLeggings;
public static ItemInfo DiamondBoots;
public static ItemInfo GoldHelmet;
public static ItemInfo GoldChestplate;
public static ItemInfo GoldLeggings;
public static ItemInfo GoldBoots;
public static ItemInfo Flint;
public static ItemInfo RawPorkchop;
public static ItemInfo CookedPorkchop;
public static ItemInfo Painting;
public static ItemInfo GoldenApple;
public static ItemInfo Sign;
public static ItemInfo WoodenDoor;
public static ItemInfo Bucket;
public static ItemInfo WaterBucket;
public static ItemInfo LavaBucket;
public static ItemInfo Minecart;
public static ItemInfo Saddle;
public static ItemInfo IronDoor;
public static ItemInfo RedstoneDust;
public static ItemInfo Snowball;
public static ItemInfo Boat;
public static ItemInfo Leather;
public static ItemInfo Milk;
public static ItemInfo ClayBrick;
public static ItemInfo Clay;
public static ItemInfo SugarCane;
public static ItemInfo Paper;
public static ItemInfo Book;
public static ItemInfo Slimeball;
public static ItemInfo StorageMinecart;
public static ItemInfo PoweredMinecart;
public static ItemInfo Egg;
public static ItemInfo Compass;
public static ItemInfo FishingRod;
public static ItemInfo Clock;
public static ItemInfo GlowstoneDust;
public static ItemInfo RawFish;
public static ItemInfo CookedFish;
public static ItemInfo Dye;
public static ItemInfo Bone;
public static ItemInfo Sugar;
public static ItemInfo Cake;
public static ItemInfo Bed;
public static ItemInfo RedstoneRepeater;
public static ItemInfo Cookie;
public static ItemInfo Map;
public static ItemInfo Shears;
public static ItemInfo MelonSlice;
public static ItemInfo PumpkinSeeds;
public static ItemInfo MelonSeeds;
public static ItemInfo RawBeef;
public static ItemInfo Steak;
public static ItemInfo RawChicken;
public static ItemInfo CookedChicken;
public static ItemInfo RottenFlesh;
public static ItemInfo EnderPearl;
public static ItemInfo BlazeRod;
public static ItemInfo GhastTear;
public static ItemInfo GoldNugget;
public static ItemInfo NetherWart;
public static ItemInfo Potion;
public static ItemInfo GlassBottle;
public static ItemInfo SpiderEye;
public static ItemInfo FermentedSpiderEye;
public static ItemInfo BlazePowder;
public static ItemInfo MagmaCream;
public static ItemInfo BrewingStand;
public static ItemInfo Cauldron;
public static ItemInfo EyeOfEnder;
public static ItemInfo GlisteringMelon;
public static ItemInfo SpawnEgg;
public static ItemInfo BottleOEnchanting;
public static ItemInfo FireCharge;
public static ItemInfo BookAndQuill;
public static ItemInfo WrittenBook;
public static ItemInfo Emerald;
public static ItemInfo ItemFrame;
public static ItemInfo FlowerPot;
public static ItemInfo Carrot;
public static ItemInfo Potato;
public static ItemInfo BakedPotato;
public static ItemInfo PoisonPotato;
public static ItemInfo EmptyMap;
public static ItemInfo GoldenCarrot;
public static ItemInfo MobHead;
public static ItemInfo CarrotOnStick;
public static ItemInfo NetherStar;
public static ItemInfo PumpkinPie;
public static ItemInfo FireworkRocket;
public static ItemInfo FireworkStar;
public static ItemInfo EnchantedBook;
public static ItemInfo RedstoneComparator;
public static ItemInfo NetherBrick;
public static ItemInfo NetherQuartz;
public static ItemInfo TntMinecart;
public static ItemInfo HopperMinecart;
public static ItemInfo IronHorseArmor;
public static ItemInfo GoldHorseArmor;
public static ItemInfo DiamondHorseArmor;
public static ItemInfo Lead;
public static ItemInfo NameTag;
public static ItemInfo MusicDisc13;
public static ItemInfo MusicDiscCat;
public static ItemInfo MusicDiscBlocks;
public static ItemInfo MusicDiscChirp;
public static ItemInfo MusicDiscFar;
public static ItemInfo MusicDiscMall;
public static ItemInfo MusicDiscMellohi;
public static ItemInfo MusicDiscStal;
public static ItemInfo MusicDiscStrad;
public static ItemInfo MusicDiscWard;
public static ItemInfo MusicDisc11;
static ItemInfo ()
{
_itemTable = new Dictionary<int, ItemInfo>();
_itemTableCache = new CacheTableDict<ItemInfo>(_itemTable);
IronShovel = new ItemInfo(256, "Iron Shovel");
IronPickaxe = new ItemInfo(257, "Iron Pickaxe");
IronAxe = new ItemInfo(258, "Iron Axe");
FlintAndSteel = new ItemInfo(259, "Flint and Steel");
Apple = new ItemInfo(260, "Apple").SetStackSize(64);
Bow = new ItemInfo(261, "Bow");
Arrow = new ItemInfo(262, "Arrow").SetStackSize(64);
Coal = new ItemInfo(263, "Coal").SetStackSize(64);
Diamond = new ItemInfo(264, "Diamond").SetStackSize(64);
IronIngot = new ItemInfo(265, "Iron Ingot").SetStackSize(64);
GoldIngot = new ItemInfo(266, "Gold Ingot").SetStackSize(64);
IronSword = new ItemInfo(267, "Iron Sword");
WoodenSword = new ItemInfo(268, "Wooden Sword");
WoodenShovel = new ItemInfo(269, "Wooden Shovel");
WoodenPickaxe = new ItemInfo(270, "Wooden Pickaxe");
WoodenAxe = new ItemInfo(271, "Wooden Axe");
StoneSword = new ItemInfo(272, "Stone Sword");
StoneShovel = new ItemInfo(273, "Stone Shovel");
StonePickaxe = new ItemInfo(274, "Stone Pickaxe");
StoneAxe = new ItemInfo(275, "Stone Axe");
DiamondSword = new ItemInfo(276, "Diamond Sword");
DiamondShovel = new ItemInfo(277, "Diamond Shovel");
DiamondPickaxe = new ItemInfo(278, "Diamond Pickaxe");
DiamondAxe = new ItemInfo(279, "Diamond Axe");
Stick = new ItemInfo(280, "Stick").SetStackSize(64);
Bowl = new ItemInfo(281, "Bowl").SetStackSize(64);
MushroomSoup = new ItemInfo(282, "Mushroom Soup");
GoldSword = new ItemInfo(283, "Gold Sword");
GoldShovel = new ItemInfo(284, "Gold Shovel");
GoldPickaxe = new ItemInfo(285, "Gold Pickaxe");
GoldAxe = new ItemInfo(286, "Gold Axe");
String = new ItemInfo(287, "String").SetStackSize(64);
Feather = new ItemInfo(288, "Feather").SetStackSize(64);
Gunpowder = new ItemInfo(289, "Gunpowder").SetStackSize(64);
WoodenHoe = new ItemInfo(290, "Wooden Hoe");
StoneHoe = new ItemInfo(291, "Stone Hoe");
IronHoe = new ItemInfo(292, "Iron Hoe");
DiamondHoe = new ItemInfo(293, "Diamond Hoe");
GoldHoe = new ItemInfo(294, "Gold Hoe");
Seeds = new ItemInfo(295, "Seeds").SetStackSize(64);
Wheat = new ItemInfo(296, "Wheat").SetStackSize(64);
Bread = new ItemInfo(297, "Bread").SetStackSize(64);
LeatherCap = new ItemInfo(298, "Leather Cap");
LeatherTunic = new ItemInfo(299, "Leather Tunic");
LeatherPants = new ItemInfo(300, "Leather Pants");
LeatherBoots = new ItemInfo(301, "Leather Boots");
ChainHelmet = new ItemInfo(302, "Chain Helmet");
ChainChestplate = new ItemInfo(303, "Chain Chestplate");
ChainLeggings = new ItemInfo(304, "Chain Leggings");
ChainBoots = new ItemInfo(305, "Chain Boots");
IronHelmet = new ItemInfo(306, "Iron Helmet");
IronChestplate = new ItemInfo(307, "Iron Chestplate");
IronLeggings = new ItemInfo(308, "Iron Leggings");
IronBoots = new ItemInfo(309, "Iron Boots");
DiamondHelmet = new ItemInfo(310, "Diamond Helmet");
DiamondChestplate = new ItemInfo(311, "Diamond Chestplate");
DiamondLeggings = new ItemInfo(312, "Diamond Leggings");
DiamondBoots = new ItemInfo(313, "Diamond Boots");
GoldHelmet = new ItemInfo(314, "Gold Helmet");
GoldChestplate = new ItemInfo(315, "Gold Chestplate");
GoldLeggings = new ItemInfo(316, "Gold Leggings");
GoldBoots = new ItemInfo(317, "Gold Boots");
Flint = new ItemInfo(318, "Flint").SetStackSize(64);
RawPorkchop = new ItemInfo(319, "Raw Porkchop").SetStackSize(64);
CookedPorkchop = new ItemInfo(320, "Cooked Porkchop").SetStackSize(64);
Painting = new ItemInfo(321, "Painting").SetStackSize(64);
GoldenApple = new ItemInfo(322, "Golden Apple").SetStackSize(64);
Sign = new ItemInfo(323, "Sign");
WoodenDoor = new ItemInfo(324, "Door");
Bucket = new ItemInfo(325, "Bucket");
WaterBucket = new ItemInfo(326, "Water Bucket");
LavaBucket = new ItemInfo(327, "Lava Bucket");
Minecart = new ItemInfo(328, "Minecart");
Saddle = new ItemInfo(329, "Saddle");
IronDoor = new ItemInfo(330, "Iron Door");
RedstoneDust = new ItemInfo(331, "Redstone Dust").SetStackSize(64);
Snowball = new ItemInfo(332, "Snowball").SetStackSize(16);
Boat = new ItemInfo(333, "Boat");
Leather = new ItemInfo(334, "Leather").SetStackSize(64);
Milk = new ItemInfo(335, "Milk");
ClayBrick = new ItemInfo(336, "Clay Brick").SetStackSize(64);
Clay = new ItemInfo(337, "Clay").SetStackSize(64);
SugarCane = new ItemInfo(338, "Sugar Cane").SetStackSize(64);
Paper = new ItemInfo(339, "Paper").SetStackSize(64);
Book = new ItemInfo(340, "Book").SetStackSize(64);
Slimeball = new ItemInfo(341, "Slimeball").SetStackSize(64);
StorageMinecart = new ItemInfo(342, "Storage Miencart");
PoweredMinecart = new ItemInfo(343, "Powered Minecart");
Egg = new ItemInfo(344, "Egg").SetStackSize(16);
Compass = new ItemInfo(345, "Compass");
FishingRod = new ItemInfo(346, "Fishing Rod");
Clock = new ItemInfo(347, "Clock");
GlowstoneDust = new ItemInfo(348, "Glowstone Dust").SetStackSize(64);
RawFish = new ItemInfo(349, "Raw Fish").SetStackSize(64);
CookedFish = new ItemInfo(350, "Cooked Fish").SetStackSize(64);
Dye = new ItemInfo(351, "Dye").SetStackSize(64);
Bone = new ItemInfo(352, "Bone").SetStackSize(64);
Sugar = new ItemInfo(353, "Sugar").SetStackSize(64);
Cake = new ItemInfo(354, "Cake");
Bed = new ItemInfo(355, "Bed");
RedstoneRepeater = new ItemInfo(356, "Redstone Repeater").SetStackSize(64);
Cookie = new ItemInfo(357, "Cookie").SetStackSize(8);
Map = new ItemInfo(358, "Map");
Shears = new ItemInfo(359, "Shears");
MelonSlice = new ItemInfo(360, "Melon Slice").SetStackSize(64);
PumpkinSeeds = new ItemInfo(361, "Pumpkin Seeds").SetStackSize(64);
MelonSeeds = new ItemInfo(362, "Melon Seeds").SetStackSize(64);
RawBeef = new ItemInfo(363, "Raw Beef").SetStackSize(64);
Steak = new ItemInfo(364, "Steak").SetStackSize(64);
RawChicken = new ItemInfo(365, "Raw Chicken").SetStackSize(64);
CookedChicken = new ItemInfo(366, "Cooked Chicken").SetStackSize(64);
RottenFlesh = new ItemInfo(367, "Rotten Flesh").SetStackSize(64);
EnderPearl = new ItemInfo(368, "Ender Pearl").SetStackSize(64);
BlazeRod = new ItemInfo(369, "Blaze Rod").SetStackSize(64);
GhastTear = new ItemInfo(370, "Ghast Tear").SetStackSize(64);
GoldNugget = new ItemInfo(371, "Gold Nugget").SetStackSize(64);
NetherWart = new ItemInfo(372, "Nether Wart").SetStackSize(64);
Potion = new ItemInfo(373, "Potion");
GlassBottle = new ItemInfo(374, "Glass Bottle").SetStackSize(64);
SpiderEye = new ItemInfo(375, "Spider Eye").SetStackSize(64);
FermentedSpiderEye = new ItemInfo(376, "Fermented Spider Eye").SetStackSize(64);
BlazePowder = new ItemInfo(377, "Blaze Powder").SetStackSize(64);
MagmaCream = new ItemInfo(378, "Magma Cream").SetStackSize(64);
BrewingStand = new ItemInfo(379, "Brewing Stand").SetStackSize(64);
Cauldron = new ItemInfo(380, "Cauldron");
EyeOfEnder = new ItemInfo(381, "Eye of Ender").SetStackSize(64);
GlisteringMelon = new ItemInfo(382, "Glistering Melon").SetStackSize(64);
SpawnEgg = new ItemInfo(383, "Spawn Egg").SetStackSize(64);
BottleOEnchanting = new ItemInfo(384, "Bottle O' Enchanting").SetStackSize(64);
FireCharge = new ItemInfo(385, "Fire Charge").SetStackSize(64);
BookAndQuill = new ItemInfo(386, "Book and Quill");
WrittenBook = new ItemInfo(387, "Written Book");
Emerald = new ItemInfo(388, "Emerald").SetStackSize(64);
ItemFrame = new ItemInfo(389, "Item Frame").SetStackSize(64);
FlowerPot = new ItemInfo(390, "Flower Pot").SetStackSize(64);
Carrot = new ItemInfo(391, "Carrot").SetStackSize(64);
Potato = new ItemInfo(392, "Potato").SetStackSize(64);
BakedPotato = new ItemInfo(393, "Baked Potato").SetStackSize(64);
PoisonPotato = new ItemInfo(394, "Poisonous Potato").SetStackSize(64);
EmptyMap = new ItemInfo(395, "Empty Map").SetStackSize(64);
GoldenCarrot = new ItemInfo(396, "Golden Carrot").SetStackSize(64);
MobHead = new ItemInfo(397, "Mob Head").SetStackSize(64);
CarrotOnStick = new ItemInfo(398, "Carrot on a Stick");
NetherStar = new ItemInfo(399, "Nether Star").SetStackSize(64);
PumpkinPie = new ItemInfo(400, "Pumpkin Pie").SetStackSize(64);
FireworkRocket = new ItemInfo(401, "Firework Rocket");
FireworkStar = new ItemInfo(402, "Firework Star").SetStackSize(64);
EnchantedBook = new ItemInfo(403, "Enchanted Book");
RedstoneComparator = new ItemInfo(404, "Redstone Comparator").SetStackSize(64);
NetherBrick = new ItemInfo(405, "Nether Brick").SetStackSize(64);
NetherQuartz = new ItemInfo(406, "Nether Quartz").SetStackSize(64);
TntMinecart = new ItemInfo(407, "Minecart with TNT");
HopperMinecart = new ItemInfo(408, "Minecart with Hopper");
IronHorseArmor = new ItemInfo(417, "Iron Horse Armor");
GoldHorseArmor = new ItemInfo(418, "Gold Horse Armor");
DiamondHorseArmor = new ItemInfo(419, "Diamond Horse Armor");
Lead = new ItemInfo(420, "Lead").SetStackSize(64);
NameTag = new ItemInfo(421, "Name Tag").SetStackSize(64);
MusicDisc13 = new ItemInfo(2256, "13 Disc");
MusicDiscCat = new ItemInfo(2257, "Cat Disc");
MusicDiscBlocks = new ItemInfo(2258, "Blocks Disc");
MusicDiscChirp = new ItemInfo(2259, "Chirp Disc");
MusicDiscFar = new ItemInfo(2260, "Far Disc");
MusicDiscMall = new ItemInfo(2261, "Mall Disc");
MusicDiscMellohi = new ItemInfo(2262, "Mellohi Disc");
MusicDiscStal = new ItemInfo(2263, "Stal Disc");
MusicDiscStrad = new ItemInfo(2264, "Strad Disc");
MusicDiscWard = new ItemInfo(2265, "Ward Disc");
MusicDisc11 = new ItemInfo(2266, "11 Disc");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1dv402_oo222bu_2_2_digital_vackarklocka
{
class Program
{
static void Main(string[] args)
{
//Första testet
ViewTestHeader("Test 1:\nTest av standardkonstruktorn");
AlarmClock firstClock = new AlarmClock();
Console.WriteLine(firstClock.ToString());
//Andra testet
ViewTestHeader("Test 2:\nTest av konstruktorn med två parametrar. (9,42)");
AlarmClock secondClock = new AlarmClock(9, 42);
Console.WriteLine(secondClock.ToString());
//Tredje testet
ViewTestHeader("Test 3:\nTest av konstruktorn med fyra parametrar. (13,24,7,35)");
AlarmClock thirdClock = new AlarmClock(13, 24, 7, 35);
Console.WriteLine(thirdClock.ToString());
//Fjärde testet
ViewTestHeader("Test 4:\nStäll ett befintligt AlarmClock-objekt till 23:58 och låter den gå 13 minuter.");
thirdClock.Hour = 23;
thirdClock.Minute = 58;
Run(thirdClock, 13);
//Femte testet
ViewTestHeader("Test 5:\nStäller befintligt AlarmClock-objekt till tiden 6:12\noch alarmtiden till 6:15 och låter den gå 6 minuter.");
thirdClock.Hour = 6;
thirdClock.Minute = 12;
thirdClock.AlarmHour = 6;
thirdClock.AlarmMinute = 15;
Run(thirdClock, 6);
//Sjätte testet
ViewTestHeader("Test 6:\nTest av egenskaperna så att undantag kastas \ndå tid och alarmtid tilldelas felaktiga värden");
try
{
thirdClock.Hour = 27;
}
catch (ArgumentException)
{
ViewErrorMessage("Timmen är inte i intervallet 0-23 .");
}
try
{
thirdClock.Minute = 99;
}
catch (ArgumentException)
{
ViewErrorMessage("Minuten är inte i intervallet 0-59 .");
}
try
{
thirdClock.AlarmHour = 27;
}
catch (ArgumentException)
{
ViewErrorMessage("AlarmTimmen är inte i intervallet 0-23 .");
}
try
{
thirdClock.AlarmMinute = 99;
}
catch (ArgumentException)
{
ViewErrorMessage("AlarmMinuten är inte i intervallet 0-59 .");
}
//Sjunde testet
ViewTestHeader("Test 7:\nTest av konstruktorer så att undantag kastas då tid och alarmtid tilldelas \nfelaktiga värden.");
try
{
AlarmClock fourthClock=new AlarmClock(27,0);
}
catch (ArgumentException)
{
ViewErrorMessage("Timmen är inte i intervallet 0-23 .");
}
try
{
AlarmClock fifthClock=new AlarmClock(0,0,27,0);
}
catch (ArgumentException)
{
ViewErrorMessage("AlarmTimmen är inte i intervallet 0-23 .");
}
}
//Skapar metoderna
private static void ViewTestHeader(string header)
{
Console.WriteLine("===============================================================================");
Console.WriteLine(header);
Console.WriteLine();
}
private static void ViewErrorMessage(string message)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
private static void Run(AlarmClock ac, int minutes)
{
Console.BackgroundColor = ConsoleColor.DarkGreen;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(" ╔══════════════════════════════════════╗ ");
Console.WriteLine(" ║ Väckarklockan URLED (TM) ║ ");
Console.WriteLine(" ║ Modellnr:1DV402S2L2A ║ ");
Console.WriteLine(" ╚══════════════════════════════════════╝ ");
Console.WriteLine();
Console.ResetColor();
for (int i = 0; i < minutes; i++)
{
if (ac.TickTock())
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.WriteLine(ac.ToString() + "BEEP! BEEP! BEEP!");
Console.ResetColor();
}
else
{
Console.WriteLine(ac.ToString());
}
}
}
}
}
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Different
{
internal class Listing08
{
public static void MainListing08()
{
string file = "C:/Users/Hero/Desktop/MyTestText.txt";
string str;
string word = "exit";
int k = 1;
try
{
StreamWriter fw = new StreamWriter(file);
Console.WriteLine("Please, write to quit: \"{0}\"",word);
do
{
Console.WriteLine("{0}th string: >", k);
k++;
str = Console.ReadLine();
if (str == word) break;
else fw.WriteLine(str);
}
while (true);
fw.Close();
Console.WriteLine("File was created!");
StreamReader fr = new StreamReader(file);
Console.WriteLine("Into file:");
str = fr.ReadLine();
while (str != null)
{
Console.WriteLine(str);
str = fr.ReadLine();
}
fr.Close();
}
catch(Exception e)
{
Console.WriteLine("Error! Error!");
Console.WriteLine(e.Message);
}
}
}
}
|
using System.Collections.Generic;
namespace Airelax.Application.Houses.Dtos.Response
{
public class FacilityDto
{
public IEnumerable<int> Provide { get; set; }
public IEnumerable<int> NotProvide { get; set; }
}
} |
using System;
class BoolExample
{
static void Main()
{
string myGender = "Male";
bool isFemale = (myGender != "Male");
Console.WriteLine("I'm a man and my gender is Female: {0}", isFemale);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Knjizara.Models
{
public class StavkaRacunViewModel
{
public int Racun { get; set; }
public int RedniBroj { get; set; }
public string Artikal { get; set; }
public int Kolicina { get; set; }
public float Cena { get; set; }
}
} |
using EddiDataDefinitions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using Utilities;
namespace EddiConfigService.Configurations
{
/// <summary>Storage for ship and shipyard information</summary>
[JsonObject(MemberSerialization.OptOut), RelativePath(@"\shipmonitor.json")]
public class ShipMonitorConfiguration : Config
{
public int? currentshipid { get; set; }
public ObservableCollection<Ship> shipyard { get; set; } = new ObservableCollection<Ship>();
public List<StoredModule> storedmodules { get; set; } = new List<StoredModule>();
public DateTime updatedat { get; set; } = DateTime.MinValue;
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
if (!shipyard.Any())
{
// Used to be in a separate 'ships' file so try that to allow migration
string oldFilename = Constants.DATA_DIR + @"\ships.json";
if (File.Exists(oldFilename))
{
try
{
string oldData = Files.Read(oldFilename);
if (oldData != null)
{
var oldShipsConfiguration = JsonConvert.DeserializeObject<Dictionary<string, ObservableCollection<Ship>>>(oldData);
// At this point the old file is confirmed to have been there - migrate it
// There was a bug that caused null entries to be written to the ships configuration; remove these if present
var oldShips = new ObservableCollection<Ship>(oldShipsConfiguration?["ships"]?.Where(x => x.Role != null) ?? new List<Ship>());
shipyard = oldShips;
File.Delete(oldFilename);
}
}
catch (Exception ex)
{
// There was a problem parsing the old file, just press on
Logging.Error(ex.Message, ex);
}
}
}
// Populate static information from definitions
foreach (Ship ship in shipyard)
{
ship.Augment();
}
}
}
}
|
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 ProyectoPP.Models;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
namespace ProyectoPP.Controllers
{
public class sprintsController : Controller
{
private patopurificEntitiesGeneral db = new patopurificEntitiesGeneral();
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
private async Task<bool> revisarPermisos(string permiso)
{
string userName = System.Web.HttpContext.Current.User.Identity.Name;
var user = UserManager.FindByName(userName);
var rol = user.Roles.SingleOrDefault().RoleId;
var permisoID = db.permisos.Where(m => m.permiso == permiso).First().id_permiso;
var listaRoles = db.AspNetRoles.Where(m => m.permisos.Any(c => c.id_permiso == permisoID)).ToList().Select(n => n.Id);
bool userRol = false;
foreach (var element in listaRoles)
{
if (element == rol)
userRol = true;
}
return userRol;
}
// GET: sprints
public ActionResult Index()
{
Sprint2 modelo = new Sprint2();
if ( !System.Web.HttpContext.Current.User.IsInRole("Estudiante")) // Si el usuario no es estudiante
{
// Seleccion para el dropdown de proyectos. Carga todos los proyectos que hay
ViewBag.Proyecto = new SelectList(db.proyecto, "id", "nombre", "Seleccione un Proyecto");
}
else
{
var idproyecto = db.persona.Where(m => m.cedula == System.Web.HttpContext.Current.User.Identity.Name).First().IdProyecto;
// Seleccion para el dropdown de proyectos. Carga solo el proyecto donde participa el estudiante
ViewBag.Proyecto = new SelectList(db.proyecto.Where(x => x.id == idproyecto), "id", "nombre");
ViewBag.NombreProyecto = db.proyecto.Where(m => m.id == idproyecto).First().nombre;
}
return View(modelo);
}
public ActionResult SprintPlanning()
{
DatosSprintPlanning modelo = new DatosSprintPlanning();
if (!System.Web.HttpContext.Current.User.IsInRole("Estudiante")) // Si el usuario no es estudiante
{
// Seleccion para el dropdown de proyectos. Carga todos los proyectos que hay
ViewBag.Proyecto = new SelectList(db.proyecto, "id", "nombre");
// El dropdown de sprints queda en blanco porque no sabemos aún cuál proyecto se va a seleccionar. Para esto solamente busco los sprints donde el id es igual ""
ViewBag.Sprint = new SelectList(db.sprint.Where(x => x.proyectoId == ""), "id", "id");
// Repito el proceso con las HU, busco las que tengan ID ""
ViewBag.HU = db.historiasDeUsuario.Where(x => x.proyectoId == "").ToList();
}
else
{
var idproyecto = db.persona.Where(m => m.cedula == System.Web.HttpContext.Current.User.Identity.Name).First().IdProyecto;
// Seleccion para el dropdown de proyectos. Carga solo el proyecto donde participa el estudiante
ViewBag.Proyecto = new SelectList(db.proyecto.Where(x => x.id == idproyecto), "id", "nombre");
// Seleccion para el dropdown de sprints. Carga todos los sprints que hay asociados al proyecto seleccionado
ViewBag.Sprint = new SelectList(db.sprint.Where(x => x.proyectoId == idproyecto), "id", "id");
// Lss hitorias de usuario no se cargan ya que necesito seleccionar un sprint
ViewBag.HU = db.historiasDeUsuario.Where(x => x.proyectoId == "").ToList();
}
modelo.fechaC = db.fechas.ToList();
return View(modelo);
}
// GET: sprints/Details/5
public ActionResult Details(string id, string proyectoId)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
sprint sprint = db.sprint.Find(id, proyectoId);
Sprint2 s = new Sprint2();
s.fechaInicio = sprint.fechaInicio;
/*string[] fecha = sprint.fechaFinal.ToString().Split('/');
int año = Int32.Parse(fecha[2]);
s.fechaFinal = new DateTime(Int32.Parse(fecha[2]), Int32.Parse(fecha[1]), Int32.Parse(fecha[1]) ); */
s.fechaFinal = sprint.fechaFinal;
s.id = sprint.id;
s.proyectoId = sprint.proyectoId;
ViewBag.nombreProyecto = db.proyecto.Where(p => p.id == proyectoId).FirstOrDefault().nombre;
if (sprint == null)
{
return HttpNotFound();
}
return View(s);
}
// GET: sprints/Create
public ActionResult Create(string proyectoId)
{
if (proyectoId != null)
{
ViewBag.nombreProyecto = db.proyecto.Where(p => p.id == proyectoId).First().nombre;
//autogenero el numero de sprint
var max = db.sprint.Where(s => s.proyectoId == proyectoId).Max(s => s.id);
if (max == null) max = "0";
int n = Int32.Parse(max);
n = n + 1;
//asigno valores que ya deben de ir por defecto y no se pueden modificar
ViewBag.proyectoId = proyectoId;
ViewBag.id = "" + n;
Sprint2 mod = new Sprint2();
mod.proyectoId = proyectoId;
mod.nombreProyecto = db.proyecto.Where(p => p.id == proyectoId).First().nombre;
mod.id = "" + n;
return View(mod);
}
TempData["msg"] = "<script>alert('Primero seleccione un pryecto');</script>";
return RedirectToAction("Index");
}
// POST: sprints/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( Sprint2 sprint)
{
sprint nuevoSprint = new sprint();
//nuevoSprint.historiasDeUsuario = sprint.historiasDeUsuario;
nuevoSprint.id = sprint.id;
nuevoSprint.fechaInicio = sprint.fechaInicio;
nuevoSprint.fechaFinal = sprint.fechaFinal;
nuevoSprint.proyectoId = sprint.proyectoId;
nuevoSprint.proyecto = sprint.proyecto;
db.sprint.Add(nuevoSprint);
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
Console.WriteLine(ex);
TempData["msg"] = "<script>alert('Ha ocurrido un error al crear el sprint');</script>";
return View(sprint);
}
//ViewBag.proyectoId = new SelectList(db.proyecto, "id", "nombre", sprint.proyectoId);
//return View(sprint);
}
public ActionResult CreateHito()
{
return View();
TempData["msg"] = "<script>alert('Primero seleccione un pryecto');</script>";
return RedirectToAction("Index");
}
// POST: sprints/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateHito(fechas fecha)
{
//sprint nuevoSprint = new sprint();
//nuevoSprint.historiasDeUsuario = sprint.historiasDeUsuario;
//nuevoSprint.id = sprint.id;
//nuevoSprint.fechaInicio = sprint.fechaInicio;
//nuevoSprint.fechaFinal = sprint.fechaFinal;
//nuevoSprint.proyectoId = sprint.proyectoId;
//nuevoSprint.proyecto = sprint.proyecto;
db.fechas.Add(fecha);
try
{
db.SaveChanges();
return RedirectToAction("SprintPlanning");
}
catch (Exception ex)
{
Console.WriteLine(ex);
TempData["msg"] = "<script>alert('Ha ocurrido un error al crear el sprint');</script>";
return View();
}
//ViewBag.proyectoId = new SelectList(db.proyecto, "id", "nombre", sprint.proyectoId);
//return View(sprint);
}
// GET: sprints/Edit/5
public ActionResult Edit(string id, string proyectoId)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// se busca en la base de datos el sprinta editar
sprint sprintTMP = db.sprint.Find(id, proyectoId);
Sprint2 sprint = new Sprint2();
// en caso de que no lo encuentre
if (sprintTMP == null)
{
return HttpNotFound();
}
// Aqui se le asignan los campos a una clase que no es autogenerada para poder asi editar los nombres desplegados
sprint.proyectoId = sprintTMP.proyectoId;
sprint.id = sprintTMP.id;
sprint.fechaInicio = sprintTMP.fechaInicio;
/*string[] fecha = sprintTMP.fechaFinal.ToString().Split('/');
sprint.fechaFinal = new DateTime(Int32.Parse(fecha[0]), Int32.Parse(fecha[1]), Int32.Parse(fecha[2]) );*/
sprint.fechaFinal = sprintTMP.fechaFinal;
// ViewBag.proyectoId = new SelectList(db.proyecto, "id", "nombre", sprint.proyectoId);
return View(sprint);
}
// POST: sprints/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "id,fechaInicio,fechaFinal,proyectoId")] sprint sprint)
{
if (ModelState.IsValid)
{
db.Entry(sprint).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.proyectoId = new SelectList(db.proyecto, "id", "nombre", sprint.proyectoId);
return View(sprint);
}
// GET: sprints/Delete/5
public ActionResult Delete(string id, string proyectoId)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
sprint sprint = db.sprint.Find(id,proyectoId);
if (sprint == null)
{
return HttpNotFound();
}
return View(sprint);
}
// POST: sprints/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id, string proyectoId)
{
sprint sprint = db.sprint.Find(id, proyectoId);
db.sprint.Remove(sprint);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
/** Metodo para actualizar la vista una vez seleccionado un un proyecto*/
public ActionResult Actualizar(Sprint2 modelo)
{
// Si el usuario no es estudiante
if (!System.Web.HttpContext.Current.User.IsInRole("Estudiante"))
{
ViewBag.Sprints = db.sprint.Where(m => m.proyectoId == modelo.proyectoId).ToList();
ViewBag.Proyecto = new SelectList(db.proyecto, "id", "nombre", modelo.proyectoId);
}
// Si el usuario es estudiante
else
{
ViewBag.Sprints = new SelectList(db.sprint.Where(x => x.id == modelo.id), "id", "fechaInicio", "fechaFinal", "proyectoId", modelo.id);
}
//modelo.ListaPB = (from H in db.historiasDeUsuario where H.proyectoId == modelo.ProyectoID select H).ToList();
return View("Index", modelo);
}
public ActionResult ActualizarSprintPlanning(DatosSprintPlanning modelo)
{
if (!System.Web.HttpContext.Current.User.IsInRole("Estudiante")) // Si el usuario no es estudiante
{
// Seleccion para el dropdown de proyectos. Carga todos los proyectos que hay
ViewBag.Proyecto = new SelectList(db.proyecto, "id", "nombre", modelo.ProyectoId);
// El dropdown de sprints carga solamente los sprints asociados al proyecto seleccionado
ViewBag.Sprint = new SelectList(db.sprint.Where(x => x.proyectoId == modelo.ProyectoId), "id", "id", modelo.SprintID);
// El dropdonw de las hisotrias de usuario se hace con la combinación de ambas cosas
ViewBag.HU = db.historiasDeUsuario.Where(x => x.proyectoId == modelo.ProyectoId && x.sprintId == modelo.SprintID).ToList();
}
else
{
var idproyecto = db.persona.Where(m => m.cedula == System.Web.HttpContext.Current.User.Identity.Name).First().IdProyecto;
// Seleccion para el dropdown de proyectos. Carga solo el proyecto donde participa el estudiante
ViewBag.Proyecto = new SelectList(db.proyecto.Where(x => x.id == idproyecto), "id", "nombre", modelo.ProyectoId);
// Seleccion para el dropdown de sprints. Carga todos los sprints que hay asociados al proyecto seleccionado
ViewBag.Sprint = new SelectList(db.sprint.Where(x => x.proyectoId == idproyecto), "id", "id", modelo.SprintID);
ViewBag.HU = db.historiasDeUsuario.Where(x => x.proyectoId == idproyecto && x.sprintId == modelo.SprintID).ToList();
}
return View("SprintPlanning", modelo);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ex1
{
class Program
{
static void Main(string[] args)
{
ArrayList all = new ArrayList();
int i = 0 , c = 0 , min =0;
int max = 0 , sum = 0 ;
try
{
Console.WriteLine("input num ,'q' or 'x' is quit!");
do
{
string m = Console.ReadLine().Trim();
if (m == "q" | m == "x")
{
break;
}
else
{
i = Convert.ToInt32(m);
all.Add(i);
sum = sum + i;
if (max < i)
max = i;
++c;
}
} while (true);
}
catch (FormatException)
{
Console.WriteLine("error ! please input int ,again!");
Console.ReadKey();
return;
}
Console.WriteLine("shu zu shi :");
min = max;
foreach (int x in all)
if (min > x )
min = x ;
Console.WriteLine("shu zu de shu ju ru xia :");
Console.WriteLine("max={0}\nmin={1}\nsum={2}\navg={3} ",max,min,sum,sum/c);
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Thesis {
public sealed class ColorManager
{
private static readonly ColorManager _instance = new ColorManager();
public static ColorManager Instance
{
get { return _instance; }
}
private static bool _isInitialized;
private Dictionary<string, Color> _colors;
private Dictionary<string, List<Color>> _collections;
private ColorManager ()
{
_colors = new Dictionary<string, Color>();
_collections = new Dictionary<string, List<Color>>();
_isInitialized = false;
}
public void Init ()
{
if (!_isInitialized)
{
AddComponentColors();
AddWallColors();
_isInitialized = true;
}
}
public void Unload ()
{
_colors.Clear();
foreach (List<Color> l in _collections.Values)
l.Clear();
_collections.Clear();
_isInitialized = false;
}
public void Add (string name, Color color)
{
if (!_colors.ContainsKey(name))
_colors.Add(name, color);
}
public void AddToCollection (string name, Color color)
{
if (_collections.ContainsKey(name))
{
if (!_collections[name].Contains(color))
_collections[name].Add(color);
}
else
{
var list = new List<Color>();
list.Add(color);
_collections.Add(name, list);
}
}
public Color Get (string name)
{
return _colors.ContainsKey(name) ? _colors[name] : Color.clear;
}
public List<Color> GetCollection (string name)
{
return _collections.ContainsKey(name) ? _collections[name] : null;
}
private void AddComponentColors ()
{
var name = "col_components";
AddToCollection(name, new Color32( 245, 245, 220, 255));
AddToCollection(name, new Color32( 210, 180, 140, 255));
AddToCollection(name, new Color32( 151, 105, 79, 255));
AddToCollection(name, new Color32( 139, 105, 105, 255));
AddToCollection(name, new Color32( 139, 90, 51, 255));
AddToCollection(name, new Color32( 139, 69, 19, 255));
AddToCollection(name, new Color32( 133, 99, 99, 255));
AddToCollection(name, new Color32( 107, 66, 38, 255));
AddToCollection(name, new Color32( 92, 64, 51, 255));
AddToCollection(name, new Color32( 92, 51, 23, 255));
}
private void AddWallColors ()
{
var name = "col_walls";
AddToCollection(name, new Color32( 166, 159, 141, 255));
AddToCollection(name, new Color32( 231, 206, 165, 255));
AddToCollection(name, new Color32( 173, 155, 155, 255));
AddToCollection(name, new Color32( 135, 125, 115, 255));
AddToCollection(name, new Color32( 155, 157, 143, 255));
AddToCollection(name, new Color32( 225, 168, 151, 255));
AddToCollection(name, new Color32( 224, 174, 125, 255));
AddToCollection(name, new Color32( 216, 191, 150, 255));
AddToCollection(name, new Color32( 205, 171, 110, 255));
AddToCollection(name, new Color32( 165, 133, 118, 255));
AddToCollection(name, new Color32( 190, 169, 164, 255));
AddToCollection(name, new Color32( 194, 183, 181, 255));
}
}
} // namespace Thesis |
using System;
namespace BattleEngine.Utils
{
public class IntRandom : Random
{
/**
* An int [0..int.MAX_VALUE]
* @return An int [0..int.MAX_VALUE]
*/
public IntRandom(int seed) : base(seed)
{
}
public override double next()
{
return sampleInt();
}
/**
* An int [minvalue..maxvalue]
* @param minValue
* @param maxValue
* @return An int [minvalue..maxvalue]
*/
public int nextInRange(int minValue, int maxValue)
{
if (minValue > maxValue)
{
throw new ArgumentException("minValue > maxValue");
}
var range = maxValue - minValue;
return (int)(sample() * range) + minValue;
}
/**
* An int [0..maxValue]
* @param maxValue
* @return An int [0..maxValue]
*/
public int nextInMax(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentException("maxValue < 0");
}
return (int)(sample() * maxValue);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Food : WorldObject
{
/**
* Gets eaten by another world object.
*/
public override bool Interact (WorldObject other_object)
{
/* We only want to interact with sheep */
if (other_object.GetType () == typeof (Sheep))
{
Sheep sheep = (Sheep) other_object;
return EatenBySheep (sheep);
}
return false;
}
/**
* Gets eaten by a sheep.
*/
protected virtual bool EatenBySheep (Sheep sheep)
{
return true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DATN_Hoa_Yambi.Models
{
public class ketquabotritungcoc
{
public string Name { get; set; }
public double yi { get; set; }
public double xi { get; set; }
public double Pi { get; set; }
}
} |
using System;
using System.ComponentModel.Composition;
namespace Autofac.Extras.AttributeMetadata.Test.ScenarioTypes.NestedLifetimeScopeRegistrationScenario
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public class NestedLifetimeScopeRegistrationMetadataAttribute : Attribute
{
public string Value { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace HBPonto.Kernel.DTO
{
public class JiraShareWorklogDTO
{
public List<JiraIssuesForPostWorklogDTO> Issues { get; set; }
public JiraWorklogDTO Worklog { get; set; }
}
}
|
using ArangoDBNetStandard.Serialization;
using ArangoDBNetStandard.TransactionApi.Models;
using ArangoDBNetStandard.Transport;
using System.Threading.Tasks;
namespace ArangoDBNetStandard.TransactionApi
{
/// <summary>
/// Provides access to ArangoDB transaction API.
/// </summary>
public class TransactionApiClient : ApiClientBase, ITransactionApiClient
{
/// <summary>
/// The transport client used to communicate with the ArangoDB host.
/// </summary>
protected IApiClientTransport _client;
/// <summary>
/// The root path of the API.
/// </summary>
protected readonly string _transactionApiPath = "_api/transaction";
/// <summary>
/// Create an instance of <see cref="TransactionApiClient"/>
/// using the provided transport layer and the default JSON serialization.
/// </summary>
/// <param name="client"></param>
public TransactionApiClient(IApiClientTransport client)
: base(new JsonNetApiClientSerialization())
{
_client = client;
}
/// <summary>
/// Create an instance of <see cref="TransactionApiClient"/>
/// using the provided transport and serialization layers.
/// </summary>
/// <param name="client"></param>
/// <param name="serializer"></param>
public TransactionApiClient(IApiClientTransport client, IApiClientSerialization serializer)
: base(serializer)
{
_client = client;
}
/// <summary>
/// POST a js-transaction to ArangoDB.
/// </summary>
/// <remarks>
/// https://www.arangodb.com/docs/stable/http/transaction-js-transaction.html
/// </remarks>
/// <typeparam name="T">Type to use for deserializing the object returned by the transaction function.</typeparam>
/// <param name="body">Object containing information to submit in the POST transaction request.</param>
/// <returns>Response from ArangoDB after processing the request.</returns>
public virtual async Task<PostTransactionResponse<T>> PostTransactionAsync<T>(
PostTransactionBody body)
{
var content = GetContent(body, new ApiClientSerializationOptions(true, true));
using (var response = await _client.PostAsync(_transactionApiPath, content))
{
var stream = await response.Content.ReadAsStreamAsync();
if (response.IsSuccessStatusCode)
{
return DeserializeJsonFromStream<PostTransactionResponse<T>>(stream);
}
var error = DeserializeJsonFromStream<ApiErrorResponse>(stream);
throw new ApiErrorException(error);
}
}
}
}
|
using System;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using Xunit;
namespace SideBySide
{
public class Transaction : IClassFixture<TransactionFixture>
{
public Transaction(TransactionFixture database)
{
m_database = database;
m_connection = m_database.Connection;
}
[Fact]
public void NestedTransactions()
{
using (m_connection.BeginTransaction())
{
Assert.Throws<InvalidOperationException>(() => m_connection.BeginTransaction());
}
}
[Fact]
public void Commit()
{
m_connection.Execute("delete from transactions_test");
using (var trans = m_connection.BeginTransaction())
{
m_connection.Execute("insert into transactions_test values(1), (2)", transaction: trans);
trans.Commit();
}
var results = m_connection.Query<int>(@"select value from transactions_test order by value;");
Assert.Equal(new[] { 1, 2 }, results);
}
#if !BASELINE
[Fact]
public async Task CommitAsync()
{
await m_connection.ExecuteAsync("delete from transactions_test").ConfigureAwait(false);
using (var trans = await m_connection.BeginTransactionAsync().ConfigureAwait(false))
{
await m_connection.ExecuteAsync("insert into transactions_test values(1), (2)", transaction: trans).ConfigureAwait(false);
await trans.CommitAsync().ConfigureAwait(false);
}
var results = await m_connection.QueryAsync<int>(@"select value from transactions_test order by value;").ConfigureAwait(false);
Assert.Equal(new[] { 1, 2 }, results);
}
#endif
[Fact]
public void Rollback()
{
m_connection.Execute("delete from transactions_test");
using (var trans = m_connection.BeginTransaction())
{
m_connection.Execute("insert into transactions_test values(1), (2)", transaction: trans);
trans.Rollback();
}
var results = m_connection.Query<int>(@"select value from transactions_test order by value;");
Assert.Equal(new int[0], results);
}
#if !BASELINE
[Fact]
public async Task RollbackAsync()
{
await m_connection.ExecuteAsync("delete from transactions_test").ConfigureAwait(false);
using (var trans = await m_connection.BeginTransactionAsync().ConfigureAwait(false))
{
await m_connection.ExecuteAsync("insert into transactions_test values(1), (2)", transaction: trans).ConfigureAwait(false);
await trans.RollbackAsync().ConfigureAwait(false);
}
var results = await m_connection.QueryAsync<int>(@"select value from transactions_test order by value;").ConfigureAwait(false);
Assert.Equal(new int[0], results);
}
#endif
[Fact]
public void NoCommit()
{
m_connection.Execute("delete from transactions_test");
using (var trans = m_connection.BeginTransaction())
{
m_connection.Execute("insert into transactions_test values(1), (2)", transaction: trans);
}
var results = m_connection.Query<int>(@"select value from transactions_test order by value;");
Assert.Equal(new int[0], results);
}
readonly TransactionFixture m_database;
readonly MySqlConnection m_connection;
}
}
|
namespace AzureAI.CallCenterTalksAnalysis.Infrastructure.Utils
{
public class ErrorMessage
{
public string Title { get; }
public string Message { get; }
public ErrorMessage(string title, string message)
{
Title = title;
Message = message;
}
}
}
|
using System;
using System.Diagnostics;
public class Timing
{
//TimeSpan startingTime;
//TimeSpan duration;
static Stopwatch timer = new Stopwatch();
public Timing()
{
//startingTime = new TimeSpan(0);
//duration = new TimeSpan(0);
}
public void stopTime()
{
timer.Stop(); //Stop timer
//duration = Process.GetCurrentProcess().UserProcessorTime.CurrentThread.Subtract(startingTime);
//duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startingTime);
}
public void startTime()
{
GC.Collect();
GC.WaitForPendingFinalizers();
timer.Reset(); //reset timer to 0
timer.Start(); //start timer
//startingTime = Process.GetCurrentProcess().CurrentThread.UserProcessorTime;
//startingTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
}
public TimeSpan Result()
{
//get time elapsed in seconds
return TimeSpan.FromSeconds(timer.Elapsed.TotalSeconds);
//return duration;
}
}
class sortArray
{
// Perform insertion sort on arr[]
// Overloaded insertion sort to use with quick sort
public static void InsertionSort(int[] arr, int low, int n)
{
// Start from second element (element at index 0
// is already sorted)
for (int i = low + 1; i <= n; i++)
{
int val = arr[i];
int j = i;
// Find the index j within the sorted subset arr[0..i-1]
// where element arr[i] belongs
while (j > low && arr[j - 1] > val)
{
arr[j] = arr[j - 1];
j--;
}
// Note that subarray arr[j..i-1] is shifted to
// the right by one position i.e. arr[j+1..i]
arr[j] = val;
//Console.WriteLine("Using Insertion Sort pass {0}: ", i);
//chapter1.DisplayNums(arr);
}
}
// Partition data around a pivot for the quicksort algorithm
// to recurse around
public static int Partition (int[] a, int low, int high)
{
// Pick the rightmost element as pivot from the array
int pivot = a[high];
// elements less than pivot will be pushed to the left of pIndex
// elements more than pivot will be pushed to the right of pIndex
// equal elements can go either way
int pIndex = low;
// each time we find an element less than or equal to pivot,
// pIndex is incremented and that element would be placed
// before the pivot.
for (int i = low; i < high; i++)
{
if (a[i] <= pivot)
{
int temp = a[i];
a[i] = a[pIndex];
a[pIndex] = temp;
pIndex++;
}
}
// swap pIndex with Pivot
int temp2 = a[high];
a[high] = a[pIndex];
a[pIndex] = temp2;
// return pIndex (index of pivot element)
return pIndex;
}
// Add insertion sort for subproblems of 10 or smaller
public static void optimizedQuickSort(int[] A, int low, int high)
{
const int THRESHOLD = 10;
while (low < high)
{
// do insertion sort if 10 or smaller
if(high - low <= THRESHOLD)
{
InsertionSort(A, low, high);
break;
}
else
{
int pivot = Partition(A, low, high);
// tail call optimizations - recurse on smaller sub-array
if (pivot - low < high - pivot) {
optimizedQuickSort(A, low, pivot - 1);
low = pivot + 1;
} else {
optimizedQuickSort(A, pivot + 1, high);
high = pivot - 1;
}
}
}
}
}
class chapter4
{
// Class variables for generating random numbers
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
static void Main()
{
int[] nums1 = new int[10000];
int searchNumber;
bool isInputNumeric;
// Load Array with random integers
loadArray(nums1);
Timing tObj = new Timing();
Timing tObj2 = new Timing();
DisplayArray(nums1);
//Console.WriteLine(nums1[nums1.Length - 1]);
while(true)
{
Console.WriteLine("Please enter a number to search for.");
isInputNumeric = Int32.TryParse(Console.ReadLine(), out searchNumber);
if(isInputNumeric == true)
break;
else
Console.WriteLine("You entered non numeric character(s). Please enter a numeric character to continue.");
}
tObj.startTime();
if(SeqSearch(nums1, searchNumber) == true)
Console.WriteLine("Sequential Search found {0} in the array!", searchNumber);
else
Console.WriteLine("Sequential Search did not find {0} in the array.", searchNumber);
tObj.stopTime();
string seqSearchTime = tObj.Result().ToString();
Console.WriteLine("Time of Sequential Search (.NET): " + seqSearchTime);
// Sort array with optimized quick sort before performing binary search
sortArray.optimizedQuickSort(nums1, 0, nums1.Length - 1);
tObj2.startTime();
if(binSearch(nums1, searchNumber) == -1)
Console.WriteLine("Binary Search did not find {0} in the array.", searchNumber);
else
Console.WriteLine("Binary Search found {0} in the array at position {1}!", searchNumber, binSearch(nums1, searchNumber));
tObj2.stopTime();
string binSearchTime = tObj2.Result().ToString();
Console.WriteLine("Time of Binary Search (.NET): " + binSearchTime);
Console.ReadKey();
//Console.WriteLine("IsHighResolution = " + Stopwatch.IsHighResolution);
}
public static void BuildArray(int[] arr)
{
for(int i = 0; i < arr.Length; i++)
arr[i] = i;
}
public static void DisplayArray(int[] arr)
{
for(int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
Console.WriteLine("");
}
// This method loads up the array with random integers
public static void loadArray(int[] arr)
{
int Min = 0;
int Max = arr.Length * 10;
for (int i = 0; i < arr.Length; i++)
{
int next = 0;
while (true)
{
next = RandomNumber(Min, Max);
if (!Contains(arr, next))
break;
}
arr[i] = next;
}
}
//Function to get a random number
public static int RandomNumber(int min, int max)
{
lock(syncLock)
{ // synchronize
return random.Next(min, max);
}
}
// Using this to get unique numbers into the array
public static bool Contains(int[] array, int val)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == val)
return true;
}
return false;
}
public static bool SeqSearch(int[] arr, int sValue)
{
for (int i = 0; i < arr.Length; i++)
if (arr[i] == sValue)
return true;
return false;
}
public static int FindMin(int[] arr)
{
int min = arr[0];
for(int i = 1; i < arr.Length - 1; i++)
if (arr[i] < min)
min = arr[i];
return min;
}
public static int FindMax(int[] arr)
{
int max = arr[0];
for(int i = 1; i < arr.Length - 1; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
public static int SeqSearchSelfOrdering(int[] arr, int sValue)
{
for(int i = 0; i < arr.Length - 1; i++)
if (arr[i] == sValue && i > (arr.Length * 0.2))
{
swap(ref arr[i], ref arr[i - 1]);
return i;
} else
if (arr[i] == sValue)
return i;
return -1;
}
public static int binSearch(int[] arr, int sValue)
{
int upperBound, lowerBound, mid;
upperBound = arr.Length - 1;
lowerBound = 0;
while(lowerBound <= upperBound)
{
mid = (int)(upperBound + lowerBound) / 2;
if (arr[mid] == sValue)
return mid;
else
if (sValue < arr[mid])
upperBound = mid - 1;
else
lowerBound = mid + 1;
}
return -1;
}
public int RbinSearch(int[] arr, int sValue, int lower, int upper)
{
if (lower > upper)
return -1;
else {
int mid;
mid = (int)(upper + lower) / 2;
if (sValue < arr[mid])
return RbinSearch(arr, sValue, lower, mid - 1);
else if (sValue == arr[mid])
return mid;
else
return RbinSearch(arr, sValue, mid + 1, upper);
}
}
public static void swap(ref int item1, ref int item2)
{
int temp = item1;
item1 = item2;
item2 = temp;
}
}
|
namespace WinAppDriver
{
using System;
using System.Collections.Generic;
using System.Windows.Automation;
internal class Session : ISession
{
private static ILogger logger = Logger.GetLogger("WinAppDriver");
private List<AutomationElement> uiElements;
public Session(string id, IApplication application, Capabilities capabilities)
{
this.ID = id;
this.Application = application;
this.Capabilities = capabilities;
this.FocusOnCurrentWindow = true;
this.ImplicitWaitMillis = 0;
this.uiElements = new List<AutomationElement>();
}
public string ID { get; private set; }
public IApplication Application { get; private set; }
public Capabilities Capabilities { get; private set; }
public bool FocusOnCurrentWindow { get; set; }
public int ImplicitWaitMillis { get; set; }
public int AddUIElement(AutomationElement element)
{
int id = this.uiElements.Count;
this.uiElements.Add(element);
logger.Debug("UI element ({0})) added.", id);
return id;
}
public AutomationElement GetUIElement(int id)
{
return this.uiElements[id];
}
}
} |
using Compent.LinkPreview.HttpClient;
using System.Threading.Tasks;
using System.Web.Http;
using UBaseline.Core.Controllers;
using Uintra.Features.LinkPreview.Configurations;
using Uintra.Features.LinkPreview.Mappers;
using Uintra.Features.LinkPreview.Models;
using Uintra.Features.LinkPreview.Providers.Contracts;
using Uintra.Features.LinkPreview.Sql;
using Uintra.Features.OpenGraph.Models;
using Uintra.Features.OpenGraph.Services.Contracts;
using Uintra.Infrastructure.Extensions;
using Uintra.Persistence.Sql;
namespace Uintra.Features.LinkPreview.Controllers
{
public class LinkPreviewController : UBaselineApiController
{
private readonly ILinkPreviewClient _linkPreviewClient;
private readonly ISqlRepository<int, LinkPreviewEntity> _previewRepository;
private readonly ILinkPreviewConfigProvider _configProvider;
private readonly IOpenGraphService _openGraphService;
private readonly LinkPreviewModelMapper _linkPreviewModelMapper;
public LinkPreviewController(
ILinkPreviewClient linkPreviewClient,
ISqlRepository<int, LinkPreviewEntity> previewRepository,
LinkPreviewModelMapper linkPreviewModelMapper,
ILinkPreviewConfigProvider configProvider,
IOpenGraphService openGraphService)
{
_linkPreviewClient = linkPreviewClient;
_previewRepository = previewRepository;
_linkPreviewModelMapper = linkPreviewModelMapper;
_configProvider = configProvider;
_openGraphService = openGraphService;
}
[HttpGet]
public virtual async Task<LinkPreviewModel> Preview(string url)
{
var openGraphObject = _openGraphService.GetOpenGraphObject(url);
if (openGraphObject != null)
{
var localRequestEntity = Map(openGraphObject);
_previewRepository.Add(localRequestEntity);
return _linkPreviewModelMapper.MapPreview(localRequestEntity);
}
var result = await _linkPreviewClient.GetLinkPreview(url);
if (!result.IsSuccess) return null;
var entity = Map(result.Preview, url);
_previewRepository.Add(entity);
var linkPreview = _linkPreviewModelMapper.MapPreview(entity);
return linkPreview;
}
protected virtual LinkPreviewEntity Map(OpenGraphObject graph) =>
new LinkPreviewEntity
{
OgDescription = graph.Description,
Title = graph.Title,
Uri = graph.Url,
MediaId = graph.MediaId
};
protected virtual LinkPreviewEntity Map(Compent.LinkPreview.HttpClient.LinkPreview model, string url)
{
var entity = model.Map<LinkPreviewEntity>();
entity.Uri = url;
return entity;
}
[HttpGet]
public virtual LinkDetectionConfig Config() =>
_configProvider.Config;
}
} |
namespace Assets.Scripts.Models.MiningObjects.Rocks
{
public abstract class Rock : MiningObject
{
protected Rock()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Lottery.Entities;
using Lottery.Repository.Entities;
namespace Lottery.Service.AutoMapper
{
public class RecordProfile : Profile
{
public RecordProfile()
{
CreateMap<LotteryRecord, BigLotteryRecord>();
CreateMap<LotteryRecord, BigLotteryRecordSequence>();
CreateMap<LotteryRecord, PowerLotteryRecord>();
CreateMap<LotteryRecord, PowerLotteryRecordSequence>();
CreateMap<LotteryRecord, FiveThreeNineLotteryRecord>();
CreateMap<LotteryRecord, SimulateLotteryRecord>();
CreateMap<BigLotteryRecord, LotteryRecord>().ForMember(dest => dest.MaxNumber,
opt => opt.MapFrom(src => 49)).ForMember(dest => dest.MaxSpecialNumber,
opt => opt.MapFrom(src => 49)).ForMember(dest => dest.OpenDayOfWeek,
opt => opt.MapFrom(src => DayOfWeek.Tuesday));
CreateMap<BigLotteryRecordSequence, LotteryRecord>().ForMember(dest => dest.MaxNumber,
opt => opt.MapFrom(src => 49)).ForMember(dest => dest.MaxSpecialNumber,
opt => opt.MapFrom(src => 49)).ForMember(dest => dest.OpenDayOfWeek,
opt => opt.MapFrom(src => DayOfWeek.Tuesday));
CreateMap<PowerLotteryRecord, LotteryRecord>().ForMember(dest => dest.MaxNumber,
opt => opt.MapFrom(src => 38)).ForMember(dest => dest.MaxSpecialNumber,
opt => opt.MapFrom(src => 8)).ForMember(dest => dest.OpenDayOfWeek,
opt => opt.MapFrom(src => DayOfWeek.Monday));
CreateMap<FiveThreeNineLotteryRecord, LotteryRecord>().ForMember(dest => dest.MaxNumber,
opt => opt.MapFrom(src => 39)).ForMember(dest => dest.MaxSpecialNumber,
opt => opt.MapFrom(src => 0)).ForMember(dest => dest.OpenDayOfWeek,
opt => opt.MapFrom(src => DayOfWeek.Monday));
CreateMap<PowerLotteryRecordSequence, LotteryRecord>().ForMember(dest => dest.MaxNumber,
opt => opt.MapFrom(src => 49)).ForMember(dest => dest.MaxSpecialNumber,
opt => opt.MapFrom(src => 8)).ForMember(dest => dest.OpenDayOfWeek,
opt => opt.MapFrom(src => DayOfWeek.Monday));
CreateMap<SimulateLotteryRecord, LotteryRecord>().ForMember(dest => dest.MaxNumber,
opt => opt.MapFrom(src => 49)).ForMember(dest => dest.MaxSpecialNumber,
opt => opt.MapFrom(src => 49)).ForMember(dest => dest.OpenDayOfWeek,
opt => opt.MapFrom(src => DayOfWeek.Tuesday));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WeatherService
{
public struct ImmediateWeather
{
public decimal temp;
public decimal windSpeed;
public string windDir;
public string clouds;
public string city;
public string state;
public string country;
}
}
|
using System;
namespace Tomelt.Commands {
[AttributeUsage(AttributeTargets.Property)]
public class TomeltSwitchAttribute : Attribute {
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace WebApplication1
{
/// <summary>
/// PhoneBind 的摘要说明
/// </summary>
public class PhoneBind : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
RetureCode newRetureCode = new RetureCode();
Stream sm = context.Request.InputStream;
StreamReader inputData = new StreamReader(sm);
string DataString = inputData.ReadToEnd();
try
{
BindPhoneNum newPhoneLoginInfo = LitJson.JsonMapper.ToObject<BindPhoneNum>(DataString);
CodeData _CodeData = PhoneCode.GPhoneCode.CheckCode(newPhoneLoginInfo.CountryCode,
newPhoneLoginInfo.PhoneNum, newPhoneLoginInfo.PhoneCode);
if (_CodeData == null)
{
newRetureCode.code = 4;
newRetureCode.msg = "无效验证码";
PhoneCodeLogin.SendStringToClient(context, LitJson.JsonMapper.ToJson(newRetureCode));
return;
}
string Passw = CommonTools.CreatePassWord(12);
if (BindAccount(newPhoneLoginInfo.AccountId,
_CodeData.PhoneNum, CommonTools.GetMD5Hash(Passw), newPhoneLoginInfo.Mac, newRetureCode))
{
newRetureCode.code = 0;
newRetureCode.msg = Passw;
AppleInapp.AddScoreByBinding(300, newPhoneLoginInfo.AccountId);
JsonEMail newJsonEMail = new JsonEMail();
newJsonEMail.dwUserID = newPhoneLoginInfo.AccountId;
newJsonEMail.nStatus = 0;
newJsonEMail.szTitle = "绑定成功";
newJsonEMail.szMessage = "绑定成功手机号,赠送3.00";
newJsonEMail.szSender = "系统";
newJsonEMail.nType = 0;
newJsonEMail.nStatus = 0;
EmailAdd.AddEmail(newJsonEMail);
}
}
catch(Exception exp)
{
newRetureCode.code = 100;
newRetureCode.msg = DataString+"--"+exp.Message.ToString() + "-" + exp.StackTrace;
}
PhoneCodeLogin.SendStringToClient(context, LitJson.JsonMapper.ToJson(newRetureCode));
}
public static bool HaveBind(string PhoneName, RetureCode newRetureCode)
{
string MyConn = System.Configuration.ConfigurationManager.AppSettings["DBAccounts"];
// string MyConn = "Data Source=.; Initial Catalog=RYAccountsDB; User ID=sa_games; Password=sa_gamesluatest; Pooling=true";
SqlConnection MyConnection = new SqlConnection(MyConn);
try
{
MyConnection.Open();
{
string selStr = "select Accounts from AccountsInfo where Accounts='" + PhoneName + "'";
SqlCommand MyCommand = new SqlCommand(selStr, MyConnection);
SqlDataReader _Reader = MyCommand.ExecuteReader();
if (_Reader.HasRows)
{
_Reader.Close();
return true;
}
}
return false;
}
catch (Exception ex)
{
newRetureCode.code = 5;
newRetureCode.msg = ex.Message.ToString();
Console.WriteLine("{0} Exception caught.", ex);
return true;
}
finally
{
if (MyConnection != null)
MyConnection.Close();
}
}
public static bool BindAccount(int AccountId, string PhoneName, string Password, string Mac, RetureCode newRetureCode)
{
string MyConn = System.Configuration.ConfigurationManager.AppSettings["DBAccounts"];
// string MyConn = "Data Source=.; Initial Catalog=RYAccountsDB; User ID=sa_games; Password=sa_gamesluatest; Pooling=true";
SqlConnection MyConnection = new SqlConnection(MyConn);
try
{
MyConnection.Open();
// {
// string selStr = "select Accounts from AccountsInfo where Accounts='" + PhoneName + "'";
// SqlCommand MyCommand = new SqlCommand(selStr, MyConnection);
// SqlDataReader _Reader = MyCommand.ExecuteReader();
// if (_Reader.HasRows)
// {
// _Reader.Close();
// return false;
// }
// }
{
string updateSql = " update AccountsInfo set LogonPass='" + Password + "',";
updateSql += "Accounts='" + PhoneName + "'";
updateSql += " where UserID=" + AccountId + " and Accounts<> '" + PhoneName + "'";
SqlCommand UpdateCommand = new SqlCommand(updateSql, MyConnection);
return UpdateCommand.ExecuteNonQuery() > 0;
}
}
catch (Exception ex)
{
newRetureCode.code = 5;
newRetureCode.msg = ex.Message.ToString();
Console.WriteLine("{0} Exception caught.", ex);
}
finally
{
if (MyConnection != null)
MyConnection.Close();
}
return false;
}
public bool IsReusable
{
get
{
return false;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
namespace FallstudieSem5.Models
{
[Table("Person")] // created Table with the Name Person
public class Person
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] // used to set PersonId as PrimaryKey in the Database
public long PersonId { get; set; }
[Required(ErrorMessage = "FirstName is Required")]
[StringLength(100)]
public string FirstName { get; set; }
[Required(ErrorMessage = "LastName is Required")]
[StringLength(150)]
public string LastName { get; set; }
[Required(ErrorMessage = "E-Mail is Required")]
[EmailAddress]
public string Email { get; set; }
[JsonIgnore]
public ICollection<Staff> Staffs { get; set; } // used to extend functionality to add, remove and update elements in the list
[JsonIgnore]
public ICollection<PropertyOwner> PropertyOwners { get; set; }
[JsonIgnore]
public ICollection<ObjectOwner> ObjectOwners { get; set; }
[Required(ErrorMessage = "Title is Required")]
public Title Title { get; set; }
public Object Object { get; set; }
public Address Address { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace checkMusic
{
class getProperty
{
public static string ApplicationPath = Directory.GetCurrentDirectory().ToString();
public static string getLeavePath(){
// MessageBox.Show(ConfigurationManager.AppSettings["LeavePath"]);
return ConfigurationManager.AppSettings["LeavePath"] ;
}
public static string getRecordPath()
{
return ConfigurationManager.AppSettings["RecordPath"] ;
}
public static void setLeavePath(string path)
{
// MessageBox.Show(s);
UpdateAppConfig ua = new UpdateAppConfig();
ua.updateAppConfig("LeavePath", path);
}
public static void setRecordPath(string path)
{
// ConfigurationManager.AppSettings.Remove("RecordPath");
// ConfigurationManager.AppSettings.Add("RecordPath", path);
// ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Save(ConfigurationSaveMode.Modified);
// ConfigurationManager.RefreshSection("appSettings");
UpdateAppConfig ua = new UpdateAppConfig();
ua.updateAppConfig("RecordPath", path);
}
}
}
|
using Boxofon.Web.MailCommands;
using TinyMessenger;
namespace Boxofon.Web.Messages
{
public class MailCommand<TMailCommand> : ITinyMessage where TMailCommand : class, IMailCommand
{
public object Sender
{
get { return null; }
}
public TMailCommand Command { get; set; }
public MailCommand()
{
}
public MailCommand(TMailCommand command)
{
Command = command;
}
}
} |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace marlinX
{
static class Load
{
private static readonly HttpClient client = new HttpClient();
public static async Task<Dictionary<string, int>> LoadArticlesAsync(DateTime StartDate, DateTime EndDate,string source)
{
List<Task> tasks = new List<Task>();
for (DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
tasks.Add(CallApi(date,source).ContinueWith(result=> SaveToDb(result.Result)));
}
await Task.WhenAll(tasks);
return Db.getFromDatabase();
}
private static async Task<string> CallApi(DateTime date,string source)
{
try
{
string responseBody = await client.GetStringAsync($"http://newsapi.org/v2/everything?language=en&pageSize=100&sortBy=published At&sources={source}&from={date:YYYY-MM-DD}&to={date:YYYY-MM-DD}&apiKey=4ef9ec7a8516412095cb7fad0d40f699");
return responseBody;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
return String.Empty;
}
}
private static void SaveToDb(string responseBody)
{
ResponseModel response = JsonConvert.DeserializeObject<ResponseModel>(responseBody);
//Convert the string into an array of words
IEnumerable<string> words = response.articles.SelectMany(x =>
(x.title + " " + x.description).Split(new[] { '.', '?', '!', ' ', ';', ':', ',', '-', '\'' },
StringSplitOptions.RemoveEmptyEntries));
Db.SaveToDatabase(words);
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace DFC.ServiceTaxonomy.ContentApproval.Models.Enums
{
public enum ReviewType
{
[Display(Name="None", Order = 0)]
None,
[Display(Name="Content Design", Order = 1)]
ContentDesign,
[Display(Name="Stakeholder", Order = 2)]
Stakeholder,
[Display(Name="SME", Order = 3)]
SME,
[Display(Name="UX", Order = 4)]
UX
}
}
|
using UnityEngine;
using UnityEngine.UI;
using SimpleJSON;
using System.Collections;
using System.Collections.Generic;
public class Game1 : MonoBehaviour {
public int MonsterLevel1,MonsterEXP1,MonsterGrade1,MonsterLevel2,MonsterEXP2,MonsterGrade2,MonsterLevel3,MonsterEXP3,MonsterGrade3;
public float monstercurrentexp1,tempmonsterexp1,monstercurrentexp2,tempmonsterexp2,monstercurrentexp3,tempmonsterexp3;
public float Targetnextlevel1, Targetnextlevel2, Targetnextlevel3;
public string playerhantuid1,playerhantuid2,playerhantuid3;
public Image[] Rewards;
public Image[] DropRewards;
public AudioClip[] ending;
public AudioSource Audioplay;
bool data_belum_ada = true;
bool panggil_url = false;
bool repeat = true;
bool Ab = false;
bool Bb = false;
public GameObject waiting,CameraEnd,CameraEndA,EndOptionButton,ClaimUI;
public TextMesh damageA, damageB;
public float damage;
public bool levelingmate;
public WWWForm formkirimreward;
public GameObject[] urutan1;
public GameObject[] urutan2;
public GameObject[] urutan3;
public GameObject Aobject, Bobject;
public GameObject canvas1,canvas2,canvas3,canvas4,canvas5,canvas6;
public GameObject Monster1GO, Monster2GO, Monster3GO;
public Transform m1, m2, m3;
public GameObject effect;
public string[] suit1;
public string[] suit2;
public string[] suit3;
public float[] health1;
public float[] health2;
public float[] health3;
public GameObject[] healthBar1;
public GameObject[] healthBar2;
public GameObject[] healthBar3;
public GameObject scrollBar,vs,speedOption;
public string[] equipmentreward;
public string[] itemsreward;
public Sprite Charge;
public Sprite Block;
public Sprite Focus;
public Image icon1;
public Image icon2;
public Image icon3;
float timer = 10f;
public bool timeUps = false;
int nilai;
public GameObject plihan1;
public GameObject plihan2;
public GameObject plihan3;
public GameObject[] pilihanInputSuit;
private List<string> alpha = new List<string>{"0","1","2"};
public GameObject getReady;
public bool getReadyStatus = false;
public Sprite aIcon;
public Sprite bIcon;
public AudioSource hitYa;
// int pos1_car1_int = 0;
// int pos1_car2_int = 0;
// int pos1_car3_int = 0;
//
// int pos2_car1_int = 0;
// int pos2_car2_int = 0;
// int pos2_car3_int = 0;
public GameObject healthA1,healthA2,healthA3,healthB1,healthB2,healthB3,firstTimerGame,CB;
public Text User1, debug,ClaimText,EXPValueText;
public Text User2;
GameObject model1_1;
GameObject model2_1;
GameObject model1_2;
GameObject model2_2;
GameObject model1_3;
GameObject model2_3;
public ParticleSystem A;
public ParticleSystem B;
public ParticleSystem Charge_A;
public ParticleSystem Charge_B;
public ParticleSystem Seri_A;
public ParticleSystem Seri_Adef;
public ParticleSystem Seri_B;
public ParticleSystem Seri_Bdef;
public GameObject Nyala;
bool presentDone;
[Header("Diperlukan Untuk SELAIN JOUSTING")]
public GameObject cameraA;
public GameObject cameraB;
public GameObject hospital, school, warehouse,oldhouse,bridge,graveyard;
//Tambah New Variabel untuk JOUSTING
[Header("Diperlukan Untuk JOUSTING")]
public GameObject envi;
public GameObject CameraAR;
public GameObject CameraTarget;
public GameObject hospitalAR;
private bool ApakahCameraA = false;
public Text dg;
void Awake(){
SetReward();
//PlayerPrefs.SetInt ("pos",2);
}
void Start () {
CB.SetActive(false);
#if UNITY_EDITOR
CB.SetActive(true);
#endif
Debug.Log (PlayerPrefs.GetString ("PLAY_TUTORIAL"));
//PlayerPrefs.SetString (Link.SEARCH_BATTLE, "JOUSTING");
if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") {
firstTimerGame.gameObject.SetActive (true);
Time.timeScale = 0;
} else {
firstTimerGame.gameObject.SetActive (false);}
formkirimreward= new WWWForm ();
PlayerPrefs.DeleteKey ("win");
presentDone = false;
//debug.text = PlayerPrefs.GetInt ("pos").ToString ();
EndOptionButton.SetActive (false);
Debug.Log (PlayerPrefs.GetString (Link.POS_1_CHAR_1_ATTACK));
Debug.Log (PlayerPrefs.GetInt ("pos"));
damageA.gameObject.SetActive (false);
damageB.gameObject.SetActive (false);
PlayerPrefs.SetInt ("Jumlah",0);
if (PlayerPrefs.GetString (Link.JENIS) == "SINGLE") {
Audioplay.clip = ending [1];
Audioplay.Play ();
monsterInfo ();
EndOptionButton.transform.Find ("Replay").gameObject.SetActive (true);
EndOptionButton.transform.Find ("Maps").gameObject.SetActive (true);
EndOptionButton.transform.Find ("Arena").gameObject.SetActive (false);
speedOption.SetActive (true);
} else {
Audioplay.clip = ending [0];
Audioplay.Play ();
EndOptionButton.transform.Find ("Arena").gameObject.SetActive (true);
EndOptionButton.transform.Find ("Replay").gameObject.SetActive (false);
EndOptionButton.transform.Find ("Maps").gameObject.SetActive (false);
speedOption.SetActive (false);
// perlu di cek
// perlu di cek
// perlu di cek
//urutan1[1].transform.Find("Canvas2").gameObject.SetActive(false);
//urutan2[1].transform.Find("Canvas2").gameObject.SetActive(false);
//urutan3[1].transform.Find("Canvas2").gameObject.SetActive(false);
}
//TAMBAHAN DISINI
if (PlayerPrefs.GetString (Link.SEARCH_BATTLE) == "SINGLE" && PlayerPrefs.GetString (Link.JENIS) == "SINGLE") {
PlayerPrefs.SetString (Link.USER_1, "Musuh");
PlayerPrefs.SetString (Link.USER_2, PlayerPrefs.GetString (Link.FULL_NAME));
} else {
//BIARKAN NAMA DARI MASING MASING PEMAIN.
}
if (PlayerPrefs.GetString (Link.SEARCH_BATTLE) == "JOUSTING") {
this.gameObject.transform.SetParent (CameraTarget.transform);
speedOption.SetActive (false);
EndOptionButton.transform.Find ("Arena").gameObject.SetActive (true);
EndOptionButton.transform.Find ("Replay").gameObject.SetActive (false);
EndOptionButton.transform.Find ("Maps").gameObject.SetActive (false);
CameraAR.SetActive (true);
//hospitalAR.SetActive (true);
envi.transform.SetParent (CameraTarget.transform);
}
else {
if (PlayerPrefs.GetString (Link.LOKASI) == "warehouse") {
warehouse.SetActive (true);
} else if (PlayerPrefs.GetString (Link.LOKASI) == "school") {
school.SetActive (true);
} else if (PlayerPrefs.GetString (Link.LOKASI) == "hospital") {
hospital.SetActive (true);
} else if (PlayerPrefs.GetString (Link.LOKASI) == "bridge") {
bridge.SetActive (true);
}else if (PlayerPrefs.GetString (Link.LOKASI) == "graveyard") {
graveyard.SetActive (true);
}
else {
oldhouse.SetActive (true);
}
if (PlayerPrefs.GetInt ("pos") == 1) {
cameraA.SetActive (true);
ApakahCameraA = true;
} else {
Debug.Log ("single player");
cameraB.SetActive (true);
ApakahCameraA = false;
}
}
Destroy (GameObject.Find("SoundBG"));
urutan1 = new GameObject[2];
urutan2 = new GameObject[2];
urutan3 = new GameObject[2];
urutan1 [0] = GameObject.Find ("Hantu1A");
urutan1 [1] = GameObject.Find ("Hantu1B");
urutan2 [0] = GameObject.Find ("Hantu2A");
urutan2 [1] = GameObject.Find ("Hantu2B");
urutan3 [0] = GameObject.Find ("Hantu3A");
urutan3 [1] = GameObject.Find ("Hantu3B");
Debug.Log ("Info Hantu POS 1 : ");
Debug.Log ("GRADE : " + PlayerPrefs.GetString(Link.POS_1_CHAR_1_GRADE));
Debug.Log ("LEVEL : " + PlayerPrefs.GetString(Link.POS_1_CHAR_1_LEVEL));
Debug.Log ("ATTACK : " + PlayerPrefs.GetString(Link.POS_1_CHAR_1_ATTACK));
Debug.Log ("DEFENSE : " + PlayerPrefs.GetString(Link.POS_1_CHAR_1_DEFENSE));
Debug.Log ("HP : " + PlayerPrefs.GetString(Link.POS_1_CHAR_1_HP));
Debug.Log ("Info Hantu POS 2 : ");
Debug.Log ("GRADE : " + PlayerPrefs.GetString(Link.POS_2_CHAR_1_GRADE));
Debug.Log ("LEVEL : " + PlayerPrefs.GetString(Link.POS_2_CHAR_1_LEVEL));
Debug.Log ("ATTACK : " + PlayerPrefs.GetString(Link.POS_2_CHAR_1_ATTACK));
Debug.Log ("DEFENSE : " + PlayerPrefs.GetString(Link.POS_2_CHAR_1_DEFENSE));
Debug.Log ("HP : " + PlayerPrefs.GetString(Link.POS_2_CHAR_1_HP));
model1_1 = Instantiate (Resources.Load ("PrefabsChar/" + PlayerPrefs.GetString (Link.POS_1_CHAR_1_FILE)) as GameObject, new Vector3(0f,0f,0f), Quaternion.identity);
model1_1.transform.SetParent (urutan1[0].transform);
model1_1.transform.localPosition = urutan1 [0].transform.Find ("COPY_POSITION").transform.localPosition;
model1_1.transform.localScale = urutan1 [0].transform.Find ("COPY_POSITION").transform.localScale;
model1_1.transform.localEulerAngles = urutan1 [0].transform.Find ("COPY_POSITION").transform.localEulerAngles;
model1_1.name = "Genderuwo_Fire";
model1_1.transform.SetParent (urutan1 [0].transform.Find ("COPY_POSITION"));
//LANGSUNG SY MASUKKAN ATT,HP,DEFENSE
urutan1 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().damage = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_1_ATTACK));
urutan1 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().defend = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_1_DEFENSE));
urutan1 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().maxhealth = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_1_HP));
urutan1 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().currenthealth = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_1_HP));
//SERTA DATA LAIN, MUNGKIN AKAN DIPERLUKAN NANTI
//PlayerPrefs.GetString(Link.POS_1_CHAR_1_GRADE);
//PlayerPrefs.GetString(Link.POS_1_CHAR_1_LEVEL);
model2_1 = Instantiate (Resources.Load ("PrefabsChar/" + PlayerPrefs.GetString (Link.POS_2_CHAR_1_FILE)) as GameObject, new Vector3(0f,0f,0f), Quaternion.identity);
model2_1.transform.SetParent (urutan1[1].transform);
model2_1.transform.localPosition = urutan1 [1].transform.Find ("COPY_POSITION").transform.localPosition;
model2_1.transform.localScale = urutan1 [1].transform.Find ("COPY_POSITION").transform.localScale;
model2_1.transform.localEulerAngles = urutan1 [1].transform.Find ("COPY_POSITION").transform.localEulerAngles;
model2_1.name = "Genderuwo_Fire";
model2_1.transform.SetParent (urutan1 [1].transform.Find ("COPY_POSITION"));
//LANGSUNG SY MASUKKAN ATT,HP,DEFENSE
urutan1 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().damage = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_1_ATTACK));
urutan1 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().defend = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_1_DEFENSE));
urutan1 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().maxhealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_1_HP));
urutan1 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().currenthealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_1_HP));
//if (PlayerPrefs.GetString(Link.JENIS) == "SINGLE")
//{
// urutan1[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().damage = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_1_ATTACK));
// urutan1[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().defend = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_1_DEFENSE));
// urutan1[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().maxhealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_1_HP));
// urutan1[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().currenthealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_1_HP));
//}
//SERTA DATA LAIN, MUNGKIN AKAN DIPERLUKAN NANTI
//PlayerPrefs.GetString(Link.POS_2_CHAR_1_GRADE);
//PlayerPrefs.GetString(Link.POS_2_CHAR_1_LEVEL);
model1_2 = Instantiate (Resources.Load ("PrefabsChar/" + PlayerPrefs.GetString (Link.POS_1_CHAR_2_FILE)) as GameObject, new Vector3(0f,0f,0f), Quaternion.identity);
model1_2.transform.SetParent (urutan2[0].transform);
model1_2.transform.localPosition = urutan2 [0].transform.Find ("COPY_POSITION").transform.localPosition;
model1_2.transform.localScale = urutan2 [0].transform.Find ("COPY_POSITION").transform.localScale;
model1_2.transform.localEulerAngles = urutan2 [0].transform.Find ("COPY_POSITION").transform.localEulerAngles;
model1_2.name = "Genderuwo_Fire";
model1_2.transform.SetParent (urutan2 [0].transform.Find ("COPY_POSITION"));
//LANGSUNG SY MASUKKAN ATT,HP,DEFENSE
urutan2 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().damage = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_2_ATTACK));
urutan2 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().defend = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_2_DEFENSE));
urutan2 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().maxhealth = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_2_HP));
urutan2 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().currenthealth = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_2_HP));
//SERTA DATA LAIN, MUNGKIN AKAN DIPERLUKAN NANTI
//PlayerPrefs.GetString(Link.POS_1_CHAR_2_GRADE);
//PlayerPrefs.GetString(Link.POS_1_CHAR_2_LEVEL);
model2_2 = Instantiate (Resources.Load ("PrefabsChar/" + PlayerPrefs.GetString (Link.POS_2_CHAR_2_FILE)) as GameObject, new Vector3(0f,0f,0f), Quaternion.identity);
model2_2.transform.SetParent (urutan2[1].transform);
model2_2.transform.localPosition = urutan2 [1].transform.Find ("COPY_POSITION").transform.localPosition;
model2_2.transform.localScale = urutan2 [1].transform.Find ("COPY_POSITION").transform.localScale;
model2_2.transform.localEulerAngles = urutan2 [1].transform.Find ("COPY_POSITION").transform.localEulerAngles;
model2_2.name = "Genderuwo_Fire";
model2_2.transform.SetParent (urutan2 [1].transform.Find ("COPY_POSITION"));
//LANGSUNG SY MASUKKAN ATT,HP,DEFENSE
urutan2 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().damage = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_ATTACK));
urutan2 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().defend = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_DEFENSE));
urutan2 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().maxhealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_HP));
urutan2 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().currenthealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_HP));
//if (PlayerPrefs.GetString(Link.JENIS) == "SINGLE")
//{
// urutan2[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().damage = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_ATTACK));
// urutan2[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().defend = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_DEFENSE));
// urutan2[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().maxhealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_HP));
// urutan2[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().currenthealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_HP));
//}
//SERTA DATA LAIN, MUNGKIN AKAN DIPERLUKAN NANTI
//PlayerPrefs.GetString(Link.POS_2_CHAR_2_GRADE);
//PlayerPrefs.GetString(Link.POS_2_CHAR_2_LEVEL);
model1_3 = Instantiate (Resources.Load ("PrefabsChar/" + PlayerPrefs.GetString (Link.POS_1_CHAR_3_FILE)) as GameObject, new Vector3(0f,0f,0f), Quaternion.identity);
model1_3.transform.SetParent (urutan3[0].transform);
model1_3.transform.localPosition = urutan3 [0].transform.Find ("COPY_POSITION").transform.localPosition;
model1_3.transform.localScale = urutan3 [0].transform.Find ("COPY_POSITION").transform.localScale;
model1_3.transform.localEulerAngles = urutan3 [0].transform.Find ("COPY_POSITION").transform.localEulerAngles;
model1_3.name = "Genderuwo_Fire";
model1_3.transform.SetParent (urutan3 [0].transform.Find ("COPY_POSITION"));
//LANGSUNG SY MASUKKAN ATT,HP,DEFENSE
urutan3 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().damage = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_3_ATTACK));
urutan3 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().defend = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_3_DEFENSE));
urutan3 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().maxhealth = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_3_HP));
urutan3 [0].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().currenthealth = float.Parse(PlayerPrefs.GetString(Link.POS_1_CHAR_3_HP));
//SERTA DATA LAIN, MUNGKIN AKAN DIPERLUKAN NANTI
//PlayerPrefs.GetString(Link.POS_1_CHAR_3_GRADE);
//PlayerPrefs.GetString(Link.POS_1_CHAR_3_LEVEL);
model2_3 = Instantiate (Resources.Load ("PrefabsChar/" + PlayerPrefs.GetString (Link.POS_2_CHAR_3_FILE)) as GameObject, new Vector3(0f,0f,0f), Quaternion.identity);
model2_3.transform.SetParent (urutan3[1].transform);
model2_3.transform.localPosition = urutan3 [1].transform.Find ("COPY_POSITION").transform.localPosition;
model2_3.transform.localScale = urutan3 [1].transform.Find ("COPY_POSITION").transform.localScale;
model2_3.transform.localEulerAngles = urutan3 [1].transform.Find ("COPY_POSITION").transform.localEulerAngles;
model2_3.name = "Genderuwo_Fire";
model2_3.transform.SetParent (urutan3 [1].transform.Find ("COPY_POSITION"));
//LANGSUNG SY MASUKKAN ATT,HP,DEFENSE
urutan3 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().damage = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_3_ATTACK));
urutan3 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().defend = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_3_DEFENSE));
urutan3 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().maxhealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_3_HP));
urutan3 [1].transform.Find("Canvas").transform.Find ("Image").GetComponent<filled> ().currenthealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_3_HP));
//if (PlayerPrefs.GetString(Link.JENIS) == "SINGLE")
//{
// urutan3[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().damage = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_ATTACK));
// urutan3[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().defend = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_DEFENSE));
// urutan3[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().maxhealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_HP));
// urutan3[1].transform.Find("Canvas2").transform.FindChild("Image").GetComponent<filled>().currenthealth = float.Parse(PlayerPrefs.GetString(Link.POS_2_CHAR_2_HP));
//}
//SERTA DATA LAIN, MUNGKIN AKAN DIPERLUKAN NANTI
//PlayerPrefs.GetString(Link.POS_2_CHAR_3_GRADE);
//PlayerPrefs.GetString(Link.POS_2_CHAR_3_LEVEL);
//ModelAllStatus (false);
//PlayerPrefs.DeleteAll ();
//ganti perbandingan nilai N apabila jumlah monster bertambah
if (PlayerPrefs.GetInt ("pos") == 1) {
User2.text = PlayerPrefs.GetString (Link.USER_1);
User1.text = PlayerPrefs.GetString (Link.USER_2);
icon1.sprite = Resources.Load<Sprite>("icon_char/" + PlayerPrefs.GetString(Link.POS_1_CHAR_1_FILE));
icon2.sprite = Resources.Load<Sprite>("icon_char/" + PlayerPrefs.GetString(Link.POS_1_CHAR_2_FILE));
icon3.sprite = Resources.Load<Sprite>("icon_char/" + PlayerPrefs.GetString(Link.POS_1_CHAR_3_FILE));
} else {
User1.text = PlayerPrefs.GetString (Link.USER_1);
User2.text = PlayerPrefs.GetString (Link.USER_2);
icon1.sprite = Resources.Load<Sprite>("icon_char/" + PlayerPrefs.GetString(Link.POS_2_CHAR_1_FILE));
icon2.sprite = Resources.Load<Sprite>("icon_char/" + PlayerPrefs.GetString(Link.POS_2_CHAR_2_FILE));
icon3.sprite = Resources.Load<Sprite>("icon_char/" + PlayerPrefs.GetString(Link.POS_2_CHAR_3_FILE));
}
urutan1 = new GameObject[2];
urutan2 = new GameObject[2];
urutan3 = new GameObject[2];
healthBar1 = new GameObject[2];
healthBar2 = new GameObject[2];
healthBar3 = new GameObject[2];
suit1 = new string[2];
suit2 = new string[2];
suit3 = new string[2];
health1 = new float[2];
health2 = new float[2];
health3 = new float[2];
health1 [0] = healthA1.GetComponent<filled> ().maxhealth;
health1 [1] = healthB1.GetComponent<filled> ().maxhealth;
health2 [0] = healthA2.GetComponent<filled> ().maxhealth;
health2 [1] = healthB2.GetComponent<filled> ().maxhealth;
health3 [0] = healthA3.GetComponent<filled> ().maxhealth;
health3 [1] = healthB3.GetComponent<filled> ().maxhealth;
//SY TAMBAHIN JIKA SINGLE KE SINI
if (PlayerPrefs.GetString (Link.JENIS) == "SINGLE") {
if (PlayerPrefs.GetString ("PLAY_TUTORIAL") != "TRUE") {
StartCoroutine (randomenemiesmovement ());
} else {
// firstTimerTanding ();
}
}
StartCoroutine (areuReady());
}
public void ModelAllStatus (bool status) {
model1_1.SetActive (status);
model2_1.SetActive (status);
model1_2.SetActive (status);
model2_2.SetActive (status);
model1_3.SetActive (status);
model2_3.SetActive (status);
}
public void gameObject_Scale(){
// model1_1.gameObject.lo
// model2_1.
// model1_2.
// model2_2.
// model1_3.
// model2_3.
}
public void canvasEnd(){
canvas1.SetActive (false);
canvas2.SetActive (false);
canvas3.SetActive (false);
canvas4.SetActive (false);
canvas5.SetActive (false);
canvas6.SetActive (false);
}
public void monsterInfo(){
playerhantuid1 = PlayerPrefs.GetString (Link.CHAR_1_ID);
playerhantuid2 = PlayerPrefs.GetString (Link.CHAR_2_ID);
playerhantuid3 = PlayerPrefs.GetString (Link.CHAR_3_ID);
MonsterLevel1 = int.Parse(PlayerPrefs.GetString (Link.CHAR_1_LEVEL));
MonsterLevel2 = int.Parse(PlayerPrefs.GetString (Link.CHAR_2_LEVEL));
MonsterLevel3 = int.Parse(PlayerPrefs.GetString (Link.CHAR_3_LEVEL));
MonsterGrade1 = int.Parse(PlayerPrefs.GetString (Link.CHAR_1_GRADE));
MonsterGrade2 = int.Parse(PlayerPrefs.GetString (Link.CHAR_2_GRADE));
MonsterGrade3 = int.Parse(PlayerPrefs.GetString (Link.CHAR_3_GRADE));
Monster1GO.transform.Find ("Level").GetComponent<Text> ().text = MonsterLevel1.ToString();
Monster2GO.transform.Find ("Level").GetComponent<Text> ().text = MonsterLevel2.ToString();
Monster3GO.transform.Find ("Level").GetComponent<Text> ().text = MonsterLevel3.ToString();
Monster1GO.transform.Find ("Icon_Char").GetComponent<Image> ().sprite = Resources.Load<Sprite> ("icon_char_Maps/" + PlayerPrefs.GetString (Link.CHAR_1_FILE));
Monster2GO.transform.Find ("Icon_Char").GetComponent<Image> ().sprite = Resources.Load<Sprite> ("icon_char_Maps/" + PlayerPrefs.GetString (Link.CHAR_2_FILE));
Monster3GO.transform.Find ("Icon_Char").GetComponent<Image> ().sprite = Resources.Load<Sprite> ("icon_char_Maps/" + PlayerPrefs.GetString (Link.CHAR_3_FILE));
monstercurrentexp1= float.Parse( PlayerPrefs.GetString (Link.CHAR_1_MONSTEREXP));
Targetnextlevel1= float.Parse(PlayerPrefs.GetString (Link.CHAR_1_TARGETNL));
monstercurrentexp2= float.Parse(PlayerPrefs.GetString (Link.CHAR_2_MONSTEREXP));
Targetnextlevel2= float.Parse(PlayerPrefs.GetString (Link.CHAR_2_TARGETNL));
monstercurrentexp3= float.Parse(PlayerPrefs.GetString (Link.CHAR_3_MONSTEREXP));
Targetnextlevel3= float.Parse(PlayerPrefs.GetString (Link.CHAR_3_TARGETNL));
}
public IEnumerator areuReady () {
yield return new WaitForSeconds (1);
getReady.SetActive (true);
yield return new WaitForSeconds (1f);
getReady.SetActive (false);
Nyala.SetActive (true);
yield return new WaitForSeconds (.2f);
//ModelAllStatus (true);
yield return new WaitForSeconds (1);
model1_1.GetComponent<Animation> ().Play ("select");
model2_1.GetComponent<Animation> ().Play ("select");
model1_2.GetComponent<Animation> ().Play ("select");
model2_2.GetComponent<Animation> ().Play ("select");
model1_3.GetComponent<Animation> ().Play ("select");
model2_3.GetComponent<Animation> ().Play ("select");
model1_1.GetComponent<Animation> ().PlayQueued ("idle");
model2_1.GetComponent<Animation> ().PlayQueued ("idle");
model1_2.GetComponent<Animation> ().PlayQueued ("idle");
model2_2.GetComponent<Animation> ().PlayQueued ("idle");
model1_3.GetComponent<Animation> ().PlayQueued ("idle");
model2_3.GetComponent<Animation> ().PlayQueued ("idle");
pilihanInputSuit [0].SetActive (true);
pilihanInputSuit [1].SetActive (true);
pilihanInputSuit [2].SetActive (true);
yield return new WaitForSeconds (1);
getReadyStatus = true;
}
void suitanimation(){
}
void firstTimerTanding(){
// if (urutan1 [1].gameObject.name != "") {
if (urutan1 [1].gameObject.name == "Hantu1B") {
if (suit1 [1] == "Charge") {
suit1 [0] = "Focus";
// urutan1[0].GetComponent<>
}
if (suit1 [1] == "Focus") {
suit1 [0] = "Block";
}
if (suit1 [1] == "Block") {
suit1 [0] = "Charge";
}
}
if (urutan1 [1].gameObject.name == "Hantu2B") {
if (suit2 [1] == "Charge") {
suit1 [0] = "Focus";
// urutan1[0].GetComponent<>
}
if (suit2 [1] == "Focus") {
suit1 [0] = "Block";
}
if (suit2 [1] == "Block") {
suit1 [0] = "Charge";
}
}
if (urutan1 [1].gameObject.name == "Hantu3B") {
if (suit3 [1] == "Charge") {
suit1 [0] = "Focus";
// urutan1[0].GetComponent<>
}
if (suit3 [1] == "Focus") {
suit1 [0] = "Block";
}
if (suit3 [1] == "Block") {
suit1 [0] = "Charge";
}
}
//kondisi 2
if (urutan2 [1].gameObject.name == "Hantu1B") {
if (suit1 [1] == "Charge") {
suit2 [0] = "Focus";
// urutan1[0].GetComponent<>
}
if (suit1 [1] == "Focus") {
suit2 [0] = "Block";
}
if (suit1 [1] == "Block") {
suit2 [0] = "Charge";
}
}
if (urutan2 [1].gameObject.name == "Hantu2B") {
if (suit2 [1] == "Charge") {
suit2 [0] = "Focus";
// urutan1[0].GetComponent<>
}
if (suit2 [1] == "Focus") {
suit2 [0] = "Block";
}
if (suit2 [1] == "Block") {
suit2 [0] = "Charge";
}
}
if (urutan2 [1].gameObject.name == "Hantu3B") {
if (suit3 [1] == "Charge") {
suit2 [0] = "Focus";
// urutan1[0].GetComponent<>
}
if (suit3 [1] == "Focus") {
suit2 [0] = "Block";
}
if (suit3 [1] == "Block") {
suit2 [0] = "Charge";
}
}
//kondisi 3
if (urutan3 [1].gameObject.name == "Hantu1B") {
if (suit1 [1] == "Charge") {
suit3 [0] = "Focus";
// urutan1[0].GetComponent<>
}
if (suit1 [1] == "Focus") {
suit3 [0] = "Block";
}
if (suit1 [1] == "Block") {
suit3 [0] = "Charge";
}
}
if (urutan3 [1].gameObject.name == "Hantu2B") {
if (suit2 [1] == "Charge") {
suit3 [0] = "Focus";
// urutan1[0].GetComponent<>
}
if (suit2 [1] == "Focus") {
suit3 [0] = "Block";
}
if (suit2 [1] == "Block") {
suit3 [0] = "Charge";
}
}
if (urutan3 [1].gameObject.name == "Hantu3B") {
if (suit3 [1] == "Charge") {
suit3 [0] = "Focus";
// urutan1[0].GetComponent<>
}
if (suit3 [1] == "Focus") {
suit3 [0] = "Block";
}
if (suit3 [1] == "Block") {
suit3 [0] = "Charge";
}
}
//}
}
void Update () {
//Debug.Log (Random.value);
dg.text = PlayerPrefs.GetInt ("pos").ToString ();
//Debug.Log (PlayerPrefs.GetString (Link.JENIS));
//Debug.Log (PlayerPrefs.GetInt ("Jumlah"));
//Debug.Log (panggil_url);
// Debug.Log (timeUps);
if (PlayerPrefs.GetInt ("Jumlah") == 3) {
if (PlayerPrefs.GetString (Link.JENIS) == "SINGLE") {
//INI SAYA TARUH DISINI.
}
timeUps = true;
if (panggil_url == false) {
panggil_url = true;
if (PlayerPrefs.GetString (Link.JENIS) == "SINGLE") {
urutan1 [0] = GameObject.Find ("Hantu1A");
urutan1 [1] = GameObject.Find (PlayerPrefs.GetString ("Urutan1"));
healthBar1 [0] = urutan1 [0].transform.Find ("Canvas").transform.Find ("Image").gameObject;
healthBar1 [1] = urutan1 [1].transform.Find ("Canvas").transform.Find ("Image").gameObject;
//suit1 [0] = "Block";
suit1 [1] = PlayerPrefs.GetString ("Suit1");
urutan2 [0] = GameObject.Find ("Hantu2A");
urutan2 [1] = GameObject.Find (PlayerPrefs.GetString ("Urutan2"));
healthBar2 [0] = urutan2 [0].transform.Find ("Canvas").transform.Find ("Image").gameObject;
healthBar2 [1] = urutan2 [1].transform.Find ("Canvas").transform.Find ("Image").gameObject;
//suit2 [0] = "Charge";
suit2 [1] = PlayerPrefs.GetString ("Suit2");
urutan3 [0] = GameObject.Find ("Hantu3A");
urutan3 [1] = GameObject.Find (PlayerPrefs.GetString ("Urutan3"));
healthBar3 [0] = urutan3 [0].transform.Find ("Canvas").transform.Find ("Image").gameObject;
healthBar3 [1] = urutan3 [1].transform.Find ("Canvas").transform.Find ("Image").gameObject;
//suit3 [0] = "Focus";
suit3 [1] = PlayerPrefs.GetString ("Suit3");
waiting.SetActive (false);
//information.SetActive (true);
if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") {
firstTimerTanding ();
StartCoroutine (urutanPlay());
}
else {
StartCoroutine (urutanPlay());
}
}
else {
StartCoroutine (sendFormation());
}
}
}
if (getReadyStatus) {
timer -= Time.deltaTime;
scrollBar.transform.Find("Scrollbar").GetComponent<Scrollbar>().size = timer / 10;
}
if (timer < 0 && timeUps == false) {
timeUps = true;
for (int i = 0; i < alpha.Count; i++) {
string temp = alpha [0];
int randomIndex = Random.Range (i, alpha.Count);
alpha [i] = alpha [randomIndex];
alpha [randomIndex] = temp;
}
StartCoroutine (randomPilihanInput());
}
if (PlayerPrefs.GetString (Link.JENIS) == "SINGLE" && PlayerPrefs.GetInt ("win") == 1 && levelingmate) {
float fExp1 = MonsterEXP1 / Targetnextlevel1;
float fExp2 = MonsterEXP2 / Targetnextlevel2;
float fExp3 = MonsterEXP3 / Targetnextlevel3;
//Debug.Log (fExp);
Monster1GO.transform.Find ("EXPBar1").transform.Find ("Expbar").GetComponent<Image> ().fillAmount = fExp1;
Monster2GO.transform.Find ("EXPBar2").transform.Find ("Expbar").GetComponent<Image> ().fillAmount = fExp2;
Monster3GO.transform.Find ("EXPBar3").transform.Find ("Expbar").GetComponent<Image> ().fillAmount = fExp3;
// Level.text = MonsterLevel.ToString ();
if (MonsterEXP1 >= Targetnextlevel1) {
tempmonsterexp1 = monstercurrentexp1 - Targetnextlevel1;
MonsterEXP1 = (int)tempmonsterexp1;
monstercurrentexp1 = tempmonsterexp1;
MonsterLevel1 += 1;
MonsterEXP1 = (int)Mathf.MoveTowards (0, monstercurrentexp1, 10);
}
if (MonsterEXP2 >= Targetnextlevel2) {
tempmonsterexp2 = monstercurrentexp2 - Targetnextlevel2;
MonsterEXP2 = (int)tempmonsterexp2;
monstercurrentexp2 = tempmonsterexp2;
MonsterLevel2 += 1;
MonsterEXP2 = (int)Mathf.MoveTowards (0, monstercurrentexp2, 10);
}
if (MonsterEXP3 >= Targetnextlevel3) {
tempmonsterexp3 = monstercurrentexp3 - Targetnextlevel3;
MonsterEXP3 = (int)tempmonsterexp3;
monstercurrentexp3 = tempmonsterexp3;
MonsterLevel3 += 1;
MonsterEXP3 = (int)Mathf.MoveTowards (0, monstercurrentexp3, 10);
}
MonsterEXP1 = (int)Mathf.MoveTowards (MonsterEXP1, monstercurrentexp1, 10);
MonsterEXP2 = (int)Mathf.MoveTowards (MonsterEXP2, monstercurrentexp2, 10);
MonsterEXP3 = (int)Mathf.MoveTowards (MonsterEXP3, monstercurrentexp3, 10);
//Debug.Log (MonsterEXP);
// untuk effect level up
if (Monster1GO.transform.Find ("EXPBar1").transform.Find ("Expbar").GetComponent<Image> ().fillAmount >= 1f) {
Debug.Log ("levelup");
Monster1GO.transform.Find ("leveluptext").gameObject.SetActive (true);
Monster1GO.transform.Find ("Level").GetComponent<Text> ().text = MonsterLevel1.ToString();
GameObject blam = Instantiate (effect, m1);
//gethantunextlevel.OnClick ();
//gethantuuser.Reload ();
Targetnextlevel1 = PlayerPrefs.GetFloat ("target1");
} else {
}
if (Monster2GO.transform.Find ("EXPBar2").transform.Find ("Expbar").GetComponent<Image> ().fillAmount >= 1f) {
Debug.Log ("levelup");
Monster2GO.transform.Find ("leveluptext").gameObject.SetActive (true);
Monster2GO.transform.Find ("Level").GetComponent<Text> ().text = MonsterLevel2.ToString();
GameObject blam = Instantiate (effect, m2);
//gethantunextlevel.OnClick ();
//gethantuuser.Reload ();
Targetnextlevel2 = PlayerPrefs.GetFloat ("target2");
} else {
}
if (Monster3GO.transform.Find ("EXPBar3").transform.Find ("Expbar").GetComponent<Image> ().fillAmount >= 1f) {
Debug.Log ("levelup");
Monster3GO.transform.Find ("leveluptext").gameObject.SetActive (true);
Monster3GO.transform.Find ("Level").GetComponent<Text> ().text = MonsterLevel3.ToString();
GameObject blam = Instantiate (effect, m3);
//gethantunextlevel.OnClick ();
//gethantuuser.Reload ();
Targetnextlevel3 = PlayerPrefs.GetFloat ("target3");
} else {
}
switch (MonsterGrade1) {
case 1:
Monster1GO.transform.Find ("bintangsusunstats").transform.Find ("bintang1").gameObject.SetActive (true);
if (MonsterLevel1 == 15) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
// buttonactivate ();
}
break;
case 2:
Monster1GO.transform.Find ("bintangsusunstats").transform.Find ("bintang2").gameObject.SetActive (true);
if (MonsterLevel1 == 20) {
//Level.text = "Max";
//Mexp.text = "Max";
//EXPBar.fillAmount = 1;
//buttondeactivate ();
} else {
// buttonactivate ();
}
break;
case 3:
Monster1GO.transform.Find ("bintangsusunstats").transform.Find ("bintang3").gameObject.SetActive (true);
if (MonsterLevel1 == 25) {
//Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
//buttonactivate ();
}
break;
case 4:
Monster1GO.transform.Find ("bintangsusunstats").transform.Find ("bintang4").gameObject.SetActive (true);
if (MonsterLevel1 == 30) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
//buttonactivate ();
}
break;
case 5:
Monster1GO.transform.Find ("bintangsusunstats").transform.Find ("bintang5").gameObject.SetActive (true);
if (MonsterLevel1 == 35) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
//buttondeactivate ();
} else {
//buttonactivate ();
}
break;
case 6:
Monster1GO.transform.Find ("bintangsusunstats").transform.Find ("bintang6").gameObject.SetActive (true);
if (MonsterLevel1 == 40) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
//buttonactivate ();
}
break;
}
switch (MonsterGrade2) {
case 1:
Monster2GO.transform.Find ("bintangsusunstats").transform.Find ("bintang1").gameObject.SetActive (true);
if (MonsterLevel1 == 15) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
// buttonactivate ();
}
break;
case 2:
Monster2GO.transform.Find ("bintangsusunstats").transform.Find ("bintang2").gameObject.SetActive (true);
if (MonsterLevel1 == 20) {
//Level.text = "Max";
//Mexp.text = "Max";
//EXPBar.fillAmount = 1;
//buttondeactivate ();
} else {
// buttonactivate ();
}
break;
case 3:
Monster2GO.transform.Find ("bintangsusunstats").transform.Find ("bintang3").gameObject.SetActive (true);
if (MonsterLevel1 == 25) {
//Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
//buttonactivate ();
}
break;
case 4:
Monster2GO.transform.Find ("bintangsusunstats").transform.Find ("bintang4").gameObject.SetActive (true);
if (MonsterLevel1 == 30) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
//buttonactivate ();
}
break;
case 5:
Monster2GO.transform.Find ("bintangsusunstats").transform.Find ("bintang5").gameObject.SetActive (true);
if (MonsterLevel1 == 35) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
//buttondeactivate ();
} else {
//buttonactivate ();
}
break;
case 6:
Monster2GO.transform.Find ("bintangsusunstats").transform.Find ("bintang6").gameObject.SetActive (true);
if (MonsterLevel1 == 40) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
//buttonactivate ();
}
break;
}
switch (MonsterGrade3) {
case 1:
Monster3GO.transform.Find ("bintangsusunstats").transform.Find ("bintang1").gameObject.SetActive (true);
if (MonsterLevel1 == 15) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
// buttonactivate ();
}
break;
case 2:
Monster3GO.transform.Find ("bintangsusunstats").transform.Find ("bintang2").gameObject.SetActive (true);
if (MonsterLevel1 == 20) {
//Level.text = "Max";
//Mexp.text = "Max";
//EXPBar.fillAmount = 1;
//buttondeactivate ();
} else {
// buttonactivate ();
}
break;
case 3:
Monster3GO.transform.Find ("bintangsusunstats").transform.Find ("bintang3").gameObject.SetActive (true);
if (MonsterLevel1 == 25) {
//Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
//buttonactivate ();
}
break;
case 4:
Monster3GO.transform.Find ("bintangsusunstats").transform.Find ("bintang4").gameObject.SetActive (true);
if (MonsterLevel1 == 30) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
//buttonactivate ();
}
break;
case 5:
Monster3GO.transform.Find ("bintangsusunstats").transform.Find ("bintang5").gameObject.SetActive (true);
if (MonsterLevel1 == 35) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
//buttondeactivate ();
} else {
//buttonactivate ();
}
break;
case 6:
Monster3GO.transform.Find ("bintangsusunstats").transform.Find ("bintang6").gameObject.SetActive (true);
if (MonsterLevel1 == 40) {
// Level.text = "Max";
// Mexp.text = "Max";
// EXPBar.fillAmount = 1;
// buttondeactivate ();
} else {
//buttonactivate ();
}
break;
}
// levelingmate = false;
}
// healthA1.GetComponent<filled> ().currenthealth = health1 [0];
// healthA2.GetComponent<filled> ().currenthealth = health2 [0];
// healthA3.GetComponent<filled> ().currenthealth = health3 [0];
// healthB1.GetComponent<filled> ().currenthealth = health1 [1];
// healthB2.GetComponent<filled> ().currenthealth = health2 [1];
// healthB3.GetComponent<filled> ().currenthealth = health3 [1];
if (PlayerPrefs.GetString (Link.JENIS) == "SINGLE"&& presentDone==false ) {
if (PlayerPrefs.GetInt ("win") == 1) {
WinnerPresent ();
Audioplay.clip = ending [2];
Audioplay.Play ();
// if (CurrentbankExp1 < 1000) {
//
// transform.FindChild ("1000").GetComponent<Button> ().interactable = false;
//
// if (CurrentbankExp < 100) {
// transform.FindChild ("100").GetComponent<Button> ().interactable = false;
// if (CurrentbankExp < 10) {
//
// transform.FindChild ("10").GetComponent<Button> ().interactable = false;
// }
// }
// } else {
// buttonactivate ();
// }
} else {
//Audioplay.clip = ending [3];
//Audioplay.Play ();
}
}
//done
}
void monsterleveling(){
if (MonsterGrade1 == 1) {
if (MonsterLevel1 >= 15) {
//do nothing
Targetnextlevel1=999999;
} else {
StartCoroutine(sendEXP1(playerhantuid1,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade1 == 2) {
if (MonsterLevel1 >= 20) {
Targetnextlevel1=999999;
//do nothing
} else {
StartCoroutine(sendEXP1(playerhantuid1,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade1 == 3) {
if (MonsterLevel1 >= 25) {
Targetnextlevel1=999999;
//do nothing
} else {
StartCoroutine(sendEXP1(playerhantuid1,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade1 == 4) {
if (MonsterLevel1 >= 30) {
Targetnextlevel1=999999;
//do nothing
} else {
StartCoroutine(sendEXP1(playerhantuid1,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade1 == 5) {
if (MonsterLevel1 >= 35) {
Targetnextlevel1=999999;
//do nothing
} else {
StartCoroutine(sendEXP1(playerhantuid1,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade1 == 6) {
if (MonsterLevel1 >= 40) {
Targetnextlevel1=999999;
//do nothing
} else {
StartCoroutine(sendEXP1(playerhantuid1,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
}
void monsterleveling2(){
if (MonsterGrade2 == 1) {
if (MonsterLevel2 >= 15) {
Targetnextlevel2=999999;
//do nothing
} else {
StartCoroutine(sendEXP2(playerhantuid2,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade2 == 2) {
if (MonsterLevel2 >= 20) {
Targetnextlevel2=999999;
//do nothing
} else {
StartCoroutine(sendEXP2(playerhantuid2,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade2 == 3) {
if (MonsterLevel2 >= 25) {
Targetnextlevel2=999999;
//do nothing
} else {
StartCoroutine(sendEXP2(playerhantuid2,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade2 == 4) {
if (MonsterLevel2 >= 30) {
Targetnextlevel2=999999;
//do nothing
} else {
StartCoroutine(sendEXP2(playerhantuid2,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade2 == 5) {
if (MonsterLevel2 >= 35) {
Targetnextlevel2=999999;
//do nothing
} else {
StartCoroutine(sendEXP2(playerhantuid2,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade2 == 6) {
if (MonsterLevel2 >= 40) {
Targetnextlevel2=999999;
//do nothing
} else {
StartCoroutine(sendEXP2(playerhantuid2,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
}
void monsterleveling3(){
if (MonsterGrade3 == 1) {
if (MonsterLevel3 >= 15) {
Targetnextlevel3=999999;
//do nothing
} else {
StartCoroutine(sendEXP3(playerhantuid3,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade3 == 2) {
if (MonsterLevel3 >= 20) {
Targetnextlevel3=999999;
//do nothing
} else {
StartCoroutine(sendEXP3(playerhantuid3,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade3 == 3) {
if (MonsterLevel3 >= 25) {
Targetnextlevel3=999999;
//do nothing
} else {
StartCoroutine(sendEXP3(playerhantuid3,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade3 == 4) {
if (MonsterLevel3 >= 30) {
Targetnextlevel3=999999;
//do nothing
} else {
StartCoroutine(sendEXP3(playerhantuid3,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade3 == 5) {
if (MonsterLevel3 >= 35) {
Targetnextlevel3=999999;
//do nothing
} else {
StartCoroutine(sendEXP3(playerhantuid3,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
if (MonsterGrade3 == 6) {
if (MonsterLevel3 >= 40) {
Targetnextlevel3=999999;
//do nothing
} else {
StartCoroutine(sendEXP3(playerhantuid3,PlayerPrefs.GetInt ("MAPSEXP")));
}
}
}
public void levelingbro(){
levelingmate = true;
}
void WinnerPresent(){
//DistribusiEXPMonsterItem (playerhantuid1, playerhantuid2, playerhantuid3, "somthing", "somthing", "somthing", "somthing", "somthing", "somthing", "somthing", "somthing", "somthing", "somthing", "somthing", "somthing", int.Parse (EXPValueText.text));
// StartCoroutine(sendEXP1(playerhantuid1,PlayerPrefs.GetInt ("MAPSEXP")));
// StartCoroutine(sendEXP2(playerhantuid2,PlayerPrefs.GetInt ("MAPSEXP")));
// StartCoroutine(sendEXP3(playerhantuid3,PlayerPrefs.GetInt ("MAPSEXP")));
// float.Parse(EXPValueText.text);
//monstercurrentexp2 += Exp;
//monstercurrentexp3 += Exp;
var presentcode = RandomWeighted();
var winning = Random.value;
formkirimreward.AddField ("GOLD", 100);
EXPValueText.text = "100";
var presentType = PlayerPrefs.GetString("RewardItemType"+presentcode.ToString());
var presentQuantity = PlayerPrefs.GetString("RewardItemQuantity"+presentcode.ToString());
var presentName = PlayerPrefs.GetString("RewardItemName"+presentcode.ToString());
if(presentType=="Item")
{
formkirimreward.AddField(presentName,presentQuantity);
ClaimText.text = presentQuantity + presentName;
}
// if (winning > 0.25f) {
// Debug.Log ("dapet coin / sampah");
// var hadiah = Random.Range (1000, 1400);
// Debug.Log (hadiah);
// formkirimreward.AddField ("GOLD", hadiah);
// ClaimText.text = hadiah.ToString()+"X";
// EXPValueText.text = hadiah.ToString()+"X";
// StartCoroutine (SendReward ());
// Rewards [7].gameObject.SetActive (true);
// }
// else if (winning < 0.25f && Random.value > 0.1f) {
// Debug.Log ("dapet hadiah lumayan lah");
// var value = Random.Range (0, equipmentreward.Length);
// if (value == 0) {
// Rewards [6].gameObject.SetActive (true);
// }
// if (value == 1) {
// Rewards [3].gameObject.SetActive (true);
// }
// if (value == 2) {
// Rewards [5].gameObject.SetActive (true);
// }
// if (value == 3) {
// Rewards [4].gameObject.SetActive (true);
// }
// var hadiah = equipmentreward [value];
// formkirimreward.AddField ("ITEM", hadiah);
// ClaimText.text = 1.ToString()+"X";
// StartCoroutine (SendReward ());
// Debug.Log (hadiah);
// }
// else if (winning < 0.05f) {
// Debug.Log ("dapet door price");
// var randomagain = Random.value;
// if (randomagain < 0.85f) {
// nilai = 0;
// Rewards [2].gameObject.SetActive (true);
// }
// else if (randomagain > 0.85f && randomagain < 0.95) {
// nilai = 1;
// Rewards [1].gameObject.SetActive (true);
// }
// else if (randomagain > 0.95) {
// nilai = 2;
// Rewards [0].gameObject.SetActive (true);
// }
// ClaimText.text = 1.ToString()+"X";
// var hadiah = itemsreward [nilai];
// Debug.Log (hadiah);
// formkirimreward.AddField (hadiah, 1);
StartCoroutine (SendReward ());
//StartCoroutine (sendEXP (idhantuplayer, 1000));
// }
ClaimUI.SetActive (true);
presentDone = true;
}
IEnumerator SendReward(){
var expsingle = PlayerPrefs.GetInt ("MAPSEXP") * 3;
Debug.Log (expsingle);
string url = Link.url + "update_data_user";
//WWWForm form = new WWWForm ();
formkirimreward.AddField ("JumlahXpTransfer", (expsingle));
formkirimreward.AddField ("MY_ID", PlayerPrefs.GetString(Link.ID));
//formkirimreward.AddField ("ITEM", equipmentreward[0]);
WWW www = new WWW(url,formkirimreward);
yield return www;
if (www.error == null) {
monsterleveling();
}
Debug.Log (www.text);
// var jsonString = JSON.Parse (www.text);
//PlayerPrefs.SetString ("BATU", jsonString ["data"]);
}
private IEnumerator sendEXP1(string hantuplayerid, int Exp)
{
Debug.Log ("TES");
string url = Link.url + "send_xp";
WWWForm form = new WWWForm ();
form.AddField ("MY_ID", PlayerPrefs.GetString(Link.ID));
form.AddField ("PlayerHantuID", hantuplayerid);
form.AddField ("EXPERIENCE", Exp);
//form.AddField ("CURRENTEXPB", Latestexpbank);
WWW www = new WWW(url,form);
yield return www;
if (www.error == null) {
var jsonString = JSON.Parse (www.text);
PlayerPrefs.SetFloat("target1", float.Parse(jsonString ["code"] ["Targetnextlevel"]));
monstercurrentexp1 += Exp;
Debug.Log (www.text);
monsterleveling2();
} else {
Debug.Log ("Failed kirim data");
yield return new WaitForSeconds (5);
}
}
private IEnumerator sendEXP2(string hantuplayerid, int Exp)
{
Debug.Log ("TES");
string url = Link.url + "send_xp";
WWWForm form = new WWWForm ();
form.AddField ("MY_ID", PlayerPrefs.GetString(Link.ID));
form.AddField ("PlayerHantuID", hantuplayerid);
form.AddField ("EXPERIENCE", Exp);
//form.AddField ("CURRENTEXPB", Latestexpbank);
WWW www = new WWW(url,form);
yield return www;
if (www.error == null) {
var jsonString = JSON.Parse (www.text);
PlayerPrefs.SetFloat("target2", float.Parse(jsonString ["code"] ["Targetnextlevel"]));
monstercurrentexp2 += Exp;
monsterleveling3();
} else {
Debug.Log ("Failed kirim data");
yield return new WaitForSeconds (5);
}
}
private IEnumerator sendEXP3(string hantuplayerid, int Exp)
{
Debug.Log ("TES");
string url = Link.url + "send_xp";
WWWForm form = new WWWForm ();
form.AddField ("MY_ID", PlayerPrefs.GetString(Link.ID));
form.AddField ("PlayerHantuID", hantuplayerid);
form.AddField ("EXPERIENCE", Exp);
//form.AddField ("CURRENTEXPB", Latestexpbank);
WWW www = new WWW(url,form);
yield return www;
if (www.error == null) {
var jsonString = JSON.Parse (www.text);
PlayerPrefs.SetFloat("target3", float.Parse(jsonString ["code"] ["Targetnextlevel"]));
monstercurrentexp3 += Exp;
} else {
Debug.Log ("Failed kirim data");
yield return new WaitForSeconds (5);
}
}
//tambah exp habis game single player
IEnumerator DistribusiEXPMonsterItem(string hantuplayerid1,string hantuplayerid2,string hantuplayerid3,string hantuplayerid1item1,string hantuplayerid1item2,string hantuplayerid1item3,string hantuplayerid1item4,string hantuplayerid2item1,string hantuplayerid2item2,string hantuplayerid2item3,string hantuplayerid2item4,string hantuplayerid3item1,string hantuplayerid3item2,string hantuplayerid3item3,string hantuplayerid3item4, int Exp){
Debug.Log ("TES");
string url = Link.url + "send_xp";
WWWForm form = new WWWForm ();
form.AddField ("MY_ID", PlayerPrefs.GetString(Link.ID));
form.AddField ("PlayerHantuID1", hantuplayerid1);
form.AddField ("PlayerHantuID2", hantuplayerid2);
form.AddField ("PlayerHantuID3", hantuplayerid3);
form.AddField ("PlayerHantuID1item1", hantuplayerid1item1);
form.AddField ("PlayerHantuID2item1", hantuplayerid2item1);
form.AddField ("PlayerHantuID3item1", hantuplayerid3item1);
form.AddField ("PlayerHantuID1item2", hantuplayerid1item2);
form.AddField ("PlayerHantuID2item2", hantuplayerid2item2);
form.AddField ("PlayerHantuID3item2", hantuplayerid3item2);
form.AddField ("PlayerHantuID1item3", hantuplayerid1item3);
form.AddField ("PlayerHantuID2item3", hantuplayerid2item3);
form.AddField ("PlayerHantuID3item3", hantuplayerid3item3);
form.AddField ("PlayerHantuID1item4", hantuplayerid1item4);
form.AddField ("PlayerHantuID2item4", hantuplayerid2item4);
form.AddField ("PlayerHantuID3item4", hantuplayerid3item4);
form.AddField ("EXPERIENCE", Exp);
//form.AddField ("CURRENTEXPB", Latestexpbank);
WWW www = new WWW(url,form);
yield return www;
if (www.error == null) {
var jsonString = JSON.Parse (www.text);
PlayerPrefs.SetFloat("target", float.Parse(jsonString ["code"] ["Targetnextlevel"]));
//monstercurrentexp += Exp;
monstercurrentexp1 += Exp;
monstercurrentexp2 += Exp;
monstercurrentexp3 += Exp;
} else {
Debug.Log ("Failed kirim data");
//yield return new WaitForSeconds (5);
//StartCoroutine (updateData());
}
}
IEnumerator randomenemiesmovement(){
int j = Random.Range (0, 3);
int k = Random.Range (0, 3);
int l = Random.Range (0, 3);
if (j==0) {
suit1[0]="Charge";
}
if (j==1) {
suit1[0]="Block";
}
if (j==2) {
suit1[0]="Focus";
}
yield return new WaitForSeconds(1);
if (k==0) {
suit2[0]="Charge";
}
if (k==1) {
suit2[0]="Block";
}
if (k==2) {
suit2[0]="Focus";
}
yield return new WaitForSeconds(1);
if (l==0) {
suit3[0]="Charge";
}
if (l==1) {
suit3[0]="Block";
}
if (l==2) {
suit3[0]="Focus";
}
}
IEnumerator randomPilihanInput(){
int j = Random.Range (0, 3);
if (j == 0) {
if (pilihanInputSuit [0].activeSelf) {
pilihanInputSuit [0].GetComponent<RandomClick> ().RandomPilih ();
}
yield return new WaitForSeconds(1);
if (pilihanInputSuit [1].activeSelf) {
pilihanInputSuit [1].GetComponent<RandomClick> ().RandomPilih ();
}
yield return new WaitForSeconds(1);
if (pilihanInputSuit [2].activeSelf) {
pilihanInputSuit [2].GetComponent<RandomClick> ().RandomPilih ();
}
if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") {
firstTimerTanding ();
//StartCoroutine (urutanPlay());
}
}
else if (j == 1) {
if (pilihanInputSuit [0].activeSelf) {
pilihanInputSuit [0].GetComponent<RandomClick> ().RandomPilih ();
}
yield return new WaitForSeconds(1);
if (pilihanInputSuit [2].activeSelf) {
pilihanInputSuit [2].GetComponent<RandomClick> ().RandomPilih ();
}
yield return new WaitForSeconds(1);
if (pilihanInputSuit [1].activeSelf) {
pilihanInputSuit [1].GetComponent<RandomClick> ().RandomPilih ();
}if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") {
firstTimerTanding ();
//StartCoroutine (urutanPlay());
}
}
else if (j == 2) {
if (pilihanInputSuit [2].activeSelf) {
pilihanInputSuit [2].GetComponent<RandomClick> ().RandomPilih ();
}
yield return new WaitForSeconds(1);
if (pilihanInputSuit [0].activeSelf) {
pilihanInputSuit [0].GetComponent<RandomClick> ().RandomPilih ();
}
yield return new WaitForSeconds(1);
if (pilihanInputSuit [1].activeSelf) {
pilihanInputSuit [1].GetComponent<RandomClick> ().RandomPilih ();
}if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") {
firstTimerTanding ();
//StartCoroutine (urutanPlay());
}
}
else if (j == 3) {
if (pilihanInputSuit [2].activeSelf) {
pilihanInputSuit [2].GetComponent<RandomClick> ().RandomPilih ();
}
yield return new WaitForSeconds(1);
if (pilihanInputSuit [1].activeSelf) {
pilihanInputSuit [1].GetComponent<RandomClick> ().RandomPilih ();
}
yield return new WaitForSeconds(1);
if (pilihanInputSuit [0].activeSelf) {
pilihanInputSuit [0].GetComponent<RandomClick> ().RandomPilih ();
}if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") {
firstTimerTanding ();
//StartCoroutine (urutanPlay());
}
}
}
private IEnumerator sendFormation()
{
ImDoneForSendBool = true;
StartCoroutine (ImDoneForSend ());
Debug.Log ("send prrogress");
string url = Link.url + "send_formation";
WWWForm form = new WWWForm ();
form.AddField (Link.ID, PlayerPrefs.GetString(Link.ID));
form.AddField ("pos", PlayerPrefs.GetInt("pos").ToString());
form.AddField ("urutan_1", PlayerPrefs.GetString("Urutan1"));
form.AddField ("suit_1", PlayerPrefs.GetString("Suit1"));
form.AddField ("urutan_2", PlayerPrefs.GetString("Urutan2"));
form.AddField ("suit_2", PlayerPrefs.GetString("Suit2"));
form.AddField ("urutan_3", PlayerPrefs.GetString("Urutan3"));
form.AddField ("suit_3", PlayerPrefs.GetString("Suit3"));
form.AddField ("room_name", PlayerPrefs.GetString ("RoomName"));
WWW www = new WWW(url,form);
yield return www;
if (www.error == null) {
Debug.Log ("send success");
var jsonString = JSON.Parse (www.text);
int a = 0;
for (int i = 0; i < int.Parse (jsonString ["code"]); i++) {
a++;
}
if (a == 1) {
ImDoneForSendInteger = 0;
ImDoneForSendBool = false;
ImDoneForWaitingBool = true;
StartCoroutine (ImDoneForWaiting ());
StartCoroutine (onCoroutine());
} else {
Debug.Log ("fail");
}
} else {
Debug.Log ("fail");
}
}
public bool ImDoneForWaitingBool = true;
public int ImDoneForWaitingInteger = 0;
public GameObject done;
IEnumerator ImDoneForWaiting () {
while(ImDoneForWaitingBool)
{
Debug.Log ("TikTok : " + ImDoneForWaitingInteger.ToString ());
ImDoneForWaitingInteger++;
if (ImDoneForWaitingInteger>30) {
done.SetActive (true);
}
yield return new WaitForSeconds(1f);
}
}
public void OnClickDone () {
Application.LoadLevel ("Home");
}
public bool ImDoneForSendBool = true;
public int ImDoneForSendInteger = 0;
public GameObject Send;
IEnumerator ImDoneForSend () {
while(ImDoneForSendBool)
{
Debug.Log ("TikTok : " + ImDoneForSendInteger.ToString ());
ImDoneForSendInteger++;
if (ImDoneForSendInteger>30) {
Send.SetActive (true);
}
yield return new WaitForSeconds(1f);
}
}
public void OnClickSend () {
Application.LoadLevel ("Home");
}
IEnumerator onCoroutine(){
while(data_belum_ada)
{
StartCoroutine (cekFormation());
yield return new WaitForSeconds(1f);
}
}
private IEnumerator cekFormation()
{
if (data_belum_ada) {
string url = Link.url + "cek_formation";
WWWForm form = new WWWForm ();
form.AddField (Link.ID, PlayerPrefs.GetString(Link.ID));
form.AddField ("room_name", PlayerPrefs.GetString ("RoomName"));
WWW www = new WWW(url,form);
yield return www;
if (www.error == null) {
var jsonString = JSON.Parse (www.text);
int a = 0;
int c = 0;
for (int i = 0; i < int.Parse (jsonString ["code"]); i++) {
a++;
}
if (a == 2 && data_belum_ada) {
data_belum_ada = false;
ImDoneForWaitingBool = false;
ImDoneForWaitingInteger = 0;
Debug.Log ("SUDAH DI FALSE KAN !!!!");
Debug.Log (data_belum_ada);
urutan1 [0] = GameObject.Find (jsonString ["data"] [0] ["urutan_1"]);
urutan1 [1] = GameObject.Find (jsonString ["data"] [1] ["urutan_1"]);
healthBar1 [0] = urutan1 [0].transform.Find ("Canvas").transform.Find ("Image").gameObject;
healthBar1 [1] = urutan1 [1].transform.Find ("Canvas").transform.Find ("Image").gameObject;
suit1 [0] = jsonString ["data"] [0] ["suit_1"];
suit1 [1] = jsonString ["data"] [1] ["suit_1"];
urutan2 [0] = GameObject.Find (jsonString ["data"] [0] ["urutan_2"]);
urutan2 [1] = GameObject.Find (jsonString ["data"] [1] ["urutan_2"]);
healthBar2 [0] = urutan2 [0].transform.Find ("Canvas").transform.Find ("Image").gameObject;
healthBar2 [1] = urutan2 [1].transform.Find ("Canvas").transform.Find ("Image").gameObject;
suit2 [0] = jsonString ["data"] [0] ["suit_2"];
suit2 [1] = jsonString ["data"] [1] ["suit_2"];
urutan3 [0] = GameObject.Find (jsonString ["data"] [0] ["urutan_3"]);
urutan3 [1] = GameObject.Find (jsonString ["data"] [1] ["urutan_3"]);
healthBar3 [0] = urutan3 [0].transform.Find ("Canvas").transform.Find ("Image").gameObject;
healthBar3 [1] = urutan3 [1].transform.Find ("Canvas").transform.Find ("Image").gameObject;
suit3 [0] = jsonString ["data"] [0] ["suit_3"];
suit3 [1] = jsonString ["data"] [1] ["suit_3"];
waiting.SetActive (false);
//information.SetActive (true);
StartCoroutine (urutanPlay());
} else {
waiting.SetActive (true);
}
} else {
Debug.Log ("fail");
}
}
}
public Image[] kertasButton;
public Image[] batuButton;
public Image[] guntingButton;
public Sprite kertasSprite;
public Sprite batuSprite;
public Sprite guntingSprite;
IEnumerator urutanPlay(){
scrollBar.SetActive (false);
cameraB.GetComponent<Animator> ().SetBool ("Fighting", true);
cameraA.GetComponent<Animator> ().SetBool ("Fighting", true);
yield return new WaitForSeconds(1f);
vs.SetActive (true);
Aobject.GetComponent<Animator> ().SetBool ("LeftFight", true);
Bobject.GetComponent<Animator> ().SetBool ("RightFight", true);
// Aaobject.GetComponent<Animator> ().SetBool ("LeftFight", true);
// Baobject.GetComponent<Animator> ().SetBool ("RightFight", true);
if (suit1 [0] == "Charge") {
Aobject.GetComponent<Animator> ().SetBool ("FightCharge", true);
}
if (suit1 [0] == "Focus") {
Aobject.GetComponent<Animator> ().SetBool ("FightFocus", true);
}
if (suit1 [0] == "Block") {
Aobject.GetComponent<Animator> ().SetBool ("FightBlock", true);
}
if (suit1 [1] == "Charge") {
Bobject.GetComponent<Animator> ().SetBool ("FightCharge", true);
}
if (suit1 [1] == "Focus") {
Bobject.GetComponent<Animator> ().SetBool ("FightFocus", true);
}
if (suit1 [1] == "Block") {
Bobject.GetComponent<Animator> ().SetBool ("FightBlock", true);
}
StartCoroutine (War(urutan1[0],urutan1[1],suit1[0],suit1[1],1));
pilihanInputSuit [0].SetActive (false);
pilihanInputSuit [1].SetActive (false);
pilihanInputSuit [2].SetActive (false);
if (PlayerPrefs.GetString(Link.JENIS) == "SINGLE")
{
//healthBar1[1].SetActive(false);
//healthBar2[1].SetActive(false);
//healthBar3[1].SetActive(false);
}
//cameraB.GetComponent<Animator> ().SetBool ("Fighting", false);
yield return new WaitForSeconds(5f);
cameraB.GetComponent<Animator> ().SetBool ("Fighting", true);
cameraA.GetComponent<Animator> ().SetBool ("Fighting", true);
Aobject.GetComponent<Animator> ().SetBool ("LeftFight", true);
Bobject.GetComponent<Animator> ().SetBool ("RightFight", true);
// Aaobject.GetComponent<Animator> ().SetBool ("LeftFight", true);
// Baobject.GetComponent<Animator> ().SetBool ("RightFight", true);
if (suit2 [0] == "Charge") {
Aobject.GetComponent<Animator> ().SetBool ("FightCharge", true);
}
if (suit2 [0] == "Focus") {
Aobject.GetComponent<Animator> ().SetBool ("FightFocus", true);
}
if (suit2 [0] == "Block") {
Aobject.GetComponent<Animator> ().SetBool ("FightBlock", true);
}
if (suit2 [1] == "Charge") {
Bobject.GetComponent<Animator> ().SetBool ("FightCharge", true);
}
if (suit2 [1] == "Focus") {
Bobject.GetComponent<Animator> ().SetBool ("FightFocus", true);
}
if (suit2 [1] == "Block") {
Bobject.GetComponent<Animator> ().SetBool ("FightBlock", true);
}
StartCoroutine (War(urutan2[0],urutan2[1],suit2[0],suit2[1],2));
yield return new WaitForSeconds(5.3f);
cameraB.GetComponent<Animator> ().SetBool ("Fighting", true);
cameraA.GetComponent<Animator> ().SetBool ("Fighting", true);
Aobject.GetComponent<Animator> ().SetBool ("LeftFight", true);
Bobject.GetComponent<Animator> ().SetBool ("RightFight", true);
// Aaobject.GetComponent<Animator> ().SetBool ("LeftFight", true);
// Baobject.GetComponent<Animator> ().SetBool ("RightFight", true);
if (suit3 [0] == "Charge") {
Aobject.GetComponent<Animator> ().SetBool ("FightCharge", true);
}
if (suit3 [0] == "Focus") {
Aobject.GetComponent<Animator> ().SetBool ("FightFocus", true);
}
if (suit3 [0] == "Block") {
Aobject.GetComponent<Animator> ().SetBool ("FightBlock", true);
}
if (suit3 [1] == "Charge") {
Bobject.GetComponent<Animator> ().SetBool ("FightCharge", true);
}
if (suit3 [1] == "Focus") {
Bobject.GetComponent<Animator> ().SetBool ("FightFocus", true);
}
if (suit3 [1] == "Block") {
Bobject.GetComponent<Animator> ().SetBool ("FightBlock", true);
}
StartCoroutine (War(urutan3[0],urutan3[1],suit3[0],suit3[1],3));
yield return new WaitForSeconds(4);
cameraB.GetComponent<Animator> ().SetBool ("Fighting", false);
cameraA.GetComponent<Animator> ().SetBool ("Fighting", false);
kertasButton [0].sprite = kertasSprite;
kertasButton [1].sprite = kertasSprite;
kertasButton [2].sprite = kertasSprite;
batuButton [0].sprite = batuSprite;
batuButton [1].sprite = batuSprite;
batuButton [2].sprite = batuSprite;
guntingButton [0].sprite = guntingSprite;
guntingButton [1].sprite = guntingSprite;
guntingButton [2].sprite = guntingSprite;
kertasButton [0].transform.GetComponent<ButtonInput> ().tekan = true;
kertasButton [1].transform.GetComponent<ButtonInput> ().tekan = true;
kertasButton [2].transform.GetComponent<ButtonInput> ().tekan = true;
batuButton [0].transform.GetComponent<ButtonInput> ().tekan = true;
batuButton [1].transform.GetComponent<ButtonInput> ().tekan = true;
batuButton [2].transform.GetComponent<ButtonInput> ().tekan = true;
guntingButton [0].transform.GetComponent<ButtonInput> ().tekan = true;
guntingButton [1].transform.GetComponent<ButtonInput> ().tekan = true;
guntingButton [2].transform.GetComponent<ButtonInput> ().tekan = true;
scrollBar.SetActive (true);
vs.SetActive (false);
if (repeat) {
Debug.Log ("Repeat");
if (PlayerPrefs.GetString ("PLAY_TUTORIAL") != "TRUE") {
StartCoroutine (randomenemiesmovement ());
} else {
firstTimerTanding ();
}
if (PlayerPrefs.GetString (Link.JENIS) == "SINGLE") {
timer = 10f;
timeUps = false;
panggil_url = false;
data_belum_ada = true;
PlayerPrefs.SetInt ("Jumlah", 0);
// PlayerPrefs.SetString ("id_device","2");
// PlayerPrefs.SetString ("pos","2");
PlayerPrefs.SetString ("RoomName", "SINGLE");
plihan1.SetActive (true);
plihan2.SetActive (true);
plihan3.SetActive (true);
if (PlayerPrefs.GetString(Link.JENIS) == "SINGLE")
{
healthBar1[1].SetActive(true);
healthBar2[1].SetActive(true);
healthBar3[1].SetActive(true);
}
} else {
StartCoroutine (resetFormation());
}
}
else {
resetDatabaseYo = true;
if (Bb) {
if (PlayerPrefs.GetString (Link.JENIS) == "SINGLE") {
if (ApakahCameraA) {
Debug.Log ("KALAH");
PlayerPrefs.SetInt ("win", 0);
urutan1 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan2 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan3 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan1 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan2 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan3 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
cameraA.SetActive (false);
cameraB.SetActive (false);
plihan1.SetActive (false);
plihan2.SetActive (false);
plihan3.SetActive (false);
// EndOptionButton.SetActive (true);
losser.SetActive (true);
winner.SetActive (false);
scrollBar.SetActive (false);
speedOption.SetActive (false);
Time.timeScale = 1;
Audioplay.loop = false;
Audioplay.clip = ending [3];
Audioplay.Play ();
} else {
Debug.Log ("MENANG");
PlayerPrefs.SetInt ("win", 1);
urutan1 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan2 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan3 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan1 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan2 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan3 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
cameraA.SetActive (false);
cameraB.SetActive (false);
// CameraEnd.SetActive (true);
plihan1.SetActive (false);
plihan2.SetActive (false);
plihan3.SetActive (false);
// EndOptionButton.SetActive (true);
winner.SetActive (true);
losser.SetActive (false);
scrollBar.SetActive (false);
speedOption.SetActive (false);
Time.timeScale = 1;
Audioplay.loop = false;
Audioplay.clip = ending [2];
Audioplay.Play ();
}
}
//Multiplayer
//Multiplayer
//Multiplayer
else {
if (ApakahCameraA) {
Debug.Log ("KALAH");
PlayerPrefs.SetInt ("win", 0);
urutan1 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan2 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan3 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan1 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan2 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan3 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
cameraA.SetActive (false);
cameraB.SetActive (false);
plihan1.SetActive (false);
plihan2.SetActive (false);
plihan3.SetActive (false);
// EndOptionButton.SetActive (true);
losser.SetActive (true);
winner2.SetActive (false);
scrollBar.SetActive (false);
speedOption.SetActive (false);
Time.timeScale = 1;
Audioplay.loop = false;
Audioplay.clip = ending [3];
Audioplay.Play ();
} else {
Debug.Log ("MENANG");
PlayerPrefs.SetInt ("win", 1);
urutan1 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan2 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan3 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan1 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan2 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan3 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
cameraA.SetActive (false);
cameraB.SetActive (false);
// CameraEnd.SetActive (true);
plihan1.SetActive (false);
plihan2.SetActive (false);
plihan3.SetActive (false);
// EndOptionButton.SetActive (true);
winner2.SetActive (true);
losser.SetActive (false);
scrollBar.SetActive (false);
speedOption.SetActive (false);
Time.timeScale = 1;
Audioplay.loop = false;
Audioplay.clip = ending [2];
Audioplay.Play ();
}
}
}
else
//kondisi A menang
{
if (PlayerPrefs.GetString (Link.JENIS) == "SINGLE") {
if (ApakahCameraA) {
Debug.Log ("MENANG");
PlayerPrefs.SetInt ("win", 1);
urutan1 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan2 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan3 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan1 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan2 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan3 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
cameraA.SetActive (false);
cameraB.SetActive (false);
// CameraEnd.SetActive (true);
plihan1.SetActive (false);
plihan2.SetActive (false);
plihan3.SetActive (false);
//EndOptionButton.SetActive (true);
winner2.SetActive (true);
losser.SetActive (false);
scrollBar.SetActive (false);
speedOption.SetActive (false);
Time.timeScale = 1;
Audioplay.loop = false;
Audioplay.clip = ending [2];
Audioplay.Play ();
} else {
Debug.Log ("KALAH");
PlayerPrefs.SetInt ("win", 0);
urutan1 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan2 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan3 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan1 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan2 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan3 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
cameraA.SetActive (false);
cameraB.SetActive (false);
plihan1.SetActive (false);
plihan2.SetActive (false);
plihan3.SetActive (false);
// EndOptionButton.SetActive (true);
losser.SetActive (true);
winner2.SetActive (false);
scrollBar.SetActive (false);
speedOption.SetActive (false);
Time.timeScale = 1;
Audioplay.loop = false;
Audioplay.clip = ending [3];
Audioplay.Play ();
}
} else
//multiplayer
{
if (ApakahCameraA) {
Debug.Log ("MENANG");
PlayerPrefs.SetInt ("win", 1);
urutan1 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan2 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan3 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan1 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan2 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan3 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
cameraA.SetActive (false);
cameraB.SetActive (false);
// CameraEnd.SetActive (true);
plihan1.SetActive (false);
plihan2.SetActive (false);
plihan3.SetActive (false);
// EndOptionButton.SetActive (true);
winner2.SetActive (true);
losser.SetActive (false);
scrollBar.SetActive (false);
speedOption.SetActive (false);
Time.timeScale = 1;
Audioplay.loop = false;
Audioplay.clip = ending [2];
Audioplay.Play ();
} else {
Debug.Log ("KALAH");
PlayerPrefs.SetInt ("win", 0);
urutan1 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan2 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan3 [0].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("menang", QueueMode.PlayNow);
urutan1 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan2 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
urutan3 [1].transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("kalah", QueueMode.PlayNow);
cameraA.SetActive (false);
cameraB.SetActive (false);
plihan1.SetActive (false);
plihan2.SetActive (false);
plihan3.SetActive (false);
// EndOptionButton.SetActive (true);
losser.SetActive (true);
winner2.SetActive (false);
scrollBar.SetActive (false);
speedOption.SetActive (false);
Time.timeScale = 1;
Audioplay.loop = false;
Audioplay.clip = ending [3];
Audioplay.Play ();
}
}
}
if (ApakahCameraA) {
CameraEndA.SetActive (true);
canvasEnd ();
} else {
CameraEnd.SetActive (true);
canvasEnd ();
}
Debug.Log (PlayerPrefs.GetInt ("win"));
}
}
IEnumerator GoEND () {
yield return new WaitForSeconds (1);
Application.LoadLevel ("End");
}
public GameObject winner, winner2;
public GameObject losser;
private IEnumerator resetFormation()
{
Debug.Log ("RESET !!");
string url = Link.url + "reset_formation";
WWWForm form = new WWWForm ();
form.AddField (Link.ID, PlayerPrefs.GetString(Link.ID));
form.AddField ("room_name", PlayerPrefs.GetString ("RoomName"));
WWW www = new WWW(url,form);
yield return www;
if (www.error == null) {
timer = 10f;
timeUps = false;
panggil_url = false;
data_belum_ada = true;
PlayerPrefs.SetInt ("Jumlah", 0);
plihan1.SetActive (true);
plihan2.SetActive (true);
plihan3.SetActive (true);
}
}
bool resetDatabaseYo = false;
public void ResetDatabase () {
Application.LoadLevel ("MainMenu");
}
private IEnumerator resetDatabase()
{
waiting.SetActive (false);
string url = Link.url + "reset_database";
WWWForm form = new WWWForm ();
form.AddField (Link.ID, PlayerPrefs.GetString(Link.ID));
WWW www = new WWW(url,form);
yield return www;
if (www.error == null) {
Application.LoadLevel ("MainMenu");
}
}
public void PlaySajaLah(int i) {
if (i==1) {
StartCoroutine (War(GameObject.Find("Hantu1A"),GameObject.Find("Hantu2B"),"Charge","Block",1));
}
else if (i==2) {
StartCoroutine (War(GameObject.Find("Hantu2A"),GameObject.Find("Hantu3B"),"Block","Focus",1));
}
else if (i==3) {
StartCoroutine (War(GameObject.Find("Hantu2A"),GameObject.Find("Hantu3B"),"Charge","Focus",1));
}
else if (i==4) {
StartCoroutine (War(GameObject.Find("Hantu2A"),GameObject.Find("Hantu3B"),"Charge","Charge",1));
}
}
IEnumerator War (GameObject aObject, GameObject bObject, string pilA, string pilB, int urutan) {
Debug.Log (pilA + " " + pilB);
dg.text = (pilA + " " + pilB);
aObject.GetComponent<PlayAnimation> ().PlayMaju ();
bObject.GetComponent<PlayAnimation> ().PlayMaju ();
switch (pilA) {
case "Charge":
// Aobject.GetComponent<Animator> ().SetBool ("FightCharge", true);
Aobject.GetComponent<Image> ().sprite = Charge;
break;
case "Block":
// Aobject.GetComponent<Animator> ().SetBool ("FightBlock", true);
Aobject.GetComponent<Image> ().sprite = Block;
break;
case "Focus":
//Aobject.GetComponent<Animator> ().SetBool ("FightFocus", true);
Aobject.GetComponent<Image> ().sprite = Focus;
break;
}
switch (pilB) {
case "Charge":
//bObject.transform.FindChild ("Select").GetComponent<SpriteRenderer>().sprite = Charge;
Bobject.GetComponent<Animator> ().SetBool ("FightCharge", true);
Bobject.GetComponent<Image> ().sprite = Charge;
break;
case "Block":
//bObject.transform.FindChild ("Select").GetComponent<SpriteRenderer> ().sprite = Block;
Bobject.GetComponent<Animator> ().SetBool ("FightBlock", true);
Bobject.GetComponent<Image> ().sprite = Block;
break;
case "Focus":
//bObject.transform.FindChild ("Select").GetComponent<SpriteRenderer>().sprite = Focus;
Bobject.GetComponent<Animator> ().SetBool ("FightFocus", true);
Bobject.GetComponent<Image> ().sprite = Focus;
break;
}
yield return new WaitForSeconds (1.3f);
if (pilA == "Charge" && pilB == "Block") {
damage = bObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().damage- (aObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().defend/2);
if (damage <= 0) {
damage = 0;
}damageA.text = "- "+damage.ToString ();
damageB.text = "- "+damage.ToString ();
Bobject.GetComponent<Animator> ().SetBool ("win", true);
Aobject.GetComponent<Animator> ().SetBool ("chargekalah", true);
Debug.Log ("CB");
//aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
//bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("attack",QueueMode.PlayNow);
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("nangkis",QueueMode.PlayNow);
yield return new WaitForSeconds (0.5f);
Seri_Bdef.Play ();
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle",QueueMode.PlayNow,PlayMode.StopAll);
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("attack",QueueMode.PlayNow);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("hit",QueueMode.PlayNow);
yield return new WaitForSeconds (.5f);
damageA.gameObject.SetActive (true);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
yield return new WaitForSeconds (0.3f);
HealthReduction (urutan,0,damage);
A.Play ();
hitYa.Play ();
}
else if (pilA == "Block" && pilB == "Charge") {
Debug.Log ("BC");
yield return new WaitForSeconds (0.5f);
damage = aObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().damage- bObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().defend/2;
if (damage <= 0) {
damage = 0;
}damageA.text = "- "+damage.ToString ();
damageB.text = "- "+damage.ToString ();
Aobject.GetComponent<Animator> ().SetBool ("win", true);
Bobject.GetComponent<Animator> ().SetBool ("chargekalah", true);
//bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
//aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("attack",QueueMode.PlayNow);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("nangkis",QueueMode.PlayNow);
yield return new WaitForSeconds (.5f);
Seri_Adef.Play ();
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle",QueueMode.PlayNow,PlayMode.StopAll);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("attack");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("hit");
yield return new WaitForSeconds (0.5f);
damageB.gameObject.SetActive (true);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
HealthReduction (urutan,1,damage);
yield return new WaitForSeconds (0.1f);
B.Play ();
hitYa.Play ();
}
else if (pilA == "Block" && pilB == "Focus") {
Debug.Log ("BF");
damage = bObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().damage- aObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().defend/2;
if (damage <= 0) {
damage = 0;
}
damageA.text = "- "+damage.ToString ();
damageB.text = "- "+damage.ToString ();
Bobject.GetComponent<Animator> ().SetBool ("win", true);
Aobject.GetComponent<Animator> ().SetBool ("blokkalah", true);
//aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
//bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued("charge");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
Charge_B.Play ();
yield return new WaitForSeconds (1f);
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("attack");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("nangkis_loss");
yield return new WaitForSeconds (0.5f);
damageA.gameObject.SetActive (true);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
yield return new WaitForSeconds (0.3f);
HealthReduction (urutan,0,damage);
A.Play ();
hitYa.Play ();
}
else if (pilA == "Focus" && pilB == "Block") {
Debug.Log ("FB");
damage = aObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().damage- bObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().defend/2;
if (damage <= 0) {
damage = 0;
}damageA.text = "- "+damage.ToString ();
damageB.text = "- "+damage.ToString ();
Aobject.GetComponent<Animator> ().SetBool ("win", true);
Bobject.GetComponent<Animator> ().SetBool ("blokkalah", true);
//bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
//aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle",QueueMode.PlayNow);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("charge",QueueMode.PlayNow);
Charge_A.Play ();
//
// aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
// bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
yield return new WaitForSeconds (1f);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("attack");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("nangkis_loss");
yield return new WaitForSeconds (0.5f);
damageB.gameObject.SetActive (true);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
yield return new WaitForSeconds (0.3f);
HealthReduction (urutan,1,damage);
B.Play ();
hitYa.Play ();
}
else if (pilA == "Focus" && pilB == "Charge") {
Debug.Log ("FC");
damage = bObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().damage- aObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().defend/2;
if (damage <= 0) {
damage = 0;
}damageA.text = "- "+damage.ToString ();
damageB.text = "- "+damage.ToString ();
Bobject.GetComponent<Animator> ().SetBool ("win", true);
Aobject.GetComponent<Animator> ().SetBool ("fokuskalah", true);
//aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
//bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("charge",QueueMode.PlayNow);
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle",QueueMode.PlayNow);
Charge_A.Play ();
// aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
// bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
yield return new WaitForSeconds (.5f);
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("attack");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("hit");
yield return new WaitForSeconds (0.5f);
damageA.gameObject.SetActive (true);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
yield return new WaitForSeconds (0.3f);
HealthReduction (urutan,0,damage);
A.Play ();
hitYa.Play ();
} else if (pilA == "Charge" && pilB == "Focus") {
Debug.Log ("CF");
damage = aObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().damage- bObject.transform.Find ("Canvas").transform.Find ("Image").GetComponent<filled> ().defend/2;
if (damage <= 0) {
damage = 0;
}damageA.text = "- "+damage.ToString ();
damageB.text = "- "+damage.ToString ();
Aobject.GetComponent<Animator> ().SetBool ("win", true);
Bobject.GetComponent<Animator> ().SetBool ("fokuskalah", true);
//bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
//aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued("charge",QueueMode.PlayNow);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
Charge_B.Play ();
// aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
// bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
yield return new WaitForSeconds (.5f);
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("attack");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("hit");
yield return new WaitForSeconds (0.5f);
damageB.gameObject.SetActive (true);
//
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
yield return new WaitForSeconds (0.1f);
HealthReduction (urutan,1,damage);
B.Play ();
hitYa.Play ();
}
else if (pilA == "Focus" && pilB == "Focus") {
//bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
//aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("charge");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("charge");
// aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
// bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
//
Bobject.GetComponent<Animator> ().SetBool ("fokuskalah", true);
Aobject.GetComponent<Animator> ().SetBool ("fokuskalah", true);
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("draw");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("draw");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
//Seri_A.Play ();
yield return new WaitForSeconds (.5f);
Seri_A.Play ();
}
else if (pilA == "Charge" && pilB == "Charge") {
//bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
//aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("charge");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("charge");
// aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
// bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
//
Bobject.GetComponent<Animator> ().SetBool ("chargekalah", true);
Aobject.GetComponent<Animator> ().SetBool ("chargekalah", true);
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("draw");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("draw");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
//Seri_A.Play ();
yield return new WaitForSeconds (.5f);
Seri_A.Play ();
}
else if (pilA == "Block" && pilB == "Block") {
//bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
//aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().Play ("maju");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("charge");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("charge");
// aObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
// bObject.transform.FindChild ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
//
Bobject.GetComponent<Animator> ().SetBool ("blokkalah", true);
Aobject.GetComponent<Animator> ().SetBool ("blokkalah", true);
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("draw");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().Play ("draw");
aObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
bObject.transform.Find ("COPY_POSITION").transform.Find ("Genderuwo_Fire").GetComponent<Animation> ().PlayQueued ("idle");
//Seri_A.Play ();
yield return new WaitForSeconds (.5f);
Seri_A.Play ();
}
yield return new WaitForSeconds (.5f);
aObject.transform.Find ("Select").GetComponent<SpriteRenderer>().sprite = null;
bObject.transform.Find ("Select").GetComponent<SpriteRenderer>().sprite = null;
aObject.GetComponent<PlayAnimation> ().PlayBalik();
bObject.GetComponent<PlayAnimation> ().PlayBalik();
Aobject.GetComponent<Animator> ().SetBool ("LeftFight", false);
Bobject.GetComponent<Animator> ().SetBool ("RightFight", false);
Aobject.GetComponent<Animator> ().SetBool ("blokkalah", false);
Bobject.GetComponent<Animator> ().SetBool ("blokkalah", false);
Aobject.GetComponent<Animator> ().SetBool ("chargekalah", false);
Bobject.GetComponent<Animator> ().SetBool ("chargekalah", false);
Aobject.GetComponent<Animator> ().SetBool ("fokuskalah", false);
Bobject.GetComponent<Animator> ().SetBool ("fokuskalah", false);
Aobject.GetComponent<Animator> ().SetBool ("FightCharge", false);
Bobject.GetComponent<Animator> ().SetBool ("FightCharge", false);
Aobject.GetComponent<Animator> ().SetBool ("FightFocus", false);
Bobject.GetComponent<Animator> ().SetBool ("FightFocus", false);
Aobject.GetComponent<Animator> ().SetBool ("FightBlock", false);
Bobject.GetComponent<Animator> ().SetBool ("FightBlock", false);
Bobject.GetComponent<Animator> ().SetBool ("win", false);
Aobject.GetComponent<Animator> ().SetBool ("win", false);
damageA.gameObject.SetActive (false);
damageB.gameObject.SetActive (false);
//
// pilihanInputSuit [0].SetActive (true);
// pilihanInputSuit [1].SetActive (true);
// pilihanInputSuit [2].SetActive (true);
// Aaobject.GetComponent<Animator> ().SetBool ("LeftFight", false);
// Baobject.GetComponent<Animator> ().SetBool ("RightFight", false);
}
public Sprite half;
public Sprite empty;
public void HealthReduction (int urutan, int player,float damaged) {
Debug.Log ("Health Reduction"+Bb+player);
if (urutan == 1) {
if (player == 1) {
//health1 [1] = health1 [1] - damaged;
healthBar1 [1].GetComponent<filled> ().currenthealth = healthBar1 [1].GetComponent<filled> ().currenthealth - damaged;
//healthBar1 [1].GetComponent<filled> ().currenthealth = health1 [1];
//healthBar1[1].GetComponent<filled>().currenthealth = healthBar1[1].GetComponent<filled>().currenthealth - damaged;
if (healthBar1 [1].GetComponent<filled> ().currenthealth <=0) {
repeat = false;
if (Bb == false) {
Ab = true;
Debug.Log ("Its Done Dude, A is the Winner");
}
//healthBar1 [1].GetComponent<SpriteRenderer> ().sprite = empty;
}
//healthBar1[1].transform.localScale = new Vector3(health1[1], healthBar1[1].transform.localScale.y, healthBar1[1].transform.localScale.z);
} else {
//healthBar1[0].GetComponent<filled>().currenthealth = healthBar1[0].GetComponent<filled>().currenthealth - damaged;
//health1 [0] = health1 [0] - damaged;
// healthBar1 [0].GetComponent<filled> ().currenthealth = health1 [0];
healthBar1 [0].GetComponent<filled> ().currenthealth= healthBar1 [0].GetComponent<filled> ().currenthealth-damaged;
//health1 [0] = health1 [0] - damaged;
//healthBar1 [0].transform.localScale = new Vector3 (health1 [0], healthBar1 [0].transform.localScale.y, healthBar1 [0].transform.localScale.z);
if (healthBar1 [0].GetComponent<filled> ().currenthealth <= 0) {
repeat = false;
if (Ab == false) {
Bb = true;
Debug.Log ("Its Done Dude, B is the Winner");
}
//healthBar1 [0].GetComponent<SpriteRenderer> ().sprite = empty;
}
}
} else if (urutan == 2) {
if (player == 1) {
// health2 [1] = health2 [1] - damaged;
//health2 [1] = health2 [1] - damaged;
healthBar2 [1].GetComponent<filled> ().currenthealth = healthBar2 [1].GetComponent<filled> ().currenthealth-damaged;
//healthBar2[1].GetComponent<filled>().currenthealth = healthBar2[1].GetComponent<filled>().currenthealth - damaged;
//healthBar2[1].transform.localScale = new Vector3(health2[1], healthBar2[1].transform.localScale.y, healthBar2[1].transform.localScale.z);
if (healthBar2 [1].GetComponent<filled> ().currenthealth <= 0) {
repeat = false;
if (Bb == false) {
Ab = true;
Debug.Log ("Its Done Dude A is the Winner");
}
//healthBar2 [1].GetComponent<SpriteRenderer> ().sprite = empty;
}
} else {
//health2 [0] = health2 [0] - damaged;
//health2 [0] = health2 [0] - damaged;
healthBar2 [0].GetComponent<filled> ().currenthealth = healthBar2 [0].GetComponent<filled> ().currenthealth - damaged;
//healthBar2[0].GetComponent<filled>().currenthealth = healthBar2[0].GetComponent<filled>().currenthealth - damaged;
//healthBar2 [0].transform.localScale = new Vector3 (health2 [0], healthBar2 [0].transform.localScale.y, healthBar2 [0].transform.localScale.z);
if (healthBar2 [0].GetComponent<filled> ().currenthealth <= 0) {
repeat = false;
if (Ab == false) {
Bb = true;
Debug.Log ("Its Done Dude B is the Winner");
}
//healthBar2 [0].GetComponent<SpriteRenderer> ().sprite = empty;
}
}
} else {
if (player == 1) {
//health3 [1] = health3 [1] - damaged;
//health3 [1] = health3 [1] - damaged;
healthBar3 [1].GetComponent<filled> ().currenthealth = healthBar3 [1].GetComponent<filled> ().currenthealth - damaged;
//healthBar3[1].GetComponent<filled>().currenthealth = healthBar3[1].GetComponent<filled>().currenthealth - damaged;
//healthBar3[1].transform.localScale = new Vector3(health3[1], healthBar3[1].transform.localScale.y, healthBar3[1].transform.localScale.z);
if (healthBar3 [1].GetComponent<filled> ().currenthealth <= 0) {
repeat = false;
if (Bb == false) {
Ab = true;
Debug.Log ("Its Done Dude A is the Winner");
}
//healthBar3 [1].GetComponent<SpriteRenderer> ().sprite = empty;
}
} else {
// health3 [0] = health3 [0] - damaged;
healthBar3 [0].GetComponent<filled> ().currenthealth = healthBar3 [0].GetComponent<filled> ().currenthealth - damaged;
//healthBar3 [0].transform.localScale = new Vector3 (health3 [0], healthBar3 [0].transform.localScale.y, healthBar3 [0].transform.localScale.z);
if (healthBar3 [0].GetComponent<filled> ().currenthealth <= 0) {
repeat = false;
if (Ab == false) {
Bb = true;
Debug.Log ("Its Done Dude B is the Winner");
}
// healthBar3 [0].GetComponent<SpriteRenderer> ().sprite = empty;
}
}
}
}
public void Replay () {
if (PlayerPrefs.GetString (Link.JENIS) != "SINGLE") {
Application.LoadLevel (Link.Arena);
} else {
Application.LoadLevel (Link.Game);
}
}
public void Map () {
if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") {
PlayerPrefs.SetString ("Tutorgame", "TRUE");
}
Application.LoadLevel (Link.Map);
}
public void GameSpeed(int speed){
Time.timeScale = speed;
}
public int[] ItemRate;
public string[] ItemQuantity;
public string[] ItemType;
public string[] ItemName;
public int weightTotal;
void SetReward () {
ItemRate = new int[3]; //number of things
ItemName = new string[3];
//weighting of each thing, high number means more occurrance
for(int i = 0; i<3;i++)
{
ItemQuantity[i] = PlayerPrefs.GetString("RewardItemQuantity"+i.ToString());
ItemType[i] = PlayerPrefs.GetString("RewardItemType"+i.ToString());
ItemName[i] = PlayerPrefs.GetString("RewardItemName"+i.ToString());
ItemRate[i] = int.Parse(PlayerPrefs.GetString("RewardItemRate"+i.ToString()));
}
weightTotal = 0;
foreach ( int w in ItemRate ) {
weightTotal += w;
}
}
public void getresult()
{
var result = RandomWeighted ();
}
int RandomWeighted () {
int result = 0, total = 0;
int randVal = Random.Range( 0, weightTotal );
for ( result = 0; result < ItemRate.Length; result++ ) {
total += ItemRate[result];
if ( total > randVal ) break;
}
return result;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Level8 : MonoBehaviour
{
public List<GameObject> solutionButtons;
public List<GameObject> solutionFigures;
public Color figureClickColor;
private float changeColorDuration = 0.5f;
private bool isRunning = false;
private int counter = 0;
private GameObject lastGo;
private void Start()
{
ClickListener.ObjClicked += CheckClick;
}
private void OnDestroy()
{
ClickListener.ObjClicked -= CheckClick;
}
private void CheckClick(GameObject go)
{
if (isRunning && ReferenceEquals(lastGo, go))
{
AudioManager.instance.Play("Reset");
return;
}
if (solutionButtons[counter].gameObject == go)
{
//change sprite color with self distruct corutine
//inc counter
StartCoroutine(ChangeSpriteColor(solutionFigures[counter].gameObject));
counter++;
}
else
{
//clear counter
counter = 0;
AudioManager.instance.Play("Reset");
}
lastGo = go;
CheckWin();
}
private void CheckWin()
{
if (counter == solutionButtons.Count)
{
Debug.Log("Win");
GameManager.instance.NextLevel();
}
}
private IEnumerator ChangeSpriteColor(GameObject go)
{
isRunning = true;
var sr = go.GetComponent<SpriteRenderer>();
var originalColor = sr.color;
float t = 0;
while (t < changeColorDuration)
{
t += Time.deltaTime;
sr.color = Color.Lerp(figureClickColor, originalColor, t / changeColorDuration);
yield return null;
}
isRunning = false;
}
} |
using AutoFixture;
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Web.Mappers.Cohort;
using System.Threading.Tasks;
using Moq;
using SFA.DAS.CommitmentsV2.Types;
using SFA.DAS.ProviderCommitments.Web.Mappers;
using SFA.DAS.ProviderCommitments.Web.Models;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Cohort
{
[TestFixture]
public class WhenIMapCreateCohortWithAddDraftApprenticeshipViewModelToSelectDeliveryModelViewModel
{
private SelectDeliveryModelViewModelFromCreateCohortWithDraftApprenticeshipRequestMapper _mapper;
private Mock<ISelectDeliveryModelMapperHelper> _helper;
private SelectDeliveryModelViewModel _model;
private CreateCohortWithDraftApprenticeshipRequest _request;
[SetUp]
public void Arrange()
{
var fixture = new Fixture();
_request = fixture.Create<CreateCohortWithDraftApprenticeshipRequest>();
_model = fixture.Create<SelectDeliveryModelViewModel>();
_helper = new Mock<ISelectDeliveryModelMapperHelper>();
_helper.Setup(x => x.Map(It.IsAny<long>(), It.IsAny<string>(), It.IsAny<long>(), It.IsAny<DeliveryModel?>(), It.IsAny<bool?>())).ReturnsAsync(_model);
_mapper = new SelectDeliveryModelViewModelFromCreateCohortWithDraftApprenticeshipRequestMapper(_helper.Object);
}
[Test]
public async Task TheParamsArePassedInCorrectly()
{
await _mapper.Map(_request);
_helper.Verify(x=>x.Map(_request.ProviderId, _request.CourseCode, _request.AccountLegalEntityId, _request.DeliveryModel, _request.IsOnFlexiPaymentPilot));
}
[Test]
public async Task ThenModelIsReturned()
{
var result = await _mapper.Map(_request);
Assert.AreEqual(_model, result);
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
public class AgentController : MonoBehaviour {
// needed variables - public one are for easy changing via the inspector
public int target;
public int speed;
public bool useGraph;
protected Vector3 a, b;
protected float startTime, aToB;
protected IGraph graph;
protected int currentWaypoint;
protected Queue<int> path;
protected GameObject waypointSet;
protected bool arrived;
// Use this for initialization
void Start () {
startTime = Time.time;
a = transform.position;
waypointSet = GameObject.Find ("WaypointSet"); // gets gameobject data from WaypointSet
int numWaypoints = waypointSet.GetComponent<WaypointSet> ().getCount (); // gets the number of waypoints
int closestWaypoint = -1; // for setting what the closewaypoint is as it'll be the start point for the graph search
path = new Queue<int> ();
// this makes it so that this conforms to the requirements of lab3-5
if (useGraph) {
float smallest = 99999999; // an arbitrary large number to compare against in the beginning
for (int i = 0; i < numWaypoints; i++) {
// this goes through all the waypoints in waypoint set and gets their game world position
Vector3 t = waypointSet.GetComponent<WaypointSet> ().getWaypointPosition (i);
float current = Vector3.Distance (a, t); // gets the distance to the current waypoint being checked
// checks if the current distance is the smallest and if so sets that waypoint to be the closest
if (current > 0 && current < smallest) {
smallest = current;
closestWaypoint = i;
}
}
// the b vector is then set to the position of the closest waypoint
b = waypointSet.GetComponent<WaypointSet> ().getWaypointPosition (closestWaypoint);
aToB = Vector3.Distance (a, b); // sets distance from a to b from vectors a and b
//Debug.Log("Smallest distance is " + smallest);
//Debug.Log ("The closest waypoint is " + closestWaypoint);
// A graph search is needed now to find the best path to the target waypoint
graph = waypointSet.GetComponent<WaypointSet> ().getGraph ();
//BFS bfs = new BFS ();
//bfs.setGraph (graph);
//List<int> p = bfs.findPath (closestWaypoint, target, true);
AStarSearch aStar = new AStarSearch ();
aStar.setGraph (graph);
List<int> p = aStar.findPath (closestWaypoint, target, true);
if (p != null) {
string s = "";
for(int i = 0; i < p.Count; i++) {
if (i > 0) s += ", ";
s += p[i];
}
Debug.Log ("Path found: " + s);
} else {
Debug.Log ("No path found");
}
foreach (int j in p)
path.Enqueue(j);
currentWaypoint = path.Dequeue();
//Debug.Log ("Current waypoint is: " + currentWaypoint);
//Debug.Log("Next waypoint is: " + path.Peek());
} else {
// performs as in lab3-4 and moves straight to the target waypoint
b = waypointSet.GetComponent<WaypointSet> ().getWaypointPosition (target);
aToB = Vector3.Distance (a, b);
}
arrived = false; // allows movement
}
// Update is called once per frame
void Update () {
// moves agent only when it hasn't arrived at it's destination
if (!arrived) {
// implementation of linear interpolation
float soFar = (Time.time - startTime) * speed;
float done = soFar / aToB;
transform.position = Vector3.Lerp (a, b, done);
if (transform.position == b){ // this checks if the agent has reach it's current target
arrived = true; // and if so sets the arrived boolean to true
if (currentWaypoint == target)
Debug.Log("Arrived at target");
}
} else {// this runs when the agents reaches it's current target
if (currentWaypoint != target){ // checks if the main target has been reached and if not the next target is set
if (path.Count != 0){ // checks if the path queue is empty
int next = path.Dequeue(); // sets the next waypoint from the front of the queue
Debug.Log ("Moving to waypoint " + next);
startTime = Time.time; // sets a new start time for the lerp
// gets vectors a & b which correspond to the agent (a) and the next waypoint (b)
a = transform.position;
b = waypointSet.GetComponent<WaypointSet>().getWaypointPosition(next);
aToB = Vector3.Distance (a, b); // derives distance between waypoints
currentWaypoint = next; // updates the current waypoint with the new soon to be current
arrived = false; // allows movement again
}
}
}
}
}
|
using EAN.GPD.Infrastructure.Database;
using EAN.GPD.Infrastructure.Database.SqlClient;
using System;
using System.Linq;
using System.Reflection;
namespace EAN.GPD.Domain.Entities
{
public class BaseEntity
{
private readonly string nameTable;
public BaseEntity(string nameTable, long? id = null)
{
this.nameTable = nameTable;
if (id.HasValue && id.Value > 0)
{
LoadObject(id.Value);
}
}
public string GetNameTable() => nameTable;
public string GetNameSequence() => $"Seq{nameTable}";
public string GetNamePrimaryKey() => $"Id{nameTable}";
private void LoadObject(long id)
{
var data = DatabaseProvider.GetAllById(nameTable, GetNamePrimaryKey(), id).GetAll().FirstOrDefault();
if (data is null || !data.Any())
{
throw new Exception($"No result for query by id in '{nameTable}' value id '{id}'.");
}
var props = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
var column = prop.GetCustomAttribute<Column>();
if (column != null)
{
string name = (column.Name ?? prop.Name).Trim().ToUpper();
if (data.ContainsKey(name))
{
object value = data[name];
if (prop.PropertyType == typeof(bool))
{
prop.SetValue(this, Convert.ToChar(value) == 'S');
}
else
{
prop.SetValue(this, value == DBNull.Value ? null : value);
}
}
}
}
foreach (var prop in props)
{
var joinColumn = prop.GetCustomAttribute<JoinColumn>();
if (joinColumn != null)
{
string name = joinColumn.NameColumnReference.Trim().ToUpper();
if (data.ContainsKey(name))
{
object value = data[name];
if (value != DBNull.Value)
{
var newObjectJoin = Activator.CreateInstance(prop.PropertyType, Convert.ToInt64(value));
prop.SetValue(this, newObjectJoin);
}
}
}
}
}
private void SetPersistenceEntity(IPersistenceEntity persistenceEntity)
{
var props = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
var column = prop.GetCustomAttribute<Column>();
if (column != null)
{
string name = column.Name ?? prop.Name;
if (name == GetNamePrimaryKey())
{
continue;
}
object value = prop.GetValue(this);
if (prop.PropertyType == typeof(string))
{
if (value is null)
{
if (column.StringNotNullable)
{
throw new Exception($"String nullable in property column: '{prop.Name}'.");
}
persistenceEntity.AddColumn(name, DBNull.Value);
}
else
{
if (column.StringMaxLenght > 0)
{
int maxLenghtString = value.ToString().Length;
if (maxLenghtString > column.StringMaxLenght)
{
throw new Exception($"String max capacity lenght in property column: '{prop.Name}'.");
}
}
persistenceEntity.AddColumn(name, value);
}
}
else
{
if (value is null)
{
persistenceEntity.AddColumn(name, DBNull.Value);
}
else
{
if (value.GetType() == typeof(bool))
{
persistenceEntity.AddColumn(name, Convert.ToBoolean(value) ? 'S' : 'N');
}
else
{
persistenceEntity.AddColumn(name, value);
}
}
}
}
}
}
public long Save(long? id = null)
{
long result = id ?? GetSequence();
if (id.HasValue)
{
var persistence = DatabaseProvider.NewPersistenceEntity(TypePersistence.Update, nameTable, GetNamePrimaryKey(), result);
SetPersistenceEntity(persistence);
persistence.Execute();
}
else
{
var persistence = DatabaseProvider.NewPersistenceEntity(TypePersistence.Insert, nameTable, GetNamePrimaryKey(), result);
SetPersistenceEntity(persistence);
persistence.Execute();
id = result;
}
return result;
}
private long GetSequence() => DatabaseProvider.NewSequence(GetNameSequence());
public static void Delete<TEntity>(long id) where TEntity : BaseEntity
{
var entity = (TEntity)Activator.CreateInstance(typeof(TEntity));
string nameTable = entity.GetNameTable();
string namePrimaryKey = entity.GetNamePrimaryKey();
var persistence = DatabaseProvider.NewPersistenceEntity(TypePersistence.Delete, nameTable, namePrimaryKey, id);
persistence.Execute();
}
public static long GetSequence<TEntity>() where TEntity : BaseEntity
{
var entity = (TEntity)Activator.CreateInstance(typeof(TEntity));
return DatabaseProvider.NewSequence(entity.GetNameSequence());
}
}
} |
using eCommerceSE.Cliente;
using eCommerceSE.Model;
using System;
using System.Configuration;
using System.Web.UI;
namespace Enviosbase.EstadoPedido
{
public partial class EstadoPedidoEdit : System.Web.UI.Page
{
string llave = ConfigurationManager.AppSettings["Usuario"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IdUsuario"] == null)
{
Response.Redirect("/Login.aspx");
}
if (!Page.IsPostBack)
{
if (Request.QueryString["Id"] != null)
{
int id = int.Parse(Request.QueryString["Id"]);
EstadoPedidoModel obj = new EstadoPedidoCliente(llave).GetById(id);
lbId.Text = obj.Id.ToString();
txtNombre.Text = obj.Nombre;
hdEstado.Value = obj.Estado.ToString();
}
else
{
hdEstado.Value = true.ToString();
}
if (Request.QueryString["View"] == "0")
{
Business.Utils.DisableForm(Controls);
btnCancel.Enabled = true;
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
EstadoPedidoModel obj;
EstadoPedidoCliente business = new EstadoPedidoCliente(llave);
obj = new EstadoPedidoModel();
obj.Nombre = txtNombre.Text;
obj.Estado = bool.Parse(hdEstado.Value);
obj.FechaRegistro = DateTime.Now;
if (Request.QueryString["Id"] != null)
{
obj.Id = int.Parse(Request.QueryString["Id"]);
business.Update(obj);
}
else
{
business.Create(obj);
}
ltScripts.Text = Business.Utils.MessageBox("Atención", "El registro ha sido guardado exitósamente", "EstadoPedidoList.aspx", "success");
}
catch (Exception)
{
ltScripts.Text = Business.Utils.MessageBox("Atención", "No pudo ser guardado el registro, por favor verifique su información e intente nuevamente", null, "error");
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("EstadoPedidoList.aspx");
}
}
}
|
using Alabo.Domains.Entities;
using Alabo.Domains.Services;
using Alabo.Framework.Basic.Relations.Domain.Entities;
using Alabo.Framework.Basic.Relations.Dtos;
using Alabo.Framework.Core.WebUis.Models.Links;
using System;
using System.Collections.Generic;
namespace Alabo.Framework.Basic.Relations.Domain.Services {
public interface IRelationService : IService<Relation, long> {
/// <summary>
/// 检查分类是否存在
/// </summary>
/// <param name="script"></param>
bool CheckExist(string script);
/// <summary>
/// 获取所有的级联类型
/// </summary>
IEnumerable<Type> GetAllTypes();
/// <summary>
/// 获取所有的分类类型
/// </summary>
IEnumerable<Type> GetAllClassTypes();
/// <summary>
/// 获取所有的标签类型
/// </summary>
IEnumerable<Type> GetAllTagTypes();
/// <summary>
/// 根据类型获取所有的分类
/// </summary>
/// <param name="type"></param>
IEnumerable<RelationApiOutput> GetClass(string type);
/// <summary>
/// 根据类型获取所有的分类
/// </summary>
/// <param name="type"></param>
IEnumerable<RelationApiOutput> GetClass(string type, long userId);
/// <summary>
/// 根据类型获取所有的父级分类
/// </summary>
/// <param name="type"></param>
IEnumerable<RelationApiOutput> GetFatherClass(string type);
/// <summary>
/// 根据类型获取所有的字典类型,包括标签与分类
/// </summary>
/// <param name="type"></param>
IEnumerable<KeyValue> GetFatherKeyValues(string type);
/// <summary>
/// 根据类型获取所有的标签
/// </summary>
/// <param name="type"></param>
IEnumerable<RelationApiOutput> GetTag(string type);
/// <summary>
/// 根据类型获取所有的字典类型,包括标签与分类
/// </summary>
/// <param name="type"></param>
IEnumerable<KeyValue> GetKeyValues(string type);
/// <summary>
/// 根据类型获取所有的字典类型,包括标签与分类
/// 和上面的方法一样,只是key和value的方式不一样,调换下
/// </summary>
/// <param name="type"></param>
IEnumerable<KeyValue> GetKeyValues2(string type);
/// <summary>
/// </summary>
/// <param name="type"></param>
/// <param name="userId"></param>
/// <returns></returns>
IEnumerable<KeyValue> GetKeyValues(string type, long userId);
/// <summary>
/// 查找类型
/// </summary>
/// <param name="typeName"></param>
Type FindType(string typeName);
/// <summary>
/// 获取所有分类的链接地址
/// </summary>
/// <returns></returns>
List<Link> GetClassLinks();
/// <summary>
/// 获取所有标签的链接地址
/// </summary>
/// <returns></returns>
List<Link> GetTagLinks();
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace DrugManufacturing.Models
{
public class Registration
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[MinLength(8)]
public string Password1 { get; set; }
[Required]
public string Password2 { get; set; }
[Required]
[MinLength(2)]
public string Name { get; set; }
[Required]
[MinLength(2)]
public string Country { get; set; }
[Required]
[MinLength(2)]
public string City { get; set; }
[Required]
[MinLength(2)]
public string StreetAddress { get; set; }
[Required]
public string RegistrationType { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Aquamonix.Mobile.Lib.Extensions;
namespace Aquamonix.Mobile.Lib.Domain
{
[DataContract]
public class DeviceType
{
[DataMember(Name = PropertyNames.Name)]
public string Name { get; set; }
[DataMember(Name = PropertyNames.Settings)]
public ItemsDictionary<DeviceSetting> Settings { get; set; }
[DataMember(Name = PropertyNames.Features)]
public ItemsDictionary<DeviceFeature> Features { get; set; }
public void ReadyChildIds()
{
this.Settings?.ReadyDictionary();
this.Features?.ReadyDictionary();
//DomainObjectWithId.ReadyChildIdsDictionary(this.Settings);
//DomainObjectWithId.ReadyChildIdsDictionary(this.Features);
}
}
}
|
using BDTest.NetCore.Razor.ReportMiddleware.Interfaces;
using Microsoft.AspNetCore.Http;
namespace BDTest.NetCore.Razor.ReportMiddleware.Implementations;
public class NoOpAdminAuthorizer : IAdminAuthorizer
{
public Task<bool> IsAdminAsync(HttpContext httpContext)
{
return Task.FromResult(false);
}
} |
namespace CaseManagement.DataObjects
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Agency")]
public partial class Agency
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Agency()
{
ClientVisitReferrals = new HashSet<ClientVisitReferral>();
}
public int agencyId { get; set; }
[Required]
[StringLength(255)]
public string name { get; set; }
[JsonIgnore]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ClientVisitReferral> ClientVisitReferrals { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using JDWinService.Utils;
using JDWinService.Model;
using System.Data.SqlClient;
namespace JDWinService.Dal
{
public class JD_SePriceApply_LogDal
{
public static string connectionString = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["ConnectionString"].Value; //连接信息
Common common = new Common();
public JD_SePriceApply_Log Detail(int ItemID)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM JD_SePriceApply_Log WHERE ItemID = @m_ItemID", con);
con.Open();
cmd.Parameters.Add(new SqlParameter("@m_ItemID", SqlDbType.Int, 0)).Value = ItemID;
JD_SePriceApply_Log myDetail = new JD_SePriceApply_Log();
SqlDataReader myReader = cmd.ExecuteReader();
if (myReader.Read())
{
if (!Convert.IsDBNull(myReader["ItemID"])) { myDetail.ItemID = Convert.ToInt32(myReader["ItemID"]); }
if (!Convert.IsDBNull(myReader["ParentID"])) { myDetail.ParentID = Convert.ToInt32(myReader["ParentID"]); }
if (!Convert.IsDBNull(myReader["Operater"])) { myDetail.Operater = Convert.ToString(myReader["Operater"]); }
if (!Convert.IsDBNull(myReader["CreateTime"])) { myDetail.CreateTime = Convert.ToDateTime(myReader["CreateTime"]); }
if (!Convert.IsDBNull(myReader["IsUpdate"])) { myDetail.IsUpdate = Convert.ToString(myReader["IsUpdate"]); }
if (!Convert.IsDBNull(myReader["ShortName"])) { myDetail.ShortName = Convert.ToString(myReader["ShortName"]); }
if (!Convert.IsDBNull(myReader["CustomCode"])) { myDetail.CustomCode = Convert.ToString(myReader["CustomCode"]); }
if (!Convert.IsDBNull(myReader["CustomName"])) { myDetail.CustomName = Convert.ToString(myReader["CustomName"]); }
if (!Convert.IsDBNull(myReader["FNumber"])) { myDetail.FNumber = Convert.ToString(myReader["FNumber"]); }
if (!Convert.IsDBNull(myReader["FModel"])) { myDetail.FModel = Convert.ToString(myReader["FModel"]); }
if (!Convert.IsDBNull(myReader["CoinType"])) { myDetail.CoinType = Convert.ToString(myReader["CoinType"]); }
if (!Convert.IsDBNull(myReader["BeginSalesCount"])) { myDetail.BeginSalesCount = Convert.ToDecimal(myReader["BeginSalesCount"]); }
if (!Convert.IsDBNull(myReader["EndSalesCount"])) { myDetail.EndSalesCount = Convert.ToDecimal(myReader["EndSalesCount"]); }
if (!Convert.IsDBNull(myReader["Price"])) { myDetail.Price = Convert.ToDecimal(myReader["Price"]); }
if (!Convert.IsDBNull(myReader["BeginTime"])) { myDetail.BeginTime = Convert.ToDateTime(myReader["BeginTime"]); }
if (!Convert.IsDBNull(myReader["EndTime"])) { myDetail.EndTime = Convert.ToDateTime(myReader["EndTime"]); }
if (!Convert.IsDBNull(myReader["IsNew"])) { myDetail.IsNew = Convert.ToString(myReader["IsNew"]); }
if (!Convert.IsDBNull(myReader["MOQ"])) { myDetail.MOQ = Convert.ToDecimal(myReader["MOQ"]); }
if (!Convert.IsDBNull(myReader["LimitTimes"])) { myDetail.LimitTimes = Convert.ToString(myReader["LimitTimes"]); }
if (!Convert.IsDBNull(myReader["CaiWuRemarks"])) { myDetail.CaiWuRemarks = Convert.ToString(myReader["CaiWuRemarks"]); }
if (!Convert.IsDBNull(myReader["PlanRemarks"])) { myDetail.PlanRemarks = Convert.ToString(myReader["PlanRemarks"]); }
if (!Convert.IsDBNull(myReader["ApplyType"])) { myDetail.ApplyType = Convert.ToString(myReader["ApplyType"]); }
}
myReader.Close();
cmd.Dispose();
con.Close();
con.Dispose();
return myDetail;
}
/// <summary>
/// 新增JD_SePriceApply_Log对象
/// 编写人:ywk
/// 编写日期:2018/7/26 星期四
/// </summary>
public int Add(JD_SePriceApply_Log model)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO JD_SePriceApply_Log(ParentID,Operater,CreateTime,IsUpdate,ShortName,CustomCode,CustomName,FNumber,FModel,CoinType,BeginSalesCount,EndSalesCount,Price,BeginTime,EndTime,IsNew,MOQ,LimitTimes,CaiWuRemarks,PlanRemarks,ApplyType,TaskID) VALUES(@m_ParentID,@m_Operater,@m_CreateTime,@m_IsUpdate,@m_ShortName,@m_CustomCode,@m_CustomName,@m_FNumber,@m_FModel,@m_CoinType,@m_BeginSalesCount,@m_EndSalesCount,@m_Price,@m_BeginTime,@m_EndTime,@m_IsNew,@m_MOQ,@m_LimitTimes,@m_CaiWuRemarks,@m_PlanRemarks,@m_ApplyType,@m_TaskID) SELECT @thisId=@@IDENTITY FROM JD_SePriceApply_Log", con);
con.Open();
if (model.ParentID == null)
{
cmd.Parameters.Add(new SqlParameter("@m_ParentID", SqlDbType.Int, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_ParentID", SqlDbType.Int, 0)).Value = model.ParentID;
}
if (model.Operater == null)
{
cmd.Parameters.Add(new SqlParameter("@m_Operater", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_Operater", SqlDbType.NVarChar, 50)).Value = model.Operater;
}
if (model.CreateTime == new DateTime())
{
cmd.Parameters.Add(new SqlParameter("@m_CreateTime", SqlDbType.DateTime, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CreateTime", SqlDbType.DateTime, 0)).Value = model.CreateTime;
}
if (model.IsUpdate == null)
{
cmd.Parameters.Add(new SqlParameter("@m_IsUpdate", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_IsUpdate", SqlDbType.NVarChar, 50)).Value = model.IsUpdate;
}
if (model.ShortName == null)
{
cmd.Parameters.Add(new SqlParameter("@m_ShortName", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_ShortName", SqlDbType.NVarChar, 50)).Value = model.ShortName;
}
if (model.CustomCode == null)
{
cmd.Parameters.Add(new SqlParameter("@m_CustomCode", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CustomCode", SqlDbType.NVarChar, 50)).Value = model.CustomCode;
}
if (model.CustomName == null)
{
cmd.Parameters.Add(new SqlParameter("@m_CustomName", SqlDbType.NVarChar, 100)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CustomName", SqlDbType.NVarChar, 100)).Value = model.CustomName;
}
if (model.FNumber == null)
{
cmd.Parameters.Add(new SqlParameter("@m_FNumber", SqlDbType.NVarChar, 100)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_FNumber", SqlDbType.NVarChar, 100)).Value = model.FNumber;
}
if (model.FModel == null)
{
cmd.Parameters.Add(new SqlParameter("@m_FModel", SqlDbType.NVarChar, 500)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_FModel", SqlDbType.NVarChar, 500)).Value = model.FModel;
}
if (model.CoinType == null)
{
cmd.Parameters.Add(new SqlParameter("@m_CoinType", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CoinType", SqlDbType.NVarChar, 50)).Value = model.CoinType;
}
if (model.BeginSalesCount == null)
{
cmd.Parameters.Add(new SqlParameter("@m_BeginSalesCount", SqlDbType.Decimal, 18)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_BeginSalesCount", SqlDbType.Decimal, 18)).Value = model.BeginSalesCount;
}
if (model.EndSalesCount == null)
{
cmd.Parameters.Add(new SqlParameter("@m_EndSalesCount", SqlDbType.Decimal, 18)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_EndSalesCount", SqlDbType.Decimal, 18)).Value = model.EndSalesCount;
}
if (model.Price == null)
{
cmd.Parameters.Add(new SqlParameter("@m_Price", SqlDbType.Decimal, 18)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_Price", SqlDbType.Decimal, 18)).Value = model.Price;
}
if (model.BeginTime == new DateTime())
{
cmd.Parameters.Add(new SqlParameter("@m_BeginTime", SqlDbType.DateTime, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_BeginTime", SqlDbType.DateTime, 0)).Value = model.BeginTime;
}
if (model.EndTime == new DateTime())
{
cmd.Parameters.Add(new SqlParameter("@m_EndTime", SqlDbType.DateTime, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_EndTime", SqlDbType.DateTime, 0)).Value = model.EndTime;
}
if (model.IsNew == null)
{
cmd.Parameters.Add(new SqlParameter("@m_IsNew", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_IsNew", SqlDbType.NVarChar, 50)).Value = model.IsNew;
}
if (model.MOQ == null)
{
cmd.Parameters.Add(new SqlParameter("@m_MOQ", SqlDbType.Decimal, 18)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_MOQ", SqlDbType.Decimal, 18)).Value = model.MOQ;
}
if (model.LimitTimes == null)
{
cmd.Parameters.Add(new SqlParameter("@m_LimitTimes", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_LimitTimes", SqlDbType.NVarChar, 50)).Value = model.LimitTimes;
}
if (model.CaiWuRemarks == null)
{
cmd.Parameters.Add(new SqlParameter("@m_CaiWuRemarks", SqlDbType.NVarChar, 100)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CaiWuRemarks", SqlDbType.NVarChar, 100)).Value = model.CaiWuRemarks;
}
if (model.PlanRemarks == null)
{
cmd.Parameters.Add(new SqlParameter("@m_PlanRemarks", SqlDbType.NVarChar, 100)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_PlanRemarks", SqlDbType.NVarChar, 100)).Value = model.PlanRemarks;
}
if (model.ApplyType == null)
{
cmd.Parameters.Add(new SqlParameter("@m_ApplyType", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_ApplyType", SqlDbType.NVarChar, 50)).Value = model.ApplyType;
}
if (model.TaskID == null)
{
cmd.Parameters.Add(new SqlParameter("@m_TaskID", SqlDbType.Int, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_TaskID", SqlDbType.Int, 0)).Value = model.TaskID;
}
//输出参数
SqlParameter returnParam = cmd.Parameters.Add(new SqlParameter("@thisId", SqlDbType.Int));
returnParam.Direction = ParameterDirection.Output;
int returnId = -1;
try
{
cmd.ExecuteScalar();
returnId = Convert.ToInt32(cmd.Parameters["@thisId"].Value);
}
catch (Exception e) { throw new Exception(e.ToString()); }
cmd.Dispose();
con.Close();
con.Dispose();
return returnId;
}
/// <summary>
/// 更新JD_SePriceApply_Log对象
/// 编写人:ywk
/// 编写日期:2018/7/26 星期四
/// </summary>
public void Update(JD_SePriceApply_Log model)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE JD_SePriceApply_Log SET ParentID = @m_ParentID,Operater = @m_Operater,CreateTime = @m_CreateTime,IsUpdate = @m_IsUpdate,ShortName = @m_ShortName,CustomCode = @m_CustomCode,CustomName = @m_CustomName,FNumber = @m_FNumber,FModel = @m_FModel,CoinType = @m_CoinType,BeginSalesCount = @m_BeginSalesCount,EndSalesCount = @m_EndSalesCount,Price = @m_Price,BeginTime = @m_BeginTime,EndTime = @m_EndTime,IsNew = @m_IsNew,MOQ = @m_MOQ,LimitTimes = @m_LimitTimes,CaiWuRemarks = @m_CaiWuRemarks,PlanRemarks = @m_PlanRemarks,ApplyType = @m_ApplyType,TaskID = @m_TaskID WHERE ItemID = @m_ItemID", con);
con.Open();
if (model.ParentID == null)
{
cmd.Parameters.Add(new SqlParameter("@m_ParentID", SqlDbType.Int, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_ParentID", SqlDbType.Int, 0)).Value = model.ParentID;
}
if (model.Operater == null)
{
cmd.Parameters.Add(new SqlParameter("@m_Operater", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_Operater", SqlDbType.NVarChar, 50)).Value = model.Operater;
}
if (model.CreateTime == new DateTime())
{
cmd.Parameters.Add(new SqlParameter("@m_CreateTime", SqlDbType.DateTime, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CreateTime", SqlDbType.DateTime, 0)).Value = model.CreateTime;
}
if (model.IsUpdate == null)
{
cmd.Parameters.Add(new SqlParameter("@m_IsUpdate", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_IsUpdate", SqlDbType.NVarChar, 50)).Value = model.IsUpdate;
}
if (model.ShortName == null)
{
cmd.Parameters.Add(new SqlParameter("@m_ShortName", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_ShortName", SqlDbType.NVarChar, 50)).Value = model.ShortName;
}
if (model.CustomCode == null)
{
cmd.Parameters.Add(new SqlParameter("@m_CustomCode", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CustomCode", SqlDbType.NVarChar, 50)).Value = model.CustomCode;
}
if (model.CustomName == null)
{
cmd.Parameters.Add(new SqlParameter("@m_CustomName", SqlDbType.NVarChar, 100)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CustomName", SqlDbType.NVarChar, 100)).Value = model.CustomName;
}
if (model.FNumber == null)
{
cmd.Parameters.Add(new SqlParameter("@m_FNumber", SqlDbType.NVarChar, 100)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_FNumber", SqlDbType.NVarChar, 100)).Value = model.FNumber;
}
if (model.FModel == null)
{
cmd.Parameters.Add(new SqlParameter("@m_FModel", SqlDbType.NVarChar, 500)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_FModel", SqlDbType.NVarChar, 500)).Value = model.FModel;
}
if (model.CoinType == null)
{
cmd.Parameters.Add(new SqlParameter("@m_CoinType", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CoinType", SqlDbType.NVarChar, 50)).Value = model.CoinType;
}
if (model.BeginSalesCount == null)
{
cmd.Parameters.Add(new SqlParameter("@m_BeginSalesCount", SqlDbType.Decimal, 18)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_BeginSalesCount", SqlDbType.Decimal, 18)).Value = model.BeginSalesCount;
}
if (model.EndSalesCount == null)
{
cmd.Parameters.Add(new SqlParameter("@m_EndSalesCount", SqlDbType.Decimal, 18)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_EndSalesCount", SqlDbType.Decimal, 18)).Value = model.EndSalesCount;
}
if (model.Price == null)
{
cmd.Parameters.Add(new SqlParameter("@m_Price", SqlDbType.Decimal, 18)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_Price", SqlDbType.Decimal, 18)).Value = model.Price;
}
if (model.BeginTime == new DateTime())
{
cmd.Parameters.Add(new SqlParameter("@m_BeginTime", SqlDbType.DateTime, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_BeginTime", SqlDbType.DateTime, 0)).Value = model.BeginTime;
}
if (model.EndTime == new DateTime())
{
cmd.Parameters.Add(new SqlParameter("@m_EndTime", SqlDbType.DateTime, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_EndTime", SqlDbType.DateTime, 0)).Value = model.EndTime;
}
if (model.IsNew == null)
{
cmd.Parameters.Add(new SqlParameter("@m_IsNew", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_IsNew", SqlDbType.NVarChar, 50)).Value = model.IsNew;
}
if (model.MOQ == null)
{
cmd.Parameters.Add(new SqlParameter("@m_MOQ", SqlDbType.Decimal, 18)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_MOQ", SqlDbType.Decimal, 18)).Value = model.MOQ;
}
if (model.LimitTimes == null)
{
cmd.Parameters.Add(new SqlParameter("@m_LimitTimes", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_LimitTimes", SqlDbType.NVarChar, 50)).Value = model.LimitTimes;
}
if (model.CaiWuRemarks == null)
{
cmd.Parameters.Add(new SqlParameter("@m_CaiWuRemarks", SqlDbType.NVarChar, 100)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_CaiWuRemarks", SqlDbType.NVarChar, 100)).Value = model.CaiWuRemarks;
}
if (model.PlanRemarks == null)
{
cmd.Parameters.Add(new SqlParameter("@m_PlanRemarks", SqlDbType.NVarChar, 100)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_PlanRemarks", SqlDbType.NVarChar, 100)).Value = model.PlanRemarks;
}
if (model.ApplyType == null)
{
cmd.Parameters.Add(new SqlParameter("@m_ApplyType", SqlDbType.NVarChar, 50)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_ApplyType", SqlDbType.NVarChar, 50)).Value = model.ApplyType;
}
if (model.TaskID == null)
{
cmd.Parameters.Add(new SqlParameter("@m_TaskID", SqlDbType.Int, 0)).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add(new SqlParameter("@m_TaskID", SqlDbType.Int, 0)).Value = model.TaskID;
}
cmd.Parameters.Add(new SqlParameter("@m_ItemID", SqlDbType.Int, 0)).Value = model.ItemID;
try { cmd.ExecuteNonQuery(); }
catch (Exception e) { throw new Exception(e.ToString()); }
cmd.Dispose();
con.Close();
con.Dispose();
}
public DataView GetDistinctList()
{
string sql = string.Format(@" select * from JD_SePriceApply_Log where IsUpdate='0'");
return DBUtil.Query(sql).Tables[0].DefaultView;
}
}
}
|
using SkiaSharp;
namespace gView.GraphicsEngine.Skia.Extensions
{
static class FontStyleExtensions
{
static public SKFontStyle ToSKFontStyle(this FontStyle fontStyle)
{
if (fontStyle.HasFlag(FontStyle.Bold) &&
fontStyle.HasFlag(FontStyle.Italic))
{
return SKFontStyle.BoldItalic;
}
if (fontStyle.HasFlag(FontStyle.Bold))
{
return SKFontStyle.Bold;
}
if (fontStyle.HasFlag(FontStyle.Italic))
{
return SKFontStyle.Italic;
}
return SKFontStyle.Normal;
}
}
}
|
using Project_Entity;
using Project_Entity.VM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_BLL.Managers
{
public class AuthorManager:ManagerBase<Author>
{
public Author GetCurrentUser(string _userName)
{
return Database.Authors.Where(x => x.EMail == _userName).FirstOrDefault();
}
public bool LoginUser(LoginVM _user)
{
return Database.Authors.Any(x => x.EMail == _user.EMail && x.Password == _user.Password && x.IsActive==true && x.IsDelete==false);
}
}
}
|
using System.IO;
using Newtonsoft.Json;
using Xunit;
namespace Cluj.GPS2Address.UnitTest
{
// use locality as city, if no locality, then use sublocality
public class GPS2AddressSpec
{
[Fact]
public void ExtractAddress()
{
using (var stream = new FileStream("./test/SampleAddress.json", FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
var addressString = reader.ReadToEnd();
var address = JsonConvert.DeserializeObject<GoogleAddressResult>(addressString);
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Effigy.Utility
{
public static class ExtensionMethod
{
public static string TrimString(this object str)
{
string retValue = string.Empty;
try
{
if (str != null)
{
retValue = Convert.ToString(str).Trim();
}
}
catch (Exception ex)
{
throw ex;
}
return retValue;
}
public static decimal TrimDecimal(this object str)
{
decimal retValue = 0;
try
{
if (str != null)
{
retValue = Math.Round(Convert.ToDecimal(str), 2);
}
}
catch (Exception ex)
{
throw ex;
}
return retValue;
}
public static double TrimDouble(this object str)
{
double retValue = 0;
try
{
if (str != null)
{
retValue = Math.Round(Convert.ToDouble(str), 2);
}
}
catch (Exception ex)
{
throw ex;
}
return retValue;
}
}
}
|
namespace sc80wffmex.GlassStructure
{
using System.Collections.Specialized;
public interface IControllerSitecoreContext
{
T GetDataSource<T>() where T : class;
NameValueCollection GetRenderingParameters();
}
} |
using System;
//TODO: Add other using statements here
namespace com.Sconit.Entity.TMS
{
public partial class Vehicle
{
#region Non O/R Mapping Properties
public string CodeDescription
{
get
{
if (string.IsNullOrEmpty(this.Description))
{
return this.Code;
}
else
{
return this.Code + "[" + this.Description + "]";
}
}
}
//TODO: Add Non O/R Mapping Properties here.
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using PFRCenterGlobal.ViewModels;
using Xamarin.Forms;
namespace PFRCenterGlobal.Views.AuthZone
{
public partial class HomePage : ContentPage
{
public HomePage()
{
InitializeComponent();
this.BindingContext = O2.ToolKit.Core.O2Store.CreateOrGet<MainViewModel>();
}
void CollectionView_SelectionChanged(System.Object sender, Xamarin.Forms.SelectionChangedEventArgs e)
{
if (e.CurrentSelection == null)
return;
MainItemViewModel selectedItem = (MainItemViewModel)e.CurrentSelection.First();
if(selectedItem!=null)
selectedItem.OpenUrlCommand.Execute(null);
}
}
}
|
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 System.Data;
using System.Collections;
namespace PlanMGMT.Control
{
/// 申明委托
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
//public delegate void EventPagingHandler(EventPagingArg e);
/// <summary>
/// UCPaging.xaml 的交互逻辑
/// </summary>
public partial class Pager : UserControl
{
#region Pirvate Member
// 页码变化触发事件
public event EventHandler EventPaging;
//public DataTable dt;
public IList list;
//public event EventPagingHandler EventPaging;
private int pageIndex = 1;
private int pageSize = 100;
private int recordCount = 0;
private int pageCount = 0;
private string jumpText;
/// <summary>
/// 当前页面
/// </summary>
public virtual int PageIndex
{
get { return pageIndex; }
set { pageIndex = value; }
}
/// <summary>
/// 每页记录数
/// </summary>
public virtual int PageSize
{
get { return pageSize; }
set { pageSize = value; }
}
/// <summary>
/// 总记录数
/// </summary>
public virtual int RecordCount
{
get { return recordCount; }
set { recordCount = value; }
}
/// <summary>
/// 总页数
/// </summary>
public int PageCount
{
get
{
if (pageSize != 0)
{
pageCount = GetPageCount();
}
return pageCount;
}
}
/// <summary>
/// 跳转按钮文本
/// </summary>
public string JumpText
{
get
{
if (string.IsNullOrEmpty(jumpText))
{
jumpText = "GO";
}
return jumpText;
}
set { jumpText = value; }
}
#endregion
/// <summary>
/// 计算总页数
/// </summary>
/// <returns></returns>
private int GetPageCount()
{
if (pageSize == 0)
{
return 0;
}
pageCount = RecordCount / PageSize;
if (RecordCount % PageSize == 0)
{
pageCount = RecordCount / PageSize;
}
else
{
pageCount = RecordCount / PageSize + 1;
}
return pageCount;
}
/// <summary>
/// 无参构造
/// </summary>
public Pager()
{
InitializeComponent();
}
/// <summary>
/// 触发翻页事件
/// </summary>
private void TrrigerEventPaging()
{
if (this.EventPaging != null)
this.EventPaging(this, null);//当前分页数字改变时,触发委托事件
}
/// <summary>
/// 得到数据
/// </summary>
/// <returns></returns>
public void Bind()
{
if (list == null || list.Count == 0)
{
this.Visibility = Visibility.Collapsed;
return;
}
else
{
this.Visibility = Visibility.Visible;
}
this.txbGO.Text = " " + this.JumpText;
//--控制 7
this.txbInfo.Text = "第 " + (this.PageIndex == 1 ? 1 : (this.PageIndex - 1) * this.PageSize) + "-" + this.PageIndex * this.PageSize + " 条 共 " + this.RecordCount + " 条 | 第 " + this.PageIndex + " / " + this.PageCount + " 页";
this.txtPageNum.Text = this.PageIndex.ToString();
this.txbTotalPageCount.Text = " / " + PageCount;
this.wPanel.Width = 90 + this.PageCount.ToString().Length * 7;
if (PageCount > 1 && PageCount > PageIndex)
{
//this.iNext.Source = new BitmapImage(new Uri("../Resources/Images/Pager/next2.gif", UriKind.Relative));
this.iNext.IsEnabled = true;
this.iLast.IsEnabled = true;
}
else
{
this.iNext.IsEnabled = false;
this.iLast.IsEnabled = false;
}
if (this.PageIndex > 1 && this.PageIndex <= this.PageCount)
{
this.iFirst.IsEnabled = true;
this.iPrev.IsEnabled = true;
}
else
{
this.iFirst.IsEnabled = false;
this.iPrev.IsEnabled = false;
}
}
/// <summary>
/// 第一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void iFirst_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.PageIndex = 1;
this.TrrigerEventPaging();
this.Bind();
}
/// <summary>
/// 上一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void iPrev_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.PageIndex--;
this.TrrigerEventPaging();
this.Bind();
}
/// <summary>
/// 下一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void iNext_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.PageIndex++;
this.TrrigerEventPaging();
this.Bind();
}
/// <summary>
/// 末页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void iLast_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.PageIndex = PageCount;
this.TrrigerEventPaging();
this.Bind();
}
/// <summary>
/// 确定导航到指定页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void nudPageIndex_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Return)
{
this.PageIndex = int.Parse(this.txtPageNum.Text.ToString());
this.TrrigerEventPaging();
this.Bind();
}
}
/// <summary>
/// 确定导航
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txbGO_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.PageIndex = int.Parse(this.txtPageNum.Text.ToString());
this.TrrigerEventPaging();
this.Bind();
}
/// <summary>
/// 跳转限制
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtNum_TextChanged(object sender, TextChangedEventArgs e)
{
int num = 0;
if (int.TryParse(txtPageNum.Text.Trim(), out num) && num > 0)
{
if (num > PageCount)
{
txtPageNum.Text = PageCount.ToString();
}
}
}
/// <summary>
/// 键盘按下事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtPageNum_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.txtPageNum.Focus();
this.PageIndex = int.Parse(this.txtPageNum.Text.ToString());
this.TrrigerEventPaging();
this.Bind();
}
}
/// <summary>
/// 鼠标移入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txbGO_MouseMove(object sender, MouseEventArgs e)
{
this.txbGO.TextDecorations = TextDecorations.Underline;//加下划线
}
/// <summary>
/// 鼠标移出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txbGO_MouseLeave(object sender, MouseEventArgs e)
{
this.txbGO.TextDecorations = null;
}
}
/// <summary>
/// 自定义事件数据基类
/// </summary>
//public class EventPagingArg : EventArgs
//{
// public EventPagingArg() { }
//}
}
|
using UnityEngine;
using System.Collections;
using ParticlePlayground;
public class EnemyAttack : MonoBehaviour {
public PlaygroundParticlesC particles;
public int attackDamage = 3;
public void Attack() {
particles.enabled = true;
StartCoroutine("DealDamage");
}
public void TerminateAttack() {
particles.enabled = false;
StopCoroutine("DealDamage");
}
private IEnumerator DealDamage() {
while ( true ) {
RaycastHit hit;
if ( Physics.Raycast(transform.position + Vector3.up, transform.forward, out hit, 10f) ) {
if ( hit.transform.gameObject.tag == "Player" ) {
hit.transform.gameObject.GetComponent<PlayerHealth>().TakeDamage(attackDamage, false);
} else if ( hit.transform.gameObject.tag == "Player2" ) {
hit.transform.gameObject.GetComponent<Player2Health>().TakeDamage(attackDamage, false);
}
}
yield return new WaitForFixedUpdate();
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class MenuManagement : MonoBehaviour
{
public RectTransform m_RectTransform;
public IEnumerator ShowProductionTeam()
{
while (m_RectTransform.anchoredPosition.y > -1000)
{
m_RectTransform.anchoredPosition -= new Vector2(0, 200 * Time.deltaTime);
yield return null;
}
}
public void Show()
{
StartCoroutine(ShowProductionTeam());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LuckyMasale.DAL.DataProviders
{
public interface IProductCategoryMapDataProvider : IBaseDataProvider
{ }
public class ProductCategoryMapDataProvider : BaseDataProvider, IProductCategoryMapDataProvider
{
#region Constructors
public ProductCategoryMapDataProvider(IDataSourceFactory dataSourceFactory)
: base(dataSourceFactory)
{
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace KartObjects
{
/// <summary>
/// Запись в дереве структуры типов документов
/// </summary>
public class DocKindRecord:SimpleDbEntity
{
public override string FriendlyName
{
get { return "Структура типов документов"; }
}
public long IdParent
{
get;
set;
}
/// <summary>
/// Вид документа
/// </summary>
public DocKindEnum docKind
{
get;
set;
}
public string Name
{
get;
set;
}
/// <summary>
/// Идентификато типа документа
/// </summary>
public long? IdDocType
{
get;
set;
}
}
}
|
using DataLightning.Core.Operators;
using Moq;
using System.Collections.Generic;
using Xunit;
namespace DataLightning.Core.Tests.Unit.Operators
{
public class JoinTests
{
private readonly Join<TestEntityA, TestEntityB> _sut;
private readonly PassThroughUnit<TestEntityA> _inputLeft;
private readonly PassThroughUnit<TestEntityB> _inputRight;
public JoinTests()
{
_inputLeft = new PassThroughUnit<TestEntityA>();
_inputRight = new PassThroughUnit<TestEntityB>();
_sut = new Join<TestEntityA, TestEntityB>(
_inputLeft, _inputRight,
value => value.KeyA, value => value.KeyB,
value => value.KeyA, value => value.KeyB);
}
[Fact]
public void ShouldReturnMatchedElements()
{
(IList<TestEntityA>, IList<TestEntityB>) result = (null, null);
var subscriberMock = new Mock<ISubscriber<(IList<TestEntityA>, IList<TestEntityB>)>>();
subscriberMock.Setup(s => s.Push(It.IsAny<(IList<TestEntityA>, IList<TestEntityB>)>()))
.Callback<(IList<TestEntityA>, IList<TestEntityB>)>(value => result = value);
_sut.Subscribe(subscriberMock.Object);
var value1 = new TestEntityA { KeyA = 1, Value1 = "A" };
_inputLeft.Push(value1);
var value2 = new TestEntityB { KeyB = 1, Value1 = "B", Value2 = "B" };
_inputRight.Push(value2);
var expected = (new List<TestEntityA> { value1 }, new List<TestEntityB> { value2 });
Assert.Equal(expected.Item1, result.Item1);
Assert.Equal(expected.Item2, result.Item2);
}
}
} |
using System;
using Mono.Profiling;
using Mono.Options;
class Driver {
static void DumpHeader (Header header) {
Console.WriteLine ("Version {0}.{1} format {2}", header.Major, header.Minor, header.Format);
Console.WriteLine ("Pointer Size {0}", header.PointerSize);
Console.WriteLine ("Start Time {0} Pointer Overhead {1}", header.StartTime, header.TimerOverhead);
Console.WriteLine ("Flags {0:X}", header.Flags);
Console.WriteLine ("Pid {0} Port {1} SysId {2}", header.Pid, header.Port, header.SysId);
}
static void DumpBuffer (EventBuffer buffer) {
Console.WriteLine ("Buffer len {0}", buffer.Data.Length);
Console.WriteLine ("Base Variables:");
Console.WriteLine ("\tTime: {0:X}", buffer.TimeBase);
Console.WriteLine ("\tPointer: {0:X}", buffer.PointerBase);
Console.WriteLine ("\tObject: {0:X}", buffer.ObjectBase);
Console.WriteLine ("\tThreadId: {0:X}", buffer.ThreadId);
Console.WriteLine ("\tMethod: {0:X}", buffer.MethodBase);
Console.WriteLine ("----events");
foreach (var evt in buffer.GetEvents ())
Console.WriteLine (evt);
}
static void Main (string[] args) {
bool dump_file = false;
bool lint_file = false;
var opts = new OptionSet () {
{ "dump", v => dump_file = v != null },
{ "lint", v => lint_file = v != null }
};
var files = opts.Parse (args);
if (files.Count == 0) {
Console.WriteLine ("pass at least one file");
return;
}
if (!dump_file && !lint_file)
lint_file = true;
foreach (var f in files) {
Console.WriteLine ("File: {0}", f);
var decoder = new Decoder (f);
if (dump_file) {
Console.WriteLine ("========HEADER");
DumpHeader (decoder.Header);
Console.WriteLine ("========BUFFERS");
foreach (var buffer in decoder.GetBuffers ())
DumpBuffer (buffer);
}
decoder.Reset ();
if (lint_file) {
var l = new MprofLinter (decoder);
l.Verify ();
l.PrintSummary ();
}
}
}
}
|
using System;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.Extensions;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts;
using Newtonsoft.Json.Linq;
using OrchardCore.PublishLater.Models;
namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Parts
{
#pragma warning disable S1481 // need the variable for the new using syntax, see https://github.com/dotnet/csharplang/issues/2235
public class PublishLaterPartGraphSyncer : ContentPartGraphSyncer
{
public override string PartName => nameof(PublishLaterPart);
private static readonly Func<string, string> _publishLaterFieldsPropertyNameTransform = n => $"publishlater_{n}";
private const string ScheduledPublishUtcPropertyName = "ScheduledPublishUtc";
public override async Task AddSyncComponents(JObject content, IGraphMergeContext context)
{
// prefix field property names, so there's no possibility of a clash with the eponymous fields property names
using var _ = context.SyncNameProvider.PushPropertyNameTransform(_publishLaterFieldsPropertyNameTransform);
context.MergeNodeCommand.AddProperty<DateTime>(
await context.SyncNameProvider.PropertyName(ScheduledPublishUtcPropertyName),
content, ScheduledPublishUtcPropertyName);
}
public override async Task<(bool validated, string failureReason)> ValidateSyncComponent(
JObject content,
IValidateAndRepairContext context)
{
// prefix field property names, so there's no possibility of a clash with the eponymous fields property names
using var _ = context.SyncNameProvider.PushPropertyNameTransform(_publishLaterFieldsPropertyNameTransform);
return context.GraphValidationHelper.DateTimeContentPropertyMatchesNodeProperty(
ScheduledPublishUtcPropertyName,
content,
await context.SyncNameProvider!.PropertyName(ScheduledPublishUtcPropertyName),
context.NodeWithRelationships.SourceNode!);
}
}
#pragma warning restore S1481
}
|
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(DebugDrawHelper))]
public class DebugDrawHelperEditor : Editor
{
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PrefixLabel("Shortcuts");
++EditorGUI.indentLevel;
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("ToggleDebugDrawKey"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("ToggleDisplayDrawablesListKey"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("SwitchDisplayTypeKey"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("DisplayShortcutsKey"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("PrevItemKey"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("NextItemKey"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("PrevPageKey"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("NextPageKey"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("ToggleSelectionKey"));
}
--EditorGUI.indentLevel;
EditorGUILayout.Space();
EditorGUILayout.PrefixLabel("Colors");
++EditorGUI.indentLevel;
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("DefaultColor"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("SelectedColor"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("HighlightedColor"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("HighlightedSelectedColor"));
}
--EditorGUI.indentLevel;
EditorGUILayout.Space();
EditorGUILayout.PrefixLabel("Misc");
++EditorGUI.indentLevel;
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("MaxDrawablesPerPage"));
}
--EditorGUI.indentLevel;
serializedObject.ApplyModifiedProperties();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace NotSoSmartSaverAPI.ModelsGenerated
{
public partial class Users
{
public string Userid { get; set; }
[Required]
[EmailAddress(ErrorMessage = "A valid email address has to be entered")]
public string Useremail { get; set; }
[Required]
public string Userpassword { get; set; }
[Required]
[MaxLength(30, ErrorMessage = "User name is too long, maximum lenght is 30")]
public string Username { get; set; }
[Required]
[MaxLength(30, ErrorMessage = "User last name is too long, maximum lenght is 30")]
public string Userlastname { get; set; }
public float? Usermoney { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.