text
stringlengths
13
6.01M
using Microsoft.EntityFrameworkCore; using RetenionApp.Models; namespace RetenionApp.Data { public class RetentionContext : DbContext { public DbSet<User> Users { get; set; } public RetentionContext(DbContextOptions opts) : base(opts) { } } }
/* * Jacob Buri * IPooledObject.cs * Assignment 10 - Singleton and ObjectPool * Interface for a pooled object. Called in ObjectPooler.cs */ using UnityEngine; public interface IPooledObject { void OnObjectSpawn(); }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; namespace MeeToo.DataAccess.DocumentDb { public class DocumentDbQuery<T> : IDocumentDbQquery<T> { private readonly DocumentClient documentClient; private readonly Database db; private readonly DocumentCollection collection; private readonly IQueryable<T> queryable; public Expression Expression => queryable.Expression; public Type ElementType => queryable.ElementType; public IQueryProvider Provider => queryable.Provider; public DocumentDbQuery(DocumentClient documentClient, Database db, DocumentCollection collection) : this(documentClient, db, collection, documentClient.CreateDocumentQuery<T>(collection.DocumentsLink)) { } public DocumentDbQuery(DocumentClient documentClient, Database db, DocumentCollection collection, IQueryable<T> queryable) { this.documentClient = documentClient; this.db = db; this.collection = collection; this.queryable = queryable; } public IDocumentDbQquery<T> Where(Expression<Func<T, bool>> predicate) { return new DocumentDbQuery<T>(documentClient, db, collection, queryable.Where(predicate)); } public async Task<T> FindAsync(string id) { try { var response = await documentClient.ReadDocumentAsync(UriFactory.CreateDocumentUri(db.Id, collection.Id, id)) .ConfigureAwait(false); T document = (T)(dynamic)response.Resource; return document; } catch (DocumentClientException ex) { throw new InvalidOperationException(""); } } public T FirstOrDefault() { return queryable.AsEnumerable() .FirstOrDefault(); } public T FirstOrDefault(Func<T, bool> predicate) { return queryable.Where(predicate) .AsEnumerable() .FirstOrDefault(); } public IDocumentDbQquery<TResult> Select<TResult>(Expression<Func<T, TResult>> selector) { return new DocumentDbQuery<TResult>(documentClient, db, collection, queryable.Select(selector)); } public IEnumerator<T> GetEnumerator() { return queryable.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using System; class ReverseString { static void Main() { string inputStr = Console.ReadLine(); for (int i = inputStr.Length-1; i >= 0; i--) { Console.Write(inputStr[i]); } Console.WriteLine(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace WpfApp2 { /// <summary> /// Interaction logic for Oefening6.xaml /// </summary> public partial class Oefening6 : Window { public Oefening6() { InitializeComponent(); } private void btnSubmit_Click(object sender, RoutedEventArgs e) { Random rng = new Random(); int gewonnen = rng.Next(3); string input = txtNaam.Text.ToLower(); switch(input) { case "blad": if (gewonnen == 1) MessageBox.Show("De computer koos Steen.Gewonnen!"); else if (gewonnen == 2) MessageBox.Show("De Computer koos Schaar.Verloren!"); else MessageBox.Show("De Computer Koos Blad.Gelijkspel"); break; case "steen": if (gewonnen == 1) MessageBox.Show("De Computer koos Schaar.Gewonnen!"); else if (gewonnen == 2) MessageBox.Show("De Computer Koos Blad.Verloren!"); else MessageBox.Show("De computer koos Steen.Gelijkspel"); break; case "schaar": if (gewonnen == 1) MessageBox.Show("De Computer Koos Blad. Gewonnen!"); else if (gewonnen == 2) MessageBox.Show("De computer koos Steen. Verloren!"); else MessageBox.Show("De Computer koos Schaar. Gelijkspel"); break; } } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; public class Card : MonoBehaviour { [SerializeField] CardInfo _cardInfo; //[SerializeField] CardAttributes _cardAttributes; [SerializeField] CardType _cardType; [SerializeField] Image _cardIcon; [SerializeField] Text _cardName; [SerializeField] Text _cardDescription; [SerializeField] Text _cardTypeText; [SerializeField] Text _cardCostValue; [SerializeField] Image _cardHighlightImage; [SerializeField] int _playerHandIndex; // use this for player hand related funcs CardLogic _cardLogic; // the card specific logic it may have. public bool isBlank = false; public CardInfo CardInfo { get { return _cardInfo; } } public Image CardHighlightImage { get { return _cardHighlightImage; } } public int PlayerHandIndex { get { return _playerHandIndex; } set { _playerHandIndex = value; } } public CardLogic CardLogic { get { return _cardLogic; } } public void InitialiseCard(CardInfo info) { // setup card graphics _cardInfo = info; _cardIcon.sprite = _cardInfo.CardIcon; _cardName.text = _cardInfo.CardName; _cardDescription.text = _cardInfo.CardDescription; _cardType = _cardInfo.CardType; _cardTypeText.text = _cardType.GetTypeString(); // setup card logic _cardAttributes = _cardInfo.CardAttributes; _cardCostValue.text = _cardAttributes.BaseCardCost.ToString(); _cardType.OnInitCard(); try { _cardLogic = this.gameObject.GetComponent<CardLogic>(); } catch(NullReferenceException e) { Debug.Log("card does not have accompanying logic. Adding class..."); var temp = this.gameObject.AddComponent<CardLogic>(); _cardLogic = temp; } } public void CreateBlankCard() { isBlank = true; } // big TODO: // need to think about how to handle card attributes, like attack, debuffs, buffs etc. // dont use enums as that would become too much of a hassle to maintain // maybe use a struct? but then have problem of some cards having unused values // attributes: /* if going by slay the spire type, it is 'attack' cards and spell cards attack value - int card mana cost - int 'intended target' - probs bool debuff/buff on target - e.g. poison, burn, card mulligan/discard - would also need duration if applicable - this would probs be a either an enum/static class (statusType) health increase/decrease value - int //potential additions 'curse' cards, e.g. cards that you have to get out of your hand or suffer consequences */ }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace StrategyMaker { class Program { static void BuildAssembly(SyntaxTree syntaxTree, string assemblyName) { List<MetadataReference> references = new List<MetadataReference>() { MetadataReference.CreateFromFile(Assembly.Load("System.Private.CoreLib").Location), MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location), MetadataReference.CreateFromFile(Assembly.Load("RockPaperScissors.Basics").Location), MetadataReference.CreateFromFile(Assembly.Load("netstandard").Location), MetadataReference.CreateFromFile(Assembly.Load("System.Runtime.Extensions").Location) }; CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, new[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); using FileStream stream = new FileStream(Path.Combine("../../../../RockPaperScissors/bin/debug/netcoreapp3.1/Strategies", assemblyName), FileMode.Create); EmitResult result = compilation.Emit(stream); foreach (var diagnostic in result.Diagnostics) Console.WriteLine($"{diagnostic.Id}: {diagnostic.GetMessage()}"); } static void Main() { Console.Write("Percentage Rock? "); int pcRock = int.Parse(Console.ReadLine()); Console.Write("Percentage Paper? "); int pcPaper = int.Parse(Console.ReadLine()); int pcScissors = 100 - pcRock - pcPaper; Console.WriteLine($"{pcRock}% Rock. {pcPaper}% Paper. {pcScissors}% Scissors."); Console.Write("What do you want to call your strategy? "); string name = Console.ReadLine(); var builder = new StringBuilder(); builder.AppendLine("using RockPaperScissors.Basics;"); builder.AppendLine("namespace RockPaperScissors.Strategies"); builder.AppendLine("{"); builder.AppendLine($" public class {name} : IRPSStrategy"); builder.AppendLine(" {"); builder.AppendLine(" public Sign Throw()"); builder.AppendLine(" {"); builder.AppendLine(" int val = IRPSStrategy._random.Next(100);"); builder.AppendLine($" if (val < {pcRock})"); builder.AppendLine($" return Sign.Rock;"); builder.AppendLine($" else if (val < {pcRock + pcPaper})"); builder.AppendLine($" return Sign.Paper;"); builder.AppendLine($" else "); builder.AppendLine($" return Sign.Scissors;"); builder.AppendLine(" }"); builder.AppendLine(" }"); builder.AppendLine("}"); SyntaxTree tree = CSharpSyntaxTree.ParseText(builder.ToString()); BuildAssembly(tree, $"{name}.dll"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotator : MonoBehaviour { private SpriteRenderer sr; public GameObject rotated; void Start() { sr = rotated.GetComponent<SpriteRenderer>(); } void FixedUpdate() { Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg; rotated.transform.rotation = Quaternion.Euler(0f, 0f, rotZ + 90); } }
using System; using System.IO; using System.Windows.Forms; namespace DiceChart { public partial class DiceChartMainWindow : Form { const int ITERATIONS = 10000; public DiceChartMainWindow() { InitializeComponent(); } /// <summary> /// Generates the histogram data using the selected dice /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { Random randomGenerator = new Random(); int number = (int) diceNumber.Value; object selectedDice = diceType.SelectedItem; if (selectedDice == null) { return; } int dice = int.Parse( selectedDice.ToString() ); int[] diceRolls = new int[ITERATIONS]; for(int i = 0; i < ITERATIONS; ++i) { for (int j = 0; j < number; ++j) { diceRolls[i] += randomGenerator.Next(1, dice + 1); } } int[] values = new int[number * dice + 1]; for(int i = 0; i < ITERATIONS; ++i) { values[diceRolls[i]]++; } diceHistogram.Series.Clear(); diceHistogram.Series.Add("Dice: " + number + "d" + dice); diceHistogram.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column; diceHistogram.Legends.Clear(); for(int i = number; i < values.Length; ++i) { diceHistogram.Series[0].Points.AddXY(i, values[i]); } diceHistogram.ChartAreas[0].AxisX.Title = "Dice: " + number + "d" + dice; diceHistogram.ChartAreas[0].AxisY.Title = "Rolls in " + ITERATIONS; diceHistogram.Update(); } /// <summary> /// Saves the charted histogram to a JPG file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void saveToImageButton_Click(object sender, EventArgs e) { Stream imageStream; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*"; saveDialog.FilterIndex = 1; saveDialog.RestoreDirectory = true; if(saveDialog.ShowDialog() == DialogResult.OK) { imageStream = saveDialog.OpenFile(); if( imageStream != null ) { using (imageStream) { diceHistogram.SaveImage(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg); } } } } } }
using Practise.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Practise.Infrastructure { public interface IRepository<TEntity> where TEntity : BaseEntity { List<TEntity> GetAll(); void Insert(TEntity entity); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArkSavegameToolkitNet.Property { public class PropertyInt8 : PropertyBase<sbyte?> { public PropertyInt8(string name, string typeName, sbyte value) : base(name, typeName, 0, value) { } public PropertyInt8(string name, string typeName, int index, sbyte value) : base(name, typeName, index, value) { } public PropertyInt8(ArkArchive archive, PropertyArgs args, bool propertyIsExcluded = false) : base(archive, args, propertyIsExcluded) { if (propertyIsExcluded) { archive.Position += 1; return; } _value = archive.GetByte(); } //public override Type ValueClass => typeof(sbyte?); public override sbyte? Value { get { return _value; } set { _value = value; } } //public override int calculateDataSize(bool nameTable) //{ // return Byte.BYTES; //} } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class CraftRecipeDatabase : MonoBehaviour { public List<CraftRecipe> recipes = new List<CraftRecipe>(); private ItemDatabase itemDatabase; private void Awake() { itemDatabase = GetComponent<ItemDatabase>(); BuildCraftRecipeDatabase(); } public Item CheckItemRecipe(int[] recipe) { foreach(CraftRecipe craftRecipe in recipes) { if (craftRecipe.requiredItems.OrderBy(i => i).SequenceEqual(recipe.OrderBy(i => i))) { return itemDatabase.GetItem(craftRecipe.itemToCraft); } } return null; } void BuildCraftRecipeDatabase() { recipes = new List<CraftRecipe>() { new CraftRecipe(1, new int[] { 0,0,0, 1,0,3, 2,0,0 }), new CraftRecipe(2, new int[] { 0,1,0, 0,0,0, 2,0,0 }), new CraftRecipe(3, new int[] { 0,0,0, 0,1,0, 0,0,0 }) }; } }
namespace ParkingSystem { using System; using System.Collections.Generic; public class Startup { public static void Main(string[] args) { Execute(); } private static void Execute() { var args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var n = int.Parse(args[0]); var m = int.Parse(args[1]); var dict = new Dictionary<int, HashSet<int>>(); args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); while (args[0] != "stop") { var entryRow = int.Parse(args[0]); var row = int.Parse(args[1]); var col = int.Parse(args[2]); var distance = Math.Abs(entryRow - row); if (!dict.ContainsKey(row)) { dict.Add(row, new HashSet<int>()); } if (!dict[row].Contains(col)) { dict[row].Add(col); distance += col + 1; Console.WriteLine(distance); args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); continue; } if (dict[row].Count == m - 1) { Console.WriteLine($"Row {row} full"); args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); continue; } var left = 0; var right = 0; for (int i = col - 1; i > 0; i--) { if (!dict[row].Contains(i)) { left = i; break; } } for (int i = col + 1; i < m; i++) { if (!dict[row].Contains(i)) { right = i; break; } } if (left != 0 && right == 0) { dict[row].Add(left); distance += left + 1; } else if (left == 0 && right != 0) { dict[row].Add(right); distance += right + 1; } else if (col - left < right - col || col - left == right - col) { dict[row].Add(left); distance += left + 1; } else if (col - left > right - col) { dict[row].Add(right); distance += right + 1; } Console.WriteLine(distance); args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); } } } }
namespace LeadChina.CCDMonitor.Infrastrue { public class EtOpManager { private static AbstractEtFactory factory; private EtOpManager() { } public static AbstractEtFactory GetFactory() { if (factory == null) { factory = new EtFactory(); } return factory; } } }
using Controller.UsersAndWorkingTime; using Model.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using ZdravoKorporacija.View; namespace ZdravoKorporacija { /// <summary> /// Interaction logic for EditPasswordWindow.xaml /// </summary> public partial class EditPasswordWindow : Window { private static PatientController patientController = new PatientController(); private readonly UserController userController = new UserController(patientController); private Patient patient; public EditPasswordWindow() { InitializeComponent(); patient = (Patient)userController.ViewProfile(MainWindow.patient.Jmbg); usernamePatient.Text = patient.Username; } private void buttonCancel_Click(object sender, RoutedEventArgs e) { HomePageWindow homePageWindow = new HomePageWindow(); homePageWindow.Show(); this.Close(); } private void buttonConfrim_Click(object sender, RoutedEventArgs e) { if (oldPassword.Password.Equals("") || newPassword.Password.Equals("") || confirmPassword.Password.Equals("")) { ValidationMessageWindow validationWindow = new ValidationMessageWindow(); validationWindow.Show(); } else if (!oldPassword.Password.Equals(userController.ViewProfile(MainWindow.patient.Jmbg).Password)) { ValidationOldPasswordWindow validationOldPassword = new ValidationOldPasswordWindow(); validationOldPassword.Show(); } else if (!confirmPassword.Password.Equals(newPassword.Password)) { ValidationNewPasswordWindow validationNewPassword = new ValidationNewPasswordWindow(); validationNewPassword.Show(); } else { patient.Password = newPassword.Password; if (userController.EditProfile(patient) != null) { MainWindow mainWindow = new MainWindow(); mainWindow.Show(); SuccessfulUpdatePasswordWindow successfulUpdatePasswordWindow = new SuccessfulUpdatePasswordWindow(); successfulUpdatePasswordWindow.Show(); this.Close(); } else { ValidationMessageWindow validationWindowPassword = new ValidationMessageWindow(); validationWindowPassword.caption.Text = "Unesite najmanje 8 karaktera, jedan broj i bar jedno malo i veliko slovo!"; validationWindowPassword.Show(); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class ChessEntity { private List<Material> materialsCache; private List<Color> savedMaterialColors; private bool SearchMaterials() { if (Renderers == null) { return false; } if (materialsCache == null) { materialsCache = new List<Material>(); for (int i = 0; i < Renderers.Length; i++) { var mats = Renderers[i].materials; materialsCache.AddRange(mats); } savedMaterialColors = new List<Color>(materialsCache.Count); for (int i = 0; i < materialsCache.Count; i++) { var color = materialsCache[i].GetColor("_Color"); savedMaterialColors.Add(color); } } return true; } public void MaterialsColor(Color color) { if (!SearchMaterials()) return; for(int idx = 0; idx < materialsCache.Count; idx++) { materialsCache[idx].SetColor("_Color", color); } } public void RevertMaterialsColor() { if (!SearchMaterials()) return; for (int idx = 0; idx < materialsCache.Count; idx++) { materialsCache[idx].SetColor("_Color", savedMaterialColors[idx]); } } }
using System; using System.Collections.Generic; using System.Data; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; using System.Linq; using System.Security.Principal; using ILogging; using ServiceDeskSVC.DataAccess.Models; using ServiceDeskSVC.DataAccess.UserRefresh; using ServiceDeskSVC.Domain.Entities.ViewModels.UserRefresh; using ServiceDeskSVC.Managers.UserRefresh; namespace ServiceDeskSVC.Managers.Managers.UserRefresh { public class UserRefreshManager : IUserRefreshManager { private readonly IUserRefreshRepository _userRefreshRepository; private readonly INSLocationManager _nsLocationManager; private readonly IDepartmentManager _departmentManager; private readonly ILogger _logger; public UserRefreshManager(IUserRefreshRepository userRefreshRepository, INSLocationManager nsLocationManager, IDepartmentManager departmentManager, ILogger logger) { _userRefreshRepository = userRefreshRepository; _nsLocationManager = nsLocationManager; _departmentManager = departmentManager; _logger = logger; } public UserRefreshReturn RunRefreshForAllUsers() { var refresh = new UserRefreshReturn { success = true }; var data = GetAllUserData(); var departments = getUniqueDepartments(data); var deptsRefreshed = RefreshDepartments(departments); if (!deptsRefreshed) { refresh.success = false; refresh.errorMessage = "Departments Failed"; return refresh; } //REFRESH LOCATIONS var locations = getUniqueLocations(data); var locsRefreshed = RefreshLocations(locations); if (!locsRefreshed) { refresh.success = false; refresh.errorMessage = "Locations Failed"; return refresh; } data = PopulateLocationIds(data); data = PopulateDepartmentIds(data); List<ServiceDesk_Users> EFData = data.Select(MapRefreshModelToEFModel).ToList(); var usersRefreshed = RefreshUserData(EFData); if (!usersRefreshed) { refresh.success = false; refresh.errorMessage = "Users Failed"; return refresh; } return refresh; } private bool RefreshDepartments(List<Department> depts) { return _userRefreshRepository.RunRefreshForAllDepartments(depts); } private bool RefreshUserData(List<ServiceDesk_Users> EFUsers) { return _userRefreshRepository.RunRefreshForAllUsers(EFUsers); } private bool RefreshLocations(List<NSLocation> locs) { return _userRefreshRepository.RunRefreshForAllLocations(locs); } private ServiceDesk_Users MapRefreshModelToEFModel(UserRefreshModel refreshModel) { return new ServiceDesk_Users { SID = refreshModel.SID, UserName = refreshModel.UserName, FirstName = refreshModel.FirstName, LastName = refreshModel.LastName, EMail = refreshModel.EMail, LocationId = refreshModel.LocationId ?? 0, DepartmentId = refreshModel.DepartmentId ?? 0 }; } private List<UserRefreshModel> PopulateDepartmentIds(List<UserRefreshModel> model) { var departments = _departmentManager.GetAllDepartments(); foreach (var m in model) { m.DepartmentId = departments.Where(d => d.DepartmentName == m.Department).Select(di => di.Id).FirstOrDefault(); } return model; } private List<UserRefreshModel> PopulateLocationIds(List<UserRefreshModel> model) { var locations = _nsLocationManager.GetAllLocations(); foreach (var l in model) { l.LocationId = locations.Where(lo => lo.LocationCity == l.Location).Select(li => li.Id).FirstOrDefault(); if (l.LocationId.GetType() != typeof(int)) { l.LocationId = 0; } } return model; } private List<UserRefreshModel> GetAllUserData() { List<UserRefreshModel> model = new List<UserRefreshModel>(); using (var context = new PrincipalContext(ContextType.Domain, "safety.northernsafety.com")) { using (var searcher = new PrincipalSearcher(new UserPrincipal(context))) { foreach (var result in searcher.FindAll()) { UserRefreshModel singleUser = new UserRefreshModel(); DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry; if (de != null && de.Properties["givenName"].Value != null && de.Properties["physicalDeliveryOfficeName"].Value != null && de.Properties["department"].Value != null) { singleUser.FirstName = de.Properties["givenName"].Value.ToString(); singleUser.LastName = de.Properties["sn"].Value != null ? de.Properties["sn"].Value.ToString() : ""; singleUser.EMail = de.Properties["mail"].Value != null ? de.Properties["mail"].Value.ToString() : ""; singleUser.UserName = de.Properties["sAMAccountName"].Value != null ? de.Properties["sAMAccountName"].Value.ToString() : ""; singleUser.Location = de.Properties["physicalDeliveryOfficeName"].Value.ToString(); singleUser.Department = de.Properties["department"].Value.ToString(); var sidBytes = (byte[])de.Properties["objectSid"].Value; SecurityIdentifier sid = new SecurityIdentifier(sidBytes, 0); singleUser.SID = sid.ToString(); model.Add(singleUser); } } } } return model; } private List<Department> getUniqueDepartments(List<UserRefreshModel> model) { List<Department> departments = model.Select(d => new Department { DepartmentName = d.Department }).ToList() .GroupBy(g => g.DepartmentName).Select(dpt => dpt.First()).ToList(); return departments; } private List<NSLocation> getUniqueLocations(List<UserRefreshModel> model) { List<NSLocation> locations = model.Select(l => new NSLocation { LocationCity = l.Location, LocationState = " ", LocationZip = 0}).ToList() .GroupBy(g => g.LocationCity).Select(loc => loc.First()).ToList(); return locations; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0 // Changes may cause incorrect behavior and will be lost if the code is regenerated. using System; using System.Linq; using Newtonsoft.Json.Linq; namespace ApartmentApps.Client.Models { public partial class VersionInfo { private int? _androidBuildNumber; /// <summary> /// Optional. /// </summary> public int? AndroidBuildNumber { get { return this._androidBuildNumber; } set { this._androidBuildNumber = value; } } private string _androidStoreUrl; /// <summary> /// Optional. /// </summary> public string AndroidStoreUrl { get { return this._androidStoreUrl; } set { this._androidStoreUrl = value; } } private int? _iPhoneBuildNumber; /// <summary> /// Optional. /// </summary> public int? IPhoneBuildNumber { get { return this._iPhoneBuildNumber; } set { this._iPhoneBuildNumber = value; } } private string _iPhoneStoreUrl; /// <summary> /// Optional. /// </summary> public string IPhoneStoreUrl { get { return this._iPhoneStoreUrl; } set { this._iPhoneStoreUrl = value; } } private double? _version; /// <summary> /// Optional. /// </summary> public double? Version { get { return this._version; } set { this._version = value; } } /// <summary> /// Initializes a new instance of the VersionInfo class. /// </summary> public VersionInfo() { } /// <summary> /// Deserialize the object /// </summary> public virtual void DeserializeJson(JToken inputObject) { if (inputObject != null && inputObject.Type != JTokenType.Null) { JToken androidBuildNumberValue = inputObject["AndroidBuildNumber"]; if (androidBuildNumberValue != null && androidBuildNumberValue.Type != JTokenType.Null) { this.AndroidBuildNumber = ((int)androidBuildNumberValue); } JToken androidStoreUrlValue = inputObject["AndroidStoreUrl"]; if (androidStoreUrlValue != null && androidStoreUrlValue.Type != JTokenType.Null) { this.AndroidStoreUrl = ((string)androidStoreUrlValue); } JToken iPhoneBuildNumberValue = inputObject["IPhoneBuildNumber"]; if (iPhoneBuildNumberValue != null && iPhoneBuildNumberValue.Type != JTokenType.Null) { this.IPhoneBuildNumber = ((int)iPhoneBuildNumberValue); } JToken iPhoneStoreUrlValue = inputObject["IPhoneStoreUrl"]; if (iPhoneStoreUrlValue != null && iPhoneStoreUrlValue.Type != JTokenType.Null) { this.IPhoneStoreUrl = ((string)iPhoneStoreUrlValue); } JToken versionValue = inputObject["Version"]; if (versionValue != null && versionValue.Type != JTokenType.Null) { this.Version = ((double)versionValue); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace AirMouseTab { class ServerDataMain { // int PORT = 7875; int bufSize = 32; bool continueReceive = true; private bool bRunServer = false; //Сервер запущен private void startReceive() { bRunServer = true; // DForm.changeStartBtn() } private void endReceive() { bRunServer = false; //DForm.changeStartBtn() } public bool isRunServer() { return bRunServer; } public void serverStop() { // println("otmena") continueReceive = false; } public void start(ConnectProp connectProp) { byte[] buf = new byte[bufSize]; try { startReceive(); IPAddress serverAddr = IPAddress.Parse(connectProp.ip); IPEndPoint endPoint = new IPEndPoint(serverAddr, connectProp.port); using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { var obrabotka = new Obrabotka( connectProp.pin); while (continueReceive) { try { socket.Receive(buf); byte ret = obrabotka.run(buf); if (ret >= Obrabotka.CLOSE) continueReceive = false; } catch(SocketException e) { } } } } catch { } finally { endReceive(); } } } }
using System; namespace Vehicles { class Program { static void doWork() { Console.WriteLine("Journey by Airplane"); Airplane myAirplane = new Airplane(); myAirplane.StartEngine("Contact"); myAirplane.TakeOff(); myAirplane.Drive(); myAirplane.Land(); myAirplane.StopEngine("Whirrrrrr"); Console.WriteLine("\nJourney by Car"); Car myCar = new Car(); myCar.StartEngine("Brmmmm brmmm"); myCar.Accelerate(); myCar.Drive(); myCar.Break(); myCar.StopEngine("Squeek squeeeeek"); Console.WriteLine("\n Polymorphism in Action"); Vehicle v = myCar; v.Drive(); v = myAirplane; v.Drive(); } static void Main() { try { doWork(); } catch (Exception ex) { Console.WriteLine("Exception: {0}", ex.Message); } } } }
using System; using Petanque.Model.Competitions; using Petanque.Model.Repository; using Petanque.Model.Results; using Petanque.Model.Teams; namespace Petanque.Model.Prices { public class PriceService { private readonly TeamService _teamService; private readonly MongoRepository<Competition> _competitionRepo; private readonly MongoRepository<Result> _resultRepo; public PriceService(TeamService teamService, MongoRepository<Competition> competitionRepo, MongoRepository<Result> resultRepo) { _teamService = teamService; _competitionRepo = competitionRepo; _resultRepo = resultRepo; } public void AttributPot(Competition competition) { competition.Pot = (competition.BetByTeam * competition.InitialTeams.Count) * competition.PercentOfThePot; _competitionRepo.Save(competition); } public void RefundTeam(Competition competition, Result result) { competition.Pot -= competition.BetByTeam; if (competition.Pot < 0) { throw new PotCannotBeNegatifException(); } result.TeamWin.Gain += competition.BetByTeam; result.GainProcessed = true; _teamService.Save(result.TeamWin); _resultRepo.Save(result); _competitionRepo.Save(competition); } /// <summary> /// Avalaible only for team refund /// </summary> public void RewardWinnerTeam(Competition competition, Result result) { if (competition.DynamicPot <= 0.01 && result.DepthOfTheGame < competition.Depth - 2) return; competition.Pot -= competition.PriceForEachGame; if (competition.Pot < 0) { throw new PotCannotBeNegatifException(); } result.TeamWin.Gain += competition.PriceForEachGame; result.GainProcessed = true; _teamService.Save(result.TeamWin); _resultRepo.Save(result); _competitionRepo.Save(competition); } public void AttributeGain(Competition competition, Result result) { if (result.TeamWin.WinInARow == 2) { RefundTeam(competition, result); } if (competition.AllCompetitorHavePlayedTwoTime && Math.Abs(competition.DynamicPot - 0) < 0.01) { competition.DynamicPot = competition.Pot; _competitionRepo.Save(competition); } RewardWinnerTeam(competition, result); } } }
using UnityEngine; using System; // using System.Collections; // using System.Collections.Generic; public class ParticleEffectsWrapper: MonoBehaviour { public bool doDestroy = true; public GameObject wrapper; private ParticleSystem ps; public delegate void TestDelegate(); public EffectItemVO effectItem; public TestDelegate methodToCall; // private UnityEngine.ParticleSystem.MainModule main; void Start() { Debug.Log("<color=blue>========== Start ===========</color>"); ps = GetComponent<ParticleSystem>(); ps.Clear(); ps.Play(); var main = ps.main; main.stopAction = ParticleSystemStopAction.Callback; if (effectItem.autoDelete == true) main.loop = false; } public void AddItem(EffectItemVO item) { effectItem = item; effectItem.timeStart = Time.fixedTime; // var main = ps.main; // if (effectItem.autoDelete == true) // main.loop = false; } public void SetDelegateFunc(TestDelegate handler) { methodToCall = handler; } public void OnParticleSystemStopped() { Debug.Log("<color=blue>========== Stop ===========</color>"); effectItem.timeEnd = Time.fixedTime; // if (doDestroy == true) if (effectItem.autoDelete == true) { methodToCall(); Destroy(this); } // transform.parent = null; // particleSystem.main.stopAction = ParticleSystemStopAction.Destroy; // Destroy(particleSystem); // Destroy(GetComponent<ParticleSystem>().main); } }
using System; namespace OpenHMDNet { public class NoOpenHMDContextSpecifiedException : Exception { public NoOpenHMDContextSpecifiedException(string message) : base(message) { } } public class OpenHMDContextAlreadyOpened : Exception { public OpenHMDContextAlreadyOpened(string message) : base(message) { } } public class OpenHMDDeviceAlreadyOpened : Exception { public OpenHMDDeviceAlreadyOpened(string message) : base(message) { } } public class DeviceNotOpenedException : Exception { public DeviceNotOpenedException(string message) : base(message) { } } public class CanNotFindPlatform : Exception { public CanNotFindPlatform(string message) : base(message) { } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace XH.APIs.WebAPI.Models.Categories { [DataContract] public class UpdateCategoryRequest : CreateOrUpdateCategoryRequest { [DataMember] [Required] public string Id { get; set; } } }
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 JustRipeFarm.ClassEntity; namespace JustRipeFarm { public partial class FormProduct : Form { public string state = ""; public Product prodd; public FormProduct() { InitializeComponent(); } private void btnDone_Click(object sender, EventArgs e) { if (state == "Edit") { update(); } else { if (String.IsNullOrEmpty(nameText.Text)) { if (String.IsNullOrEmpty(typeText.Text)) { if (String.IsNullOrEmpty(quantityNumericUpDown.Text)) { if (String.IsNullOrEmpty(weightText.Text)) { if (String.IsNullOrEmpty(boxIdText.Text)) { MessageBox.Show("Please fill up the box"); } MessageBox.Show("Please fill up the box"); } MessageBox.Show("Please fill up the box"); } MessageBox.Show("Please fill up the box"); } MessageBox.Show("Please fill up the box"); } else { add(); } } } private void add() { Product prod = new Product(); prod.Name = nameText.Text; prod.Type = typeText.Text; prod.Quantity_box = Convert.ToInt32(quantityNumericUpDown.Value); prod.Weight = decimal.Parse(weightText.Text); prod.Box_id = Int32.Parse(boxIdText.Text); InsertSQL prodHnd = new InsertSQL(); int addrecord = prodHnd.addNewProduct(prod); MessageBox.Show("Your record is added"); this.Close(); } private void update() { Product prod = new Product(); prod.Id = prodd.Id; prod.Name = nameText.Text; prod.Type = typeText.Text; prod.Quantity_box = Convert.ToInt32(quantityNumericUpDown.Value); prod.Weight = decimal.Parse(weightText.Text); prod.Box_id = Int32.Parse(boxIdText.Text); UpdateSQL prodHnd = new UpdateSQL(); int updaterecord = prodHnd.updateProduct(prod); MessageBox.Show(updaterecord + " Your record is added"); this.Close(); } private void FormProduct_Load(object sender, EventArgs e) { InsertSQL product = new InsertSQL(); if (state == "Edit") { nameText.Text = prodd.Name; typeText.Text = prodd.Type; quantityNumericUpDown.Text = prodd.Quantity_box.ToString(); weightText.Text = prodd.Weight.ToString(); boxIdText.Text = prodd.Box_id.ToString(); } } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Net.NetworkInformation; using System.Management; using IRAP.Global; namespace IRAP_MaterialRequestImport { public abstract class TStationUser : TBaseUser { protected string ipAddress = ""; protected string macAddress = ""; public TStationUser() { macAddress = ""; // 获取当前的 IP 地址 HostToIP(ref ipAddress); // 如果配置文件中设置了 MAC 地址,并且指明使用 MAC 地址,则读取该配置的 MAC 地址 string strCFGFileName = string.Format(@"{0}\IRAP.ini", AppDomain.CurrentDomain.BaseDirectory); bool usingVirtualAddr = IniFile.ReadBool( "Virtual Station", "Virtual Station Used", false, strCFGFileName); if (usingVirtualAddr) { macAddress = IniFile.ReadString( "Virtual Station", "Virtual Station", "", strCFGFileName); } if (macAddress.Trim() == "") { string macAddresses = RDPClientMAC.GetRDPMacAddress(); string[] arrMacAddress = macAddresses.Split(';'); if (arrMacAddress.Length > 0) macAddress = arrMacAddress[0]; else macAddress = "FFFFFFFFFFFF"; } } #region 属性 public string IPAddress { get { return IPAddress; } } public string MacAddress { get { return macAddress; } } #endregion private bool HostToIP1(ref string ipAddress) { IPAddress[] arrayIPAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList; for (int i = 0; i < arrayIPAddress.Length; i++) { // 从 IP 地址列表中筛选出 IPv4 类型的地址 // AddressFamily.InterNetwork 表示此地址为 IPv4 // AddressFamily.InterNetworkV6 表示此地址为 IPv6 if (arrayIPAddress[i].AddressFamily == AddressFamily.InterNetwork) { ipAddress = arrayIPAddress[i].ToString(); return true; } } ipAddress = "127.0.0.1"; return true; } private bool HostToIP(ref string ipAddress) { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection nics = mc.GetInstances(); foreach (ManagementObject nic in nics) { if (Convert.ToBoolean(nic["ipEnabled"])) { ipAddress = (nic["ipAddress"] as string[])[0]; return true; } } ipAddress = "127.0.0.1"; return true; } private bool HostToIP2(ref string ipAddress) { try { // 获得网络接口,网卡、拨号器、适配器都会有一个网络接口 NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface network in networkInterfaces) { // 获得当前网络接口属性 IPInterfaceProperties properties = network.GetIPProperties(); // 每个网络接口可能会有多个 IP 地址 foreach (IPAddressInformation address in properties.UnicastAddresses) { // 如果此 IP 不是 IPv4,则进行下一次循环 if (address.Address.AddressFamily != AddressFamily.InterNetwork) continue; // 忽略 127.0.0.1 if (System.Net.IPAddress.IsLoopback(address.Address)) continue; ipAddress = address.Address.ToString(); return true; } } ipAddress = "127.0.0.1"; return true; } catch { ipAddress = "127.0.0.1"; return true; } } protected virtual void GetMacAddress() { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { try { if ((bool)mo["IPEnabled"]) { macAddress = mo["MacAddress"].ToString(); macAddress = macAddress.Replace(":", ""); break; } } catch { mo.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Breeze { public class ScreenAbstractor { public FloatRectangle bounds; public Vector2 Translate(Vector2 input) => new Vector2(bounds.X + (bounds.Width * input.X), bounds.Y + (bounds.Height * input.Y)); public float Untranslate(float input) { var result = input / bounds.Height; return result; } public FloatRectangle? Translate(FloatRectangle? input) { if (!input.HasValue) { return null; } var b = bounds; if (input.Value.Boundless) { b = new FloatRectangle(Solids.Instance.Bounds); } return new FloatRectangle( b.X + (b.Width * input.Value.X), b.Y + (b.Height * input.Value.Y), b.Width * input.Value.Width, b.Height * input.Value.Height ); } public Vector3 FromScreenSpace(Vector2 v) { float hw = bounds.Width / 2f; float hh = bounds.Height / 2f; float x = v.X - hw; x = x / hw; float y = v.Y - hh; y = y / hh; var result = new Vector3(x, -y, 0); return result; } public void SetBounds(Rectangle bounds) { this.bounds = new FloatRectangle(bounds); } public void SetBounds(FloatRectangle bounds) { this.bounds = bounds; } public Vector2 AbstractedSize(Texture2D texture) { return new Vector2(texture.Width / bounds.Width, texture.Height / bounds.Height); } public bool IsWithinBounds(FloatRectangle fr) { return ((fr.BottomRight.X > bounds.X || fr.TopLeft.X < bounds.BottomRight.X) && (fr.BottomRight.Y > bounds.Y || fr.TopLeft.Y < bounds.BottomRight.Y)); } } public struct FloatRectangle : IComparable { public override string ToString() { return $"X:{X}, Y:{Y}, W:{Width}, H:{Height}"; } public float X; public float Y; public float Width; public float Height; public bool Boundless; public Vector2 TopLeft => new Vector2(X, Y); public Vector2 BottomRight => new Vector2(X + Width, Y + Height); public float Right => X + Width; public float Bottom => Y + Height; public Rectangle ToRectangle => new Rectangle((int)X, (int)Y, (int)Width, (int)Height); public Vector2 ToVector2 => new Vector2(X, Y); public Vector2 Centre => new Vector2(X + (Width / 2f), Y + (Height / 2f)); public FloatRectangle(float x, float y, float width, float height, bool boundless = false) { this.X = x; this.Y = y; this.Width = width; this.Height = height; this.Boundless = boundless; } public FloatRectangle(Rectangle rectangle, bool boundless = false) { this.X = rectangle.X; this.Y = rectangle.Y; this.Width = rectangle.Width; this.Height = rectangle.Height; this.Boundless = boundless; } public FloatRectangle(FloatRectangle rectangle, bool boundless = false) { this.X = rectangle.X; this.Y = rectangle.Y; this.Width = rectangle.Width; this.Height = rectangle.Height; this.Boundless = boundless; } public FloatRectangle(string input) { if (input.StartsWith("\"")) input = input.Substring(1); if (input.EndsWith("\"")) input = input.Substring(0, input.Length - 1); var parts = input.Split(','); float x = float.Parse(parts[0]); float y = float.Parse(parts[1]); float w = float.Parse(parts[2]); float h = float.Parse(parts[3]); this.X = x; this.Y = y; this.Width = w; this.Height = h; this.Boundless = false; } public static FloatRectangle FullSize() { return new FloatRectangle(0, 0, 1, 1); } public FloatRectangle Move(Vector2 vector2) { return new FloatRectangle(this.X + vector2.X, this.Y + vector2.Y, this.Width, this.Height); } public FloatRectangle Move(Vector2? vector2d) { if (vector2d.HasValue) { Vector2 vector2 = vector2d.Value; return new FloatRectangle(this.X + vector2.X, this.Y + vector2.Y, this.Width, this.Height); } else { return this; } } public int CompareTo(object obj) { throw new NotImplementedException(); } } }
using Fingo.Auth.Domain.Infrastructure.EventBus.Events.Base; namespace Fingo.Auth.Domain.Infrastructure.EventBus.Events.CustomData { public class CustomDataRemoved : EventBase { public CustomDataRemoved(int projectId , string name) { ProjectId = projectId; Name = name; } public int ProjectId { get; set; } public string Name { get; set; } public override string ToString() { return $"Custom data (name: {Name}) deleted from project (id: {ProjectId})."; } } }
using LoowooTech.Updater.Entities; using System; using System.Collections.Generic; using System.Text; namespace LoowooTech.Updater { public enum UpdateStateChangeStateEnum { InProgress,Done,Fail } public class UpdateProgressChangedEventArgs:EventArgs { public string Message { get; set; } public long TotalProgress { get; set; } public long CurrentProgress { get; set; } public UpdateStateChangeStateEnum State { get; set; } public bool NeedCancel { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SpawnWaveManagement : MonoBehaviour { public GameObject[] Path1; public GameObject[] Path2; private GameObject[][] Paths; public Wave[] Waves; public int currentWave = 0; public int timeBetweenWaves= 5; private float lastSpawnTime; private int enemiesSpawned = 0; public Text waveCounter; // Use this for initialization void Start() { lastSpawnTime = Time.time; Paths = new GameObject[2][]; Paths[0] = Path1; Paths[1] = Path2; waveCounter.text = "Wave left: " + Waves.Length.ToString(); } // Update is called once per frame void Update() { waveCounter.text = "Wave left: " + (Waves.Length - currentWave).ToString(); if (currentWave < Waves.Length) { // 2 float timeInterval = Time.time - lastSpawnTime; float spawnInterval = Waves[currentWave].spawnInterval; if (((enemiesSpawned == 0 && timeInterval > timeBetweenWaves) || timeInterval > spawnInterval) && enemiesSpawned < Waves[currentWave].maxEnemies) { // 3 lastSpawnTime = Time.time; int which = Random.Range(0, 2); GameObject newEnemy = (GameObject) Instantiate(Waves[currentWave].Enemy); newEnemy.GetComponent<EnemyMovement>().Waypoints = Paths[which]; enemiesSpawned++; } // 4 if (enemiesSpawned == Waves[currentWave].maxEnemies && GameObject.FindGameObjectWithTag("Enemy") == null) { currentWave++; //gameManager.Gold = Mathf.RoundToInt(gameManager.Gold * 1.1f); enemiesSpawned = 0; lastSpawnTime = Time.time; } // 5 } } } [System.Serializable] public class Wave { public GameObject Enemy; public float spawnInterval; public int maxEnemies; }
using AuraAPI; using UnityEngine; using UnityEngine.Rendering.PostProcessing; namespace Player { public class StressPostEffect : MonoBehaviour { [SerializeField] private PostProcessVolume _calm; [SerializeField] private PostProcessVolume _stressed; private PlayerInfo _player; private void Awake() { _player = FindObjectOfType<PlayerInfo>(); } private void Update() { float StressPerc = _player.stressBar / 100f; _calm.weight = StressPerc; _stressed.weight = 1f - StressPerc; } } }
using MISA.Common.Models; using System; using System.Collections.Generic; using System.Text; namespace MISA.Business.Interface { public interface IGroupCustomerService: IBaseService<GroupCustomer> { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum InputState { Character, Inventory, ActionBox, Dialogue, DialogueBox, Settings, Map, Cutscene, NoInput } public class GameManager : MonoBehaviour { // Singleton // public static GameManager instance { get; protected set; } void Awake () { if (instance == null) { instance = this; } else if (instance != this) { Destroy (gameObject); } } // Singleton // public static bool actionBoxActive = false; public static bool textBoxActive = false; public static bool inventoryOpen = false; public static bool settingsOpen = false; public static bool mapOpen = false; public static bool dialogueTreeBoxActive = false; public static Dictionary<string,Color> speakerColorMap; public static Room roomToLoad; public Dictionary<string,Room> stringRoomMap = new Dictionary<string, Room> (); public static UserData userData; public static GameData gameData; public static Dictionary<string,GameObject> stringPrefabMap; public InputState inputState = InputState.Character; // Use this for initialization public void Initialize () { CreateRooms (); if (roomToLoad == null) { if (PlayerManager.myPlayer.currentRoom == "None") { roomToLoad = stringRoomMap ["bus_stop_mirror"]; } else { roomToLoad = stringRoomMap [PlayerManager.myPlayer.currentRoom]; } } speakerColorMap = new Dictionary<string, Color> (); speakerColorMap.Add("Daniel", Color.white); speakerColorMap.Add("geM", Color.magenta); speakerColorMap.Add("llehctiM", Color.cyan); speakerColorMap.Add("Stella", Color.red); speakerColorMap.Add("technician", new Color(254f,253f,158f)); speakerColorMap.Add("technician_reflection", new Color(254f,253f,158f)); speakerColorMap.Add("bartender_reflection", Color.blue); speakerColorMap.Add("man_water_reflection", Color.cyan); speakerColorMap.Add("cop_reflection", new Color (253,205,169)); speakerColorMap.Add("cop", new Color (253,205,169)); if (stringPrefabMap == null) { LoadPrefabs (); } } // Update is called once per frame void Update () { if (Input.GetKeyDown (KeyCode.R)) { CreateNewData (); } /* if (Input.GetKeyDown (KeyCode.B)) { RoomManager.instance.myRoom.myMirrorRoom.inTheShadow = !RoomManager.instance.myRoom.myMirrorRoom.inTheShadow; RoomManager.instance.SwitchObjectByShadowState(false); } */ } public void CreateRooms () { Object[] myTextAssets = Resources.LoadAll ("Jsons/Rooms"); foreach (TextAsset txt in myTextAssets) { Room myRoom = JsonUtility.FromJson<Room> (txt.text); //Debug.Log (myRoom.myName + " - " + myRoom.bgFlipped); // Adding room to dictionary stringRoomMap.Add (myRoom.myName, myRoom); } } public void LoadPrefabs() { stringPrefabMap = new Dictionary<string, GameObject> (); GameObject[] furnitureArray = Resources.LoadAll<GameObject> ("Prefabs/Furniture"); GameObject[] characterArray = Resources.LoadAll<GameObject> ("Prefabs/Characters"); foreach (GameObject obj in furnitureArray) { stringPrefabMap.Add (obj.name, obj); } foreach (GameObject obj in characterArray) { stringPrefabMap.Add (obj.name, obj); } } public void CreateInventoryItemData() { if (gameData != null) { return; } gameData = new GameData (); } /* ----- SAVING AND LOADING ----- */ public void CreateUserData () { if (userData != null) { return; } // Loading data if (PlayerPrefs.HasKey ("PlayerData")) { userData = JsonUtility.FromJson<UserData> (PlayerPrefs.GetString ("PlayerData")); // setting current player PlayerManager.instance.CreatePlayers (); Player currentPlayer = PlayerManager.instance.GetPlayerByName(userData.currentActivePlayer); if (currentPlayer != null) { PlayerManager.myPlayer = currentPlayer; PlayerManager.myPlayer.isActive = true; } // Player data foreach (PlayerData playerData in userData.playerDataList) { // set current room of the player according to current room from data Player player = PlayerManager.instance.GetPlayerByName (playerData.playerName); player.currentRoom = playerData.currentRoom; player.myPos = playerData.currentPos; foreach (InventoryItem item in playerData.inventory.items) { item.Initialize (); } } } else { // Creating new data CreateNewData (); } } public void CreateNewData () { Debug.Log ("Creating new data"); PlayerManager.instance.CreatePlayers (); userData = new UserData (); userData.currentActivePlayer = "Daniel"; PlayerManager.myPlayer = PlayerManager.instance.GetPlayerByName ("Daniel"); PlayerManager.myPlayer.isActive = true; foreach (Player player in PlayerManager.playerList) { PlayerData data = new PlayerData(player.identificationName); userData.playerDataList.Add (data); data.currentRoom = player.startingRoom; player.currentRoom = player.startingRoom; player.myPos = player.startingPos; } SaveData (); } public void SaveData () { if (userData != null) { string data = JsonUtility.ToJson (userData); PlayerPrefs.SetString ("PlayerData", data); //Debug.Log ("data: " + data); } } }
using Microsoft.Practices.Unity; using System; namespace Problem1.Infrastructure { /// <summary> /// Контекст запуска группы тестов, содержащий IoC-контейнер. /// </summary> public abstract class UnityContainerFixtureBase : IDisposable { protected IUnityContainer Container; protected UnityContainerFixtureBase() { Container = new UnityContainer(); } #region IDisposable Support private bool _disposed; protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) Container.Dispose(); _disposed = true; } } void IDisposable.Dispose() { Dispose(true); } #endregion } }
using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace MundoMascotaRosario.Models { public class Rol { [Key] public int RolId { get; set; } [DisplayName("Rol")] [Required] public string Descripcion { get; set; } public virtual ICollection<Usuario> Usuarios { get; set; } public virtual ICollection<Perfil> Perfiles { get; set; } public virtual ICollection<RolMenu> RolesMenus { get; set; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Configuration; using CAPCO.Infrastructure.Domain; namespace CAPCO.Infrastructure.Data { public class CAPCOContext : DbContext { /// <summary> /// Initializes a new instance of the ThePypeContext class. /// </summary> public CAPCOContext() : base(ConfigurationManager.ConnectionStrings["CAPCO.Web"].ConnectionString) { } public DbSet<ProductGroup> ProductGroups { get; set; } public DbSet<ProductType> ProductTypes { get; set; } public DbSet<ProductCategory> ProductCategories { get; set; } public DbSet<ProductColor> ProductColors { get; set; } public DbSet<ProductSize> ProductSizes { get; set; } public DbSet<ProductFinish> ProductFinishes { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Project> ProductBundles { get; set; } public DbSet<Notification> Notifications { get; set; } public DbSet<ApplicationUser> ApplicationUsers { get; set; } public DbSet<PriceCode> PriceCodes { get; set; } public DbSet<ProductStatus> ProductStatus { get; set; } public DbSet<ProductVariation> ProductVariations { get; set; } public DbSet<ProductUnitOfMeasure> ProductUnitOfMeasures { get; set; } public DbSet<ProductImage> ProductImages { get; set; } public DbSet<ProjectComment> ProjectComments { get; set; } public DbSet<ProjectInvitation> ProjectInvitations { get; set; } public DbSet<SliderImage> SliderImages { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //this.Configuration.LazyLoadingEnabled = false; modelBuilder.Entity<Project>() .HasMany<ApplicationUser>(c => c.Users).WithMany().Map(x => x.ToTable("ProjectApplicationUsers")); modelBuilder.Entity<Product>() .HasMany<Product>(x => x.RelatedSizes) .WithMany() .Map(x => x.ToTable("ProductRelatedSizes")); modelBuilder.Entity<Product>() .HasMany<Product>(x => x.RelatedAccents) .WithMany() .Map(x => x.ToTable("ProductRelatedAccents")); modelBuilder.Entity<Product>() .HasMany<Product>(x => x.RelatedTrims) .WithMany() .Map(x => x.ToTable("ProductRelatedTrims")); modelBuilder.Entity<Product>() .HasMany<Product>(x => x.RelatedFinishes) .WithMany() .Map(x => x.ToTable("ProductRelatedFinishes")); modelBuilder.Entity<PriceGroup>() .HasMany<ProductPriceCode>(x => x.PriceCodes) .WithRequired(x => x.PriceGroup) .Map(x => x.ToTable("ProductPriceCodes").MapKey("PriceGroup_Id")); modelBuilder.Entity<Product>() .HasOptional(x => x.PriceGroup) .WithMany(x => x.Products); } public DbSet<PriceGroup> PriceGroups { get; set; } public DbSet<ContentSection> ContentSections { get; set; } public DbSet<Manufacturer> Manufacturers { get; set; } public DbSet<PickupLocation> PickupLocations { get; set; } public DbSet<DiscountCode> DiscountCodes { get; set; } public DbSet<StoreLocation> StoreLocations { get; set; } public DbSet<ContactRequest> ContactRequests { get; set; } public DbSet<AccountRequest> AccountRequests { get; set; } public DbSet<ProductUsage> ProductUsages { get; set; } public DbSet<RelatedProductSize> OtherSizes { get; set; } public DbSet<RelatedAccent> RelatedAccents { get; set; } public DbSet<RelatedTrim> RelatedTrims { get; set; } public DbSet<ProductPriceCode> ProductPriceCodes { get; set; } public DbSet<Link> Links { get; set; } public DbSet<ProductSeries> ProductSeries { get; set; } } }
// <copyright file="FirstTaskTest.cs" company="MyCompany.com"> // Contains the solutions to tasks of the 'Encapsulation. Inheritance. Polymorphism' module. // </copyright> // <author>Daryn Akhmetov</author> namespace Encapsulation._Inheritance._Polymorphism_Tests { using System; using Encapsulation._Inheritance._Polymorphism; using NUnit.Framework; /// <summary> /// This is a test class for FirstTask and is intended /// to contain all FirstTask Unit Tests. /// </summary> [TestFixture] public class FirstTaskTest { /// <summary> /// Unsorted array used to test methods. /// </summary> private static readonly int[][] UnsortedArray = new int[][] { new[] { 11, 34, 67, -89, 8 }, new[] { 1, 4, 3, 2, 5 }, new[] { 89, 23, 39, 12, -54 }, new[] { 0, 0, 0, 0, 0 }, new[] { -3, -54, -99, 81, 66 } }; /// <summary> /// Array sorted in order of increasing sums of row elements. /// </summary> private static readonly int[][] ArraySortedInOrderOfIncreasingSumsOfRowElements = new int[][] { new[] { -3, -54, -99, 81, 66 }, new[] { 0, 0, 0, 0, 0 }, new[] { 1, 4, 3, 2, 5 }, new[] { 11, 34, 67, -89, 8 }, new[] { 89, 23, 39, 12, -54 } }; /// <summary> /// Array sorted in order of decreasing sums of row elements. /// </summary> private static readonly int[][] ArraySortedInOrderOfDecreasingSumsOfRowElements = new int[][] { new[] { 89, 23, 39, 12, -54 }, new[] { 11, 34, 67, -89, 8 }, new[] { 1, 4, 3, 2, 5 }, new[] { 0, 0, 0, 0, 0 }, new[] { -3, -54, -99, 81, 66 } }; /// <summary> /// Array sorted in order of increasing maximum elements in a row. /// </summary> private static readonly int[][] ArraySortedInOrderOfIncreasingMaximumElements = new int[][] { new[] { 0, 0, 0, 0, 0 }, new[] { 1, 4, 3, 2, 5 }, new[] { 11, 34, 67, -89, 8 }, new[] { -3, -54, -99, 81, 66 }, new[] { 89, 23, 39, 12, -54 } }; /// <summary> /// Array sorted in order of decreasing maximum elements in a row. /// </summary> private static readonly int[][] ArraySortedInOrderOfDecreasingMaximumElements = new int[][] { new[] { 89, 23, 39, 12, -54 }, new[] { -3, -54, -99, 81, 66 }, new[] { 11, 34, 67, -89, 8 }, new[] { 1, 4, 3, 2, 5 }, new[] { 0, 0, 0, 0, 0 } }; /// <summary> /// Array sorted in order of increasing minimum elements in a row. /// </summary> private static readonly int[][] ArraySortedInOrderOfIncreasingMinimumElements = new int[][] { new[] { -3, -54, -99, 81, 66 }, new[] { 11, 34, 67, -89, 8 }, new[] { 89, 23, 39, 12, -54 }, new[] { 0, 0, 0, 0, 0 }, new[] { 1, 4, 3, 2, 5 } }; /// <summary> /// Array sorted in order of decreasing minimum elements in a row. /// </summary> private static readonly int[][] ArraySortedInOrderOfDecreasingMinimumElements = new int[][] { new[] { 1, 4, 3, 2, 5 }, new[] { 0, 0, 0, 0, 0 }, new[] { 89, 23, 39, 12, -54 }, new[] { 11, 34, 67, -89, 8 }, new[] { -3, -54, -99, 81, 66 } }; /// <summary> /// A test for Accept. /// </summary> /// <param name="visitorType">Type of the visitor.</param> [TestCase(typeof(FirstTask.IncreasingSumsOfRowElements))] [TestCase(typeof(FirstTask.DecreasingSumsOfRowElements))] [TestCase(typeof(FirstTask.IncreasingMaximumElement))] [TestCase(typeof(FirstTask.DecreasingMaximumElement))] [TestCase(typeof(FirstTask.IncreasingMinimumElement))] [TestCase(typeof(FirstTask.DecreasingMinimumElement))] public void SortArrayRowsTest(Type visitorType) { // Create Matrix object from array. var matrix = new FirstTask.Matrix(UnsortedArray); // Create instance of visitor. var visitor = (FirstTask.IVisitor)Activator.CreateInstance(visitorType); // Matrix object is visited which leads to calling that implementation of Visit method that corresponds to visitor. matrix.Accept(visitor); // Get sorted array from Matrix object. var actualResult = matrix.Array; // Verify the result. if (visitorType == typeof(FirstTask.IncreasingSumsOfRowElements)) { Assert.AreEqual(ArraySortedInOrderOfIncreasingSumsOfRowElements, actualResult); } else if (visitorType == typeof(FirstTask.DecreasingSumsOfRowElements)) { Assert.AreEqual(ArraySortedInOrderOfDecreasingSumsOfRowElements, actualResult); } else if (visitorType == typeof(FirstTask.IncreasingMaximumElement)) { Assert.AreEqual(ArraySortedInOrderOfIncreasingMaximumElements, actualResult); } else if (visitorType == typeof(FirstTask.DecreasingMaximumElement)) { Assert.AreEqual(ArraySortedInOrderOfDecreasingMaximumElements, actualResult); } else if (visitorType == typeof(FirstTask.IncreasingMinimumElement)) { Assert.AreEqual(ArraySortedInOrderOfIncreasingMinimumElements, actualResult); } else if (visitorType == typeof(FirstTask.DecreasingMinimumElement)) { Assert.AreEqual(ArraySortedInOrderOfDecreasingMinimumElements, actualResult); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Ports; using System.IO; namespace Ajustador_Calibrador_ADR3000.Helpers { public class SerialPortReader { // http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport // https://stackoverflow.com/questions/6759938/stop-stream-beginread private readonly SerialPort _port; private readonly byte[] _buffer; private readonly Action<byte[]> _dataReceivedAction; private readonly Action<Exception> _serialErrorAction; private readonly Action _kickoffRead = null; private IAsyncResult _ar; public SerialPortReader(SerialPort port, int bufferSize, Action<byte[]> dataReceivedAction, Action<Exception> serialErrorAction) { _port = port; _buffer = new byte[bufferSize]; _dataReceivedAction = dataReceivedAction; _serialErrorAction = serialErrorAction; _kickoffRead = delegate () { try { _port.BaseStream.BeginRead(_buffer, 0, _buffer.Length, delegate (IAsyncResult ar) { _ar = ar; try { if (!_port.IsOpen) { // the port has been closed, so exit quietly return; } int actualLength = _port.BaseStream.EndRead(ar); if (actualLength > 0) { byte[] received = new byte[actualLength]; Buffer.BlockCopy(_buffer, 0, received, 0, actualLength); _dataReceivedAction(received); } _kickoffRead(); } catch (Exception e) { _serialErrorAction(e); } }, null); } catch (Exception ex) { _serialErrorAction(ex); } }; _kickoffRead(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WallsFollow : MonoBehaviour { public GameObject playerTofollow; public float offsetToplayer; public void Update() { transform.position = new Vector3(0f, playerTofollow.transform.position.y + offsetToplayer, 0f); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Xlns.BusBook.Core.Model; using Xlns.BusBook.Core.Repository; namespace Xlns.BusBook.UI.Web.Models { public class MenuView { public Utente Utente { get; set; } public IList<Messaggio> Messaggi { get; set; } public MenuView(Utente utente) { Utente = utente; var mr = new MessaggioRepository(); Messaggi = mr.GetMessaggiUnreadByDestinatario(utente.Id); } } }
namespace Jypeli { /// <summary> /// Rajapinta päivittyville olioille. /// </summary> public interface Updatable { /// <summary> /// Ajetaanko oliolle päivitystä /// </summary> bool IsUpdated { get; } /// <summary> /// Päivitysfunktio /// </summary> /// <param name="time">Kulunut aika edellisestä päivityksestä</param> void Update(Time time); } }
using UnityEngine; using System.Collections; public class PreprocessingCollider : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter(Collider other) { if (other.gameObject.layer.Equals(MyTags.Wide_Wall_Collider_Layer) && !Jump._judge_Bool) { Jump._judge_Bool = true; } } }
using jaytwo.Common.Extensions; using jaytwo.Common.Http; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace jaytwo.Common.Test.Http.UrlHelperTests { public static class SetPortTests { private static IEnumerable<TestCaseData> UrlHelper_SetUriPort_TestCases() { yield return new TestCaseData(null, 80).Throws(typeof(ArgumentNullException)); yield return new TestCaseData("www.google.com", null).Throws(typeof(InvalidOperationException)); yield return new TestCaseData("http://www.google.com:123", null).Returns("http://www.google.com/"); yield return new TestCaseData("http://www.google.com", 80).Returns("http://www.google.com/"); yield return new TestCaseData("https://www.google.com", 80).Returns("https://www.google.com:80/"); yield return new TestCaseData("https://www.google.com", 443).Returns("https://www.google.com/"); yield return new TestCaseData("http://www.google.com", 443).Returns("http://www.google.com:443/"); } [Test] [TestCaseSource("UrlHelper_SetUriPort_TestCases")] public static string UrlHelper_SetUriPort(string url, int? newPort) { var uri = TestUtility.GetUriFromString(url); return UrlHelper.SetUriPort(uri, newPort).ToString(); } [Test] [TestCaseSource("UrlHelper_SetUriPort_TestCases")] public static string UrlHelper_SetUrlPort(string url, int? newPort) { return UrlHelper.SetUrlPort(url, newPort); } [Test] [TestCaseSource("UrlHelper_SetUriPort_TestCases")] public static string HttpExtensionMethods_WithPort(string url, int? newPort) { var uri = TestUtility.GetUriFromString(url); return uri.WithPort(newPort).ToString(); } } }
using Microsoft.Extensions.Configuration.CommandLine; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Linq; namespace CsRemoveComment { class Program { //待处理列表 private static List<string> sb = new List<string>(); //排除获取文件夹 private readonly static List<String> _exclusion = new List<String> { "bin", "obj", ".git", ".vs" }; static void Main(string[] args) { var cmdLineConfig = new CommandLineConfigurationProvider(args); cmdLineConfig.Load(); cmdLineConfig.TryGet("From", out string FromFile); cmdLineConfig.TryGet("To", out string ToFile); if (string.IsNullOrWhiteSpace(FromFile) || string.IsNullOrWhiteSpace(ToFile)) { var path = Environment.CurrentDirectory; var input = File.ReadAllText($@"{path}\text\TestClass.csts"); RemoveAllCommentStr(input, out string noComments2, out List<string> list2); foreach (var comment in list2) Console.WriteLine(comment); Console.WriteLine("--------------"); Console.WriteLine(noComments2); Console.WriteLine("没有设置正确参数From(来源文件夹)和To(目标文件夹)"); Console.ReadLine(); return; } Console.WriteLine("等待扫描来源文件夹"); //获得来源文件 GetFiles(new DirectoryInfo(FromFile), "*.*"); foreach (var item in sb) { var newFullFile = item.Replace(FromFile, ToFile); var newPath = Path.GetDirectoryName(newFullFile); if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } //处理文件 if (!File.Exists(newFullFile) && Path.GetExtension(newFullFile).Contains(".cs")) { var file = File.ReadAllText(item); RemoveAllCommentStr(file, out string noComments, out List<string> list); File.WriteAllText(newFullFile, noComments); Console.WriteLine($"处理文件:{newFullFile}"); } else if (!File.Exists(newFullFile) && !Path.GetExtension(newFullFile).Contains(".cs")) { File.Copy(item, newFullFile); Console.WriteLine($"复制:{newFullFile}"); } } Console.WriteLine("完成"); Console.ReadLine(); } public static void GetFiles(DirectoryInfo directory, string pattern) { if (directory.Exists || pattern.Trim() != string.Empty) { foreach (FileInfo info in directory.GetFiles(pattern)) { sb.Add(info.FullName.ToString()); } foreach (DirectoryInfo info in directory.GetDirectories().Where(d => !FoundInArray(_exclusion, d.FullName))) { GetFiles(info, pattern); } } } public static bool FoundInArray(List<string> arr, string target) { return arr.Any(p => new DirectoryInfo(target).Name == p); } /// <summary> ///删除注释 ///参考来自https://stackoverflow.com/questions/3524317/regex-to-strip-line-comments-from-c-sharp/3524689#3524689 /// </summary> /// <param name="input"></param> /// <param name="outlist"></param> /// <param name="noComments"></param> private static void RemoveAllCommentStr(string input, out string noComments, out List<string> outlist) { var list = new List<string>(); var blockComments = @"/\*(.*?)\*/"; var lineComments = @"//(.*?)(\r?\n|$)"; var strings = @"""((\\[^\n]|[^""\n])*)"""; var verbatimStrings = @"@(""[^""]*"")+"; noComments = Regex.Replace(input, blockComments + "|" + lineComments + "|" + strings + "|" + verbatimStrings, me => { if (me.Value.StartsWith("/*") || me.Value.StartsWith("//")) { // 将注释内容放入列表中 list.Add(me.Groups[1].Value + me.Groups[2].Value); // 将注释替换为空, 即删除它们 return me.Value.StartsWith("//") ? me.Groups[3].Value : ""; } // 保留字面字符串 return me.Value; }, RegexOptions.Singleline); outlist = list; } } }
using System; using System.Collections.Generic; using EPI.Sorting; namespace EPI.Recursion { /// <summary> /// You are given a list of points in a 2D cartesian plane. Each point has an /// x, y integer coordinates. /// How would you find the two closest points? /// </summary> public static class FindClosestPoints { public class Point { public int X; public int Y; public Point(int x, int y) { X = x; Y = y; } public static double Distance(Point a, Point b) { return Math.Sqrt(((a.X - b.X) * (a.X - b.X)) + ((a.Y - b.Y) * (a.Y - b.Y))); } }; private class PointWithXComparison : Point, IComparable { public PointWithXComparison(int x, int y) : base(x,y){} public int CompareTo(object obj) { var other = obj as PointWithXComparison; if (null != other) { return this.X.CompareTo(other.X); } throw new InvalidOperationException(); } } private class PointWithYComparison : Point, IComparable { public PointWithYComparison(int x, int y) : base(x, y) { } public int CompareTo(object obj) { var other = obj as PointWithYComparison; if (null != other) { return this.Y.CompareTo(other.Y); } throw new InvalidOperationException(); } } private struct Pair { internal Point a; internal Point b; internal double distance; }; public static Tuple<Point, Point> FindPointsWithClosestDistance(Point[] points) { PointWithXComparison[] p = new PointWithXComparison[points.Length]; for (int i = 0; i < points.Length; i++) { p[i] = new PointWithXComparison(points[i].X, points[i].Y); } // sort the points. QuickSort<PointWithXComparison>.Sort(p); for (int i = 0; i < p.Length; i++) { points[i] = new Point(p[i].X, p[i].Y); } var result = FindClosestPointsHelper(points, 0, points.Length); return new Tuple<Point, Point>(result.a, result.b); } private static Pair FindClosestPointsHelper(Point[] points, int start, int end) { if (end - start <= 3) { return BruteForce(points, start, end); } else { int mid = start + (end - start) / 2; // recursively find closest points paritioned around mid var leftResults = FindClosestPointsHelper(points, start, mid); var rightResults = FindClosestPointsHelper(points, mid, end); Pair smallestPair = (leftResults.distance < rightResults.distance) ? leftResults : rightResults; // look for closest distance pair in range P[mid +/- smallestdistance] List<Point> remaining = new List<Point>(); foreach (var point in points) { if (Math.Abs(point.X - points[mid].X) < smallestPair.distance) { remaining.Add(point); } } var remainingResults = FindClosestPointsInRemain(remaining, smallestPair.distance); return (remainingResults.distance < smallestPair.distance) ? remainingResults : smallestPair; } } private static Pair FindClosestPointsInRemain(List<Point> remaining, double distance) { PointWithYComparison[] p = new PointWithYComparison[remaining.Count]; for (int i = 0; i < remaining.Count; i++) { p[i] = new PointWithYComparison(remaining[i].X, remaining[i].Y); } // sort the points. QuickSort<PointWithYComparison>.Sort(p); for (int i = 0; i < p.Length; i++) { remaining[i] = new Point(p[i].X, p[i].Y); } Pair smallestDistPair = new Pair(); smallestDistPair.distance = double.MaxValue; for (int i = 0; i < remaining.Count; i++) { for (int j = i + 1; j < remaining.Count && remaining[j].Y - remaining[i].Y < distance; j++) { double dist = Point.Distance(remaining[i], remaining[j]); if (dist < smallestDistPair.distance) { smallestDistPair.a = remaining[i]; smallestDistPair.b = remaining[j]; smallestDistPair.distance = dist; } } } return smallestDistPair; } private static Pair BruteForce(Point[] points, int start, int end) { Pair smallestDistPair = new Pair(); smallestDistPair.distance = double.MaxValue; for (int i = start; i < end; i++) { for (int j = i + 1; j < end; j++) { var dist = Point.Distance(points[i], points[j]); if (dist < smallestDistPair.distance) { smallestDistPair.a = points[i]; smallestDistPair.b = points[j]; smallestDistPair.distance = dist; } } } return smallestDistPair; } } }
using System; using System.Collections; using System.Collections.Generic; namespace Common.Composite { public interface IComponentCollection : IEnumerable<Component>, IEnumerable { //-------------------------------------------------------------------------- // // PUBLIC PROPERTIES // //-------------------------------------------------------------------------- int count { get; } Component[] components { get; } //-------------------------------------------------------------------------- // // PUBLIC METHODS // //-------------------------------------------------------------------------- Component Add(Component component); Component AddAt(Component component, int index); void AddRange(IEnumerable<Component> collection); bool Contains(Component component, bool includingChildren = false); Component GetAt(int index); Component GetByName(string name); Component GetByType(Type type); Component[] GetCollection(); int GetIndex(Component component); Component[] GetRange(int index, int count); bool Remove(Component component); void RemoveAll(); Component RemoveAt(int index); Component[] RemoveRange(int beginIndex = 0, int endIndex = -1); void Reverse(); void SetIndex(Component component, int index); void Sort(IComparer<Component> sortFunction); void Swap(Component component1, Component component2); void SwapIndex(int index1, int index2); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TurorialMenu : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey(KeyCode.Escape)) { Constants.dataContainer.SetCurrentState(States.MainMenu); } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Versioning; using Microsoft.Extensions.DependencyInjection; using System; namespace Library.API.Configurations { public static class VersioningConfig { public static void AddApiVersioningConfiguration(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); services.AddApiVersioning(options => { // 当客户端未提供版本时是否实用默认版本,默认值为false // true >> 客户端访问api时不需要显式的提供版本,方便那些原来并没有提供版本功能的api应用程序添加这一功能能,此时客户端仍可通过原来的方式访问api // false >> 在请求不包含版本时则会返回400 Bad Rqeuest状态码 options.AssumeDefaultVersionWhenUnspecified = true; // 指明了默认版本 options.DefaultApiVersion = new ApiVersion(1, 0); // 指明是否在http响应消息头中包含api-supported-versions和api-deprecated-versions // api-supported-versions: 当前api支持的所有版本列表 // api-deprecated-versions: 当前api将不再使用的版本列表 options.ReportApiVersions = true; // 获取指定版本内容 // 方法一:使用查询字符串https://localhost:5001/api/values/1?api-version=2.0, // 默认字符串为api-version,可通过ApiVersionReader属性修改为ver,https://localhost:5001/api/values/1?ver=2.0, // 方法二:通过路径形式来访问指定版本的api,[Route("api/v{version:apiVersion}/values")] // 方法三:在消息头中添加api-version项,它的值为要访问的版本,缺点:浏览器不支持自定义消息头;(默认不支持,需修改HeaderApiVersionReader属性) // 方法四:通过媒体类型获取,消息中包括Content-Type和Accept时,优先使用Content-Type,默认属性为v,例:Accept:*/*;v=2,修改为version后,Accept:*/*;version=2 // 以上四种方式推荐使用前两种方式,第四种用媒体类型的方式在RESTful API中比较适用 // 使用查询字符串 // options.ApiVersionReader = new QueryStringApiVersionReader("ver"); // 使用消息头 // options.ApiVersionReader = new HeaderApiVersionReader("api-version"); // 通过媒体类型获取 // options.ApiVersionReader = new MediaTypeApiVersionReader(); // 同时支持多种方式 // 当支持多种方式时,则所有方式指定的版本信息必须一致,否则服务端会提示版本信息不明确的错误消息 options.ApiVersionReader = ApiVersionReader.Combine( new QueryStringApiVersionReader("ver"), new HeaderApiVersionReader("api-version"), new MediaTypeApiVersionReader("version")); }); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Welic.App.Models.Token; namespace Welic.App.Services.ServicesViewModels { public interface IIdentityService { string CreateAuthorizationRequest(); string CreateLogoutRequest(string token); Task<UserToken> GetTokenAsync(string code); } }
using System.Data; using System.Linq; namespace test_automation_useful_features.Helpers.Examples.DB { public class ProjectRepo { private readonly string connectionString; private readonly string clientName; public ProjectRepo(string connectionString, string clientName) { this.connectionString = connectionString; this.clientName = clientName; } /// <summary> /// Method to delete projects /// </summary> /// <param name="projectId">Project id to delete</param> public void DeleteProjectById(string projectId) { LogUtil.log.Info($"{System.Reflection.MethodBase.GetCurrentMethod()} => Delete project from rfmc_invoices_{clientName} database. Project_id = \"{projectId}\"."); using (PostgreSqlDbClient dbcMcInvoices = new PostgreSqlDbClient(connectionString, $"rfmc_invoices_{clientName}")) { dbcMcInvoices.ExecuteModifyQuery(GetQueryToDeleteProjectFromMCInvoices(projectId)); } LogUtil.log.Info($"{System.Reflection.MethodBase.GetCurrentMethod()} => Delete project from rfmc_validations_{clientName} database. Project_id = \"{projectId}\"."); using (PostgreSqlDbClient dbcMcValidations = new PostgreSqlDbClient(connectionString, $"rfmc_validations_{clientName}")) { dbcMcValidations.ExecuteModifyQuery(GetQueryToDeleteProjectFromMCValidations(projectId)); } LogUtil.log.Info($"{System.Reflection.MethodBase.GetCurrentMethod()} => Delete project from common_methodologyoutputs_{clientName} database. Project_id = \"{projectId}\"."); using (PostgreSqlDbClient dbcMcOutputs = new PostgreSqlDbClient(connectionString, $"common_methodologyoutputs_{clientName}")) { DataTable outputsRegistryTableContent = dbcMcOutputs.ExecuteSelectQuery(GetQueryToReceiveOutputTableName(projectId)); string outputsTableName = outputsRegistryTableContent.Rows.Cast<DataRow>().FirstOrDefault()?["output_table_name"].ToString(); if (outputsTableName != null) { var t = dbcMcOutputs.ExecuteModifyQuery(GetQueryToDropOutputsTable(outputsTableName)); } } } #region Queries private string GetQueryToDeleteProjectFromMCInvoices(string projectId) { return $@" delete from rebate_summary where project_id = '{projectId}'; delete from invoice_scripts where invoice_id = '{projectId}'; delete from invoice_operation_log where invoice_id = '{projectId}'; delete from invoice_load where invoice_id = '{projectId}'; delete from submissions where invoice_id = '{projectId}'; delete from invoice where invoice_id = '{projectId}';"; } private string GetQueryToDeleteProjectFromMCValidations(string projectId) { return $@" delete from submissions where invoice_id = '{projectId}'; delete from invoice where invoice_id = '{projectId}';"; } private string GetQueryToReceiveOutputTableName(string projectId) { return $@" select output_table_name from outputs_registry where context_id = '{projectId}'"; } private string GetQueryToDropOutputsTable(string outputTableName) { return $@"drop table {outputTableName}"; } #endregion } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityEngine.UIElements; using UnityAtoms.Editor; using UnityEngine; namespace UnityAtoms.BaseAtoms.Editor { /// <summary> /// Event property drawer of type `Collider2D`. Inherits from `AtomEventEditor&lt;Collider2D, Collider2DEvent&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomEditor(typeof(Collider2DEvent))] public sealed class Collider2DEventEditor : AtomEventEditor<Collider2D, Collider2DEvent> { } } #endif
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; [RequireComponent(typeof(NavMeshObstacle))] public class SlidingDoor : MonoBehaviour { private Vector3 startingPoint; private Vector3 openPosition; [SerializeField] private Vector3 direction = Vector3.down; [SerializeField] private float distance; [SerializeField] private float speed = 2f; [SerializeField] private float waitTime = 3f; private float nextTimeDoorMoves; private bool isOpen = false; Coroutine running; NavMeshObstacle obstacle; [SerializeField] private bool _isLocked;//field public bool IsLocked//properties { set { _isLocked = value; if(value) // value == true { if (running != null) StopCoroutine(running); if(obstacle != null) obstacle.carving = true; } else { if(obstacle != null) obstacle.carving = false; } } get { return _isLocked; } } private void OnValidate() { if (_isLocked == false) // value == true { if (running != null) StopCoroutine(running); if (obstacle != null) obstacle.carving = true; } else { if (obstacle != null) obstacle.carving = false; } } private void Awake() { obstacle = GetComponent<NavMeshObstacle>(); } void Start() { startingPoint = transform.position; openPosition = transform.position + (direction.normalized * distance); nextTimeDoorMoves = waitTime; } void Update() { OpenCloseDoor(); } void OpenCloseDoor() { if (IsLocked) { return; } if (nextTimeDoorMoves <= Time.time) { nextTimeDoorMoves = Time.time + waitTime; if (isOpen) {//Closing if (running != null) StopCoroutine(running); running = StartCoroutine(MoveDoor(startingPoint)); isOpen = false; } else {//Opening isOpen = true; if (running != null) StopCoroutine(running); running = StartCoroutine(MoveDoor(openPosition)); } Debug.Log("MOVE DOOR"); } } IEnumerator MoveDoor(Vector3 position) { while(Vector3.Distance(transform.position, position) > Time.deltaTime * speed) { transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * speed); yield return null; //wait one frame } } }
using ENTIDAD; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DATOS { public class ProyectoDALC // usar "repositorio" { public List<Proyecto> ListarProyectos() { using(var db = new ProyectosDBEntities()) { return db.Proyecto.ToList(); } } public bool Agregar(Proyecto proyecto) // algunos usan bool para saber si se guardó bien... { using (var db = new ProyectosDBEntities()) { db.Proyecto.Add(proyecto); db.SaveChanges(); return true; } } } }
 using Android.OS; using Android.Preferences; using Android.Runtime; using System; namespace aairvid { public class SettingsFragment : PreferenceFragment { public override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); AddPreferencesFromResource(Resource.Layout.settings); } public SettingsFragment() { } protected SettingsFragment(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } } }
using UnityEngine; using System.Collections; //using UnityEditor; public class CreateMesh : MonoBehaviour { public Vector3[] vertices; public Vector2[] uv; public int[] triangles; public Material[] materials; // Use this for initialization void Start () { GameObject g = new GameObject("hex"); g.AddComponent("MeshFilter"); g.AddComponent("MeshRenderer"); g.AddComponent("MeshCollider"); Mesh mesh = new Mesh(); g.GetComponent<MeshFilter>().mesh = mesh; mesh.name = "hex"; mesh.Clear(); mesh.vertices = vertices; mesh.uv = uv; mesh.triangles = triangles; mesh.RecalculateNormals(); g.GetComponent<MeshCollider>().sharedMesh = mesh; g.GetComponent<MeshRenderer>().materials = this.materials; //string guid = AssetDatabase.CreateFolder("Assets", "My Folder"); //string newFolderPath = AssetDatabase.GUIDToAssetPath(guid); //AssetDatabase.AddObjectToAsset(mesh , newFolderPath); //string filePath = EditorUtility.SaveFilePanelInProject("Save Procedural Mesh", "Procedural Mesh", "asset", ""); //if (filePath == "") return; //AssetDatabase.CreateAsset(mesh, filePath); } // Update is called once per frame void Update () { } }
using System; using System.Collections.Generic; using System.Text; namespace D_OOP { public enum TrafficLight { Red, Yellow, Green } public enum Race { Elf = 30, Ork = 40, Terrain = 20 } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using GitHubRetriever.Commands; using GitHubRetriever.Models; using Microsoft.Azure.Cosmos; namespace GitHubRetriever { public class GitHubApiService { private readonly CommitsDownloadCommand commitsDownload; public GitHubApiService(CommitsDownloadCommand commitsDownload) { this.commitsDownload = commitsDownload; } public async Task Run(Container container, string userName, string repository) { var repositoryData = commitsDownload.Execute(userName, repository); await AddItemsToContainerAsync(repositoryData, container); } private static async Task AddItemsToContainerAsync(IEnumerable<RepositoryData> repositoryData, Container container) { foreach (var data in repositoryData) { Console.WriteLine($"[{data.Repository}]/[{data.Sha}]: {data.Message}[{data.Commiter}]"); try { await container.ReadItemAsync<RepositoryData>(data.Id, new PartitionKey(data.UserName)); } catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { await container.CreateItemAsync(data, new PartitionKey(data.UserName)); } } } } }
using Autofac; using Framework.Core.Common; using Tests.Data.Van; using Tests.Data.Van.Input.Filters; using Tests.Pages.Van.LogIn; using Tests.Pages.Van.Main.Common.DefaultPage; using Tests.Pages.Van.Main.List; using Tests.Pages.Van.Main.Turf; using NUnit.Framework; namespace Tests.Projects.Van.TurfManagementTests.MapRegionTests { public class CutOrEditTurfPolygonsNavigation : BaseTest { #region Test Pages private LoginPage LogInPage { get { return Scope.Resolve<LoginPage>(); } } private VoterDefaultPage HomePage { get { return Scope.Resolve<VoterDefaultPage>(); } } private TurfListPage TurfListPage { get { return Scope.Resolve<TurfListPage>(); } } private TurfCutterPage TurfCutterPage { get { return Scope.Resolve<TurfCutterPage>(); } } #endregion #region Test Case Data #region TestCase: Cut Or Edit Turf Polygons Navigation private static readonly VanTestUser User1 = new VanTestUser { UserName = "TurfTester3", Password = "@uT0Te$t3InG2" }; private static readonly TurfListPageFilter Filter1 = new TurfListPageFilter { Name = "Test_Region2" }; #endregion private static readonly object[] TestData = { new object[] { User1, Filter1 } }; #endregion /// <summary> /// Tests the functionality of the Cut Or Edit Turf Polygons link for a single Map Region on the TurfList Page. /// Opens the TurfCutter page for a single Map Region by clicking the Cut Or Edit Turf Polygons link. /// </summary> [Test, TestCaseSource("TestData")] [Category("van"), Category("van_smoketest"), Category("van_turfmanagement")] public void CutOrEditTurfPolygonsNavigationTest(VanTestUser user, TurfListPageFilter filter) { var driver = Scope.Resolve<Driver>(); LogInPage.Login(user); HomePage.ClickMyTurfsLink(); TurfListPage.ClickResultsGridIcon("Cut Or Edit Turf Polygons", filter); TurfCutterPage.WaitForSpinner(); Assert.That(driver.IsElementPresent(TurfCutterPage.MapLegend), Is.True, "Map Legend on TurfCutter page Map failed to load."); Assert.That(driver.IsElementPresent(TurfCutterPage.MapCanvas), Is.True, "TurfCutter page Map failed to load"); } } }
using System.Web.Mvc; using Tomelt.ContentManagement; using Tomelt.Layouts.Framework.Elements; namespace Tomelt.Layouts.Framework.Drivers { public class ElementEditorContext { public ElementEditorContext() { EditorResult = new EditorResult(); } public Element Element { get; set; } public dynamic ShapeFactory { get; set; } public IValueProvider ValueProvider { get; set; } public IUpdateModel Updater { get; set; } public IContent Content { get; set; } public string Prefix { get; set; } public EditorResult EditorResult { get; set; } public string Session { get; set; } public ElementDataDictionary ElementData { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace learn_180402_WorkStation { class WorkStationClass { } }
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 Oracle.ManagedDataAccess.Client; namespace EESSP { public partial class MainForm : Form { OracleConnection connection; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { setLabels(); connectToDatabase(); } private void connectToDatabase() { try { connection = new OracleConnection("DATA SOURCE=localhost:1521/XE;PASSWORD=STUDENT;PERSIST SECURITY INFO=True;USER ID=STUDENT"); connection.Open(); connection.Close(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } } private void setLabels() { this.ActiveControl = textBox1; label1.Font = new Font("Arial", 22, FontStyle.Bold); label2.Font = new Font("Arial", 16, FontStyle.Bold); label1.Text = "FIȘĂ DE CONSULTAȚII MEDICALE"; label2.Text = "- ADULTI -"; label8.Text = DateTime.Now.ToString("dd-MMM-yy"); label5.Text = "Unitatea \n sanitara"; label12.Text = "Data \nnasterii"; label13.Text = "Starea \ncivila"; label20.Text = " Locul \nconsultatiei"; label24.Text = " Zile con-\ncediu medical"; } private void button1_Click(object sender, EventArgs e) { OracleParameter p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21; OracleCommand cmd; String sexul = String.Empty; if (radioButton1.Checked) sexul = "Masculin"; if(radioButton2.Checked) sexul = "Feminin"; try { connection.Open(); p1 = new OracleParameter();p2 = new OracleParameter();p3 = new OracleParameter();p4 = new OracleParameter(); p5 = new OracleParameter();p6 = new OracleParameter();p7 = new OracleParameter();p8 = new OracleParameter(); p9 = new OracleParameter();p10 = new OracleParameter();p11 = new OracleParameter();p12 = new OracleParameter(); p13 = new OracleParameter();p14 = new OracleParameter();p15 = new OracleParameter();p16 = new OracleParameter(); p17 = new OracleParameter();p18 = new OracleParameter();p19 = new OracleParameter();p20 = new OracleParameter(); p21 = new OracleParameter(); p1.Value = textBox1.Text;p2.Value = textBox2.Text;p3.Value = textBox3.Text; p4.Value = textBox4.Text;p5.Value = label8.Text;p6.Value = textBox6.Text; p7.Value = textBox7.Text;p8.Value = textBox5.Text;p9.Value = sexul; p10.Value = comboBox1.Text; p11.Value = dateTimePicker1.Value.ToString("dd-MMM-yy").ToString(); p12.Value = textBox8.Text; p13.Value = textBox9.Text; p14.Value = textBox10.Text; p15.Value = textBox11.Text; p16.Value = textBox12.Text; p17.Value = textBox13.Text; p18.Value = textBox14.Text; p19.Value = textBox15.Text; p20.Value = textBox16.Text; p21.Value = textBox17.Text; String sqlInsertCommand="Insert into FiseMedicale(judetul,localitatea,unitatea_sanitara,nr_fisei,data_completarii," + "numele,prenumele,CNP,sexul,starea_civila,data_nasterii,domiciliu_judet," + "domiciliu_localitate,domiciliu_strada,domiciliu_numar,ocupatia,locul_consultatiei,simptome," + "diagnostic,prescriptii,nr_zile_medical) " + "values (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16,:17,:18,:19,:20,:21)"; cmd = new OracleCommand(sqlInsertCommand, connection); cmd.Parameters.Add(p1);cmd.Parameters.Add(p2);cmd.Parameters.Add(p3); cmd.Parameters.Add(p4);cmd.Parameters.Add(p5);cmd.Parameters.Add(p6); cmd.Parameters.Add(p7);cmd.Parameters.Add(p8);cmd.Parameters.Add(p9); cmd.Parameters.Add(p10);cmd.Parameters.Add(p11);cmd.Parameters.Add(p12); cmd.Parameters.Add(p13);cmd.Parameters.Add(p14);cmd.Parameters.Add(p15); cmd.Parameters.Add(p16);cmd.Parameters.Add(p17);cmd.Parameters.Add(p18); cmd.Parameters.Add(p19);cmd.Parameters.Add(p20);cmd.Parameters.Add(p21); cmd.ExecuteNonQuery(); connection.Close(); textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox4.Clear(); textBox5.Clear(); textBox6.Clear(); textBox7.Clear(); textBox8.Clear(); textBox9.Clear(); textBox10.Clear(); textBox11.Clear(); textBox12.Clear(); textBox13.Clear(); textBox14.Clear(); textBox15.Clear(); textBox16.Clear(); textBox17.Clear(); dateTimePicker1.ResetText();radioButton1.ResetText();radioButton2.ResetText(); comboBox1.ResetText(); FormAfisare formAfisare = new FormAfisare(connection); formAfisare.Show(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } } private void button2_Click(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using System.Data.Common; using System.Data; namespace UFO.Server.Data { public class User { public User() { } public User(uint id, string firstName, string lastName, string email, string password) { Id = id; FirstName = firstName; LastName = lastName; EmailAddress = email; Password = password; } public uint Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string Password { get; set; } public override string ToString() { return String.Format("User(id={0}, firstname='{1}', lastname='{2}', email='{3}', password='{4}') ", Id, FirstName, LastName, EmailAddress, Password); } public override bool Equals(object obj) { User u = obj as User; if(u == null) { return false; } return Id.Equals(u.Id) && FirstName.Equals(u.FirstName) && LastName.Equals(u.LastName) && EmailAddress.Equals(u.EmailAddress) && Password.Equals(u.Password); } public override int GetHashCode() { return (int)Id; } } public interface IUserDao { void DeleteAllUsers(); List<User> GetAllUsers(); User GetUserById(uint id); User GetUserByEmailAddress(string email); bool UpdateUser(User user); bool DeleteUser(User user); User CreateUser(string firstName, string lastName, string email, string password); } public class UserDao : IUserDao { private const string CREATE_CMD = "INSERT INTO User(firstname, lastname, email, password) VALUES (@first, @last, @email,@password)"; private const string DELETE_CMD = "DELETE FROM User WHERE userId = @id"; private const string GETALL_CMD = "SELECT * FROM User"; private const string GETBYID_CMD = "SELECT * FROM User WHERE userId = @id"; private const string GETBYEMAIL_CMD = "SELECT * FROM User WHERE email = @email"; private const string UPDATE_CMD = "UPDATE User SET firstname=@first, lastname=@last, email=@email, password=@password WHERE userId=@id"; private IDatabase db; private User readOne(IDataReader reader) { uint id = (uint)reader["userID"]; string firstName = (string)reader["firstname"]; string lastName = (string)reader["lastname"]; string email = (string)reader["email"]; string password = (string)reader["password"]; return new User(id, firstName, lastName, email, password); } public UserDao(IDatabase db) { this.db = db; } public User CreateUser(string firstName, string lastName, string email, string password) { DbCommand cmd = db.CreateCommand(CREATE_CMD); db.DefineParameter(cmd, "@first", System.Data.DbType.String, firstName); db.DefineParameter(cmd, "@last", System.Data.DbType.String, lastName); db.DefineParameter(cmd, "@email", System.Data.DbType.String, email); db.DefineParameter(cmd, "@password", System.Data.DbType.String, password); int id = db.ExecuteNonQuery(cmd); return new User((uint)id, firstName, lastName, email,password); } public bool DeleteUser(User user) { DbCommand cmd = db.CreateCommand(DELETE_CMD); db.DefineParameter(cmd, "@id", System.Data.DbType.UInt32, user.Id); return cmd.ExecuteNonQuery() >= 1; } public List<User> GetAllUsers() { List<User> users = new List<User>(); DbCommand cmd = db.CreateCommand(GETALL_CMD); db.doSynchronized(() => { using (IDataReader reader = db.ExecuteReader(cmd)) { while (reader.Read()) { users.Add(readOne(reader)); } } }); return users; } public User GetUserByEmailAddress(string email) { DbCommand cmd = db.CreateCommand(GETBYEMAIL_CMD); db.DefineParameter(cmd, "@email", System.Data.DbType.String, email); User user = null; db.doSynchronized(() => { using (IDataReader reader = db.ExecuteReader(cmd)) { if (reader.Read()) { user = readOne(reader); } } }); return user; } public User GetUserById(uint id) { DbCommand cmd = db.CreateCommand(GETBYID_CMD); db.DefineParameter(cmd, "@id", System.Data.DbType.UInt32, id); User user = null; db.doSynchronized(() => { using (IDataReader reader = db.ExecuteReader(cmd)) { if (reader.Read()) { user = readOne(reader); } } }); return user; } public bool UpdateUser(User user) { DbCommand cmd = db.CreateCommand(UPDATE_CMD); db.DefineParameter(cmd, "@id", System.Data.DbType.UInt32, user.Id); db.DefineParameter(cmd, "@first", System.Data.DbType.String, user.FirstName); db.DefineParameter(cmd, "@last", System.Data.DbType.String, user.LastName); db.DefineParameter(cmd, "@email", System.Data.DbType.String, user.EmailAddress); db.DefineParameter(cmd, "@password", System.Data.DbType.String, user.Password); return db.ExecuteNonQuery(cmd) >= 1; } public void DeleteAllUsers() { db.TruncateTable("User"); } } }
using System; using System.Collections.Generic; using Kattis.IO; public class Program { static string[] items; static Dictionary<string, int> itemIDs; static List<int>[] adj; static int[] side; static bool is_bipartite = true; static void check_bipartite(int u) { for (int i = 0; i < adj[u].Count; i++) { int v = adj[u][i]; if (side[v] == -1) { side[v] = 1 - side[u]; check_bipartite(v); } else if (side[u] == side[v]) { is_bipartite = false; } } } static public void Main () { Scanner scanner = new Scanner(); BufferedStdoutWriter writer = new BufferedStdoutWriter(); int nItems = scanner.NextInt(); items = new string[nItems]; itemIDs = new Dictionary<string, int>(); adj = new List<int>[nItems]; for(int i = 0; i < nItems; i++){ adj[i] = new List<int>(); } side = new int[nItems]; for(int i = 0; i < nItems; i++){ side[i] = -1; } for(int i = 0; i < nItems; i++){ items[i] = scanner.Next(); itemIDs.Add(items[i], i); } int nPairs = scanner.NextInt(); for(int i = 0; i < nPairs; i++){ string item1 = scanner.Next(); string item2 = scanner.Next(); adj[itemIDs[item1]].Add(itemIDs[item2]); adj[itemIDs[item2]].Add(itemIDs[item1]); } for (int u = 0; u < nItems; u++) { if (side[u] == -1) { side[u] = 0; check_bipartite(u); } } if(is_bipartite){ for(int i = 0; i < 2; i++){ for(int j = 0; j < nItems; j++){ if(side[j] == i){ writer.Write(items[j]); writer.Write(" "); } } writer.Write("\n"); } } else { writer.WriteLine("impossible"); } writer.Flush(); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class MapGenerator : MonoBehaviour { public Transform tilePrefab; // The prefab to construct the floor from public Transform obstaclePrefab; public Transform navmeshFloor; public Transform navmeshMaskPrefab; public Vector2 mapSize; // The size of the map along each axis public Vector2 maximumMapSize; [Range(0, 1)] public float outlinePercent; [Range(0, 1)] public float obstaclePercent; public float tileSize; List<Coord> allTileCoords; Queue<Coord> shuffledTileCoords; public int seed = 10; Coord mapCentre; void Start() { GenerateMap(); } public void GenerateMap() { allTileCoords = new List<Coord>(); for (int x = 0; x < mapSize.x; x++) { // For each column for (int y = 0; y < mapSize.y; y++) { // For each row within that column allTileCoords.Add(new Coord(x, y)); } } shuffledTileCoords = new Queue<Coord>(Utility.ShuffleArray(allTileCoords.ToArray(), seed)); mapCentre = new Coord((int)mapSize.x / 2, (int)mapSize.y / 2); string holderName = "Generated Map"; if (transform.FindChild(holderName)) { DestroyImmediate(transform.FindChild(holderName).gameObject); } Transform mapHolder = new GameObject(holderName).transform; mapHolder.parent = transform; for (int x = 0; x < mapSize.x; x++) { // For each column for (int y = 0; y < mapSize.y; y++) { // For each row within that column Vector3 tilePosition = CoordToPosition(x, y); Transform newTile = Instantiate(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 90)) as Transform; // Spawn a tile at that location newTile.localScale = Vector3.one * (1 - outlinePercent) * tileSize; newTile.parent = mapHolder; } } bool[,] obstacleMap = new bool[(int)mapSize.x, (int)mapSize.y]; int obstacleCount = (int)((mapSize.x * mapSize.y) * obstaclePercent); int currentObstacleCount = 0; for (int i = 0; i < obstacleCount; i++) { Coord randomCoord = GetRandomCoord(); obstacleMap[randomCoord.x, randomCoord.y] = true; currentObstacleCount++; if (randomCoord != mapCentre && MapIsFullyAccessible(obstacleMap, currentObstacleCount)) { Vector3 obstaclePosition = CoordToPosition(randomCoord.x, randomCoord.y); Transform newObstacle = Instantiate(obstaclePrefab, obstaclePosition + Vector3.up / 2, Quaternion.identity) as Transform; newObstacle.localScale = Vector3.one * (1 - outlinePercent) * tileSize; newObstacle.parent = mapHolder; } else { // Move these into above "if" statement? obstacleMap[randomCoord.x, randomCoord.y] = false; currentObstacleCount--; } } // THESE ARE ALL BROKEN. FIX IMMEDIATELY. Transform maskLeft = Instantiate(navmeshMaskPrefab, Vector3.left * (mapSize.x + maximumMapSize.x) * 0.75f * tileSize, Quaternion.identity) as Transform; maskLeft.parent = mapHolder; maskLeft.localScale = new Vector3((maximumMapSize.x - mapSize.x) / 2, 1, mapSize.y) * tileSize; Transform maskRight = Instantiate(navmeshMaskPrefab, Vector3.right * (mapSize.x + maximumMapSize.x) * 0.75f * tileSize, Quaternion.identity) as Transform; maskRight.parent = mapHolder; maskRight.localScale = new Vector3((maximumMapSize.x - mapSize.x) / 2, 1, mapSize.y) * tileSize; Transform maskTop = Instantiate(navmeshMaskPrefab, Vector3.forward * (mapSize.y + maximumMapSize.y) * 0.75f * tileSize, Quaternion.identity) as Transform; maskTop.parent = mapHolder; maskTop.localScale = new Vector3(maximumMapSize.x, 1, (maximumMapSize.y - mapSize.y) / 2) * tileSize; Transform maskBottom = Instantiate(navmeshMaskPrefab, Vector3.back * (mapSize.y + maximumMapSize.y) * 0.75f * tileSize, Quaternion.identity) as Transform; maskBottom.parent = mapHolder; maskBottom.localScale = new Vector3((maximumMapSize.y - mapSize.y) / 2, 1, maximumMapSize.x) * tileSize; navmeshFloor.localScale = new Vector3(maximumMapSize.x, maximumMapSize.y) * tileSize; } bool MapIsFullyAccessible(bool[,] obstacleMap, int currentObstacleCount) { // Flood-fill algorithm bool[,] mapFlags = new bool[obstacleMap.GetLength(0),obstacleMap.GetLength(1)]; Queue<Coord> queue = new Queue<Coord>(); queue.Enqueue(mapCentre); mapFlags[mapCentre.x, mapCentre.y] = true; int accessibleTileCount = 1; while (queue.Count > 0) { Coord tile = queue.Dequeue(); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { int neighborX = tile.x + x; int neighborY = tile.y + y; if (x == 0 || y == 0) { // Don't check diagonals if (neighborX >= 0 && neighborX < obstacleMap.GetLength(0) && neighborY >= 0 && neighborY < obstacleMap.GetLength(1)) { if (!mapFlags[neighborX, neighborY] && !obstacleMap[neighborX, neighborY]) { mapFlags[neighborX, neighborY] = true; queue.Enqueue(new Coord(neighborX, neighborY)); accessibleTileCount++; } } } } } } int targetAccessibleTileCount = (int)(mapSize.x * mapSize.y - currentObstacleCount); return targetAccessibleTileCount == accessibleTileCount; } Vector3 CoordToPosition(int x, int y) { return new Vector3(-mapSize.x / 2 + 0.5f + x, 0, -mapSize.y / 2 + 0.5f + y) * tileSize; } public Coord GetRandomCoord() { Coord randomCoord = shuffledTileCoords.Dequeue(); shuffledTileCoords.Enqueue(randomCoord); return randomCoord; } public struct Coord { public int x; public int y; public Coord(int _x, int _y) { x = _x; y = _y; } public static bool operator ==(Coord c1, Coord c2) { return c1.x == c2.x && c1.y == c2.y; } public static bool operator !=(Coord c1, Coord c2) { return !(c1 == c2); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; public partial class _Default : System.Web.UI.Page { SqlConnection con; SqlDataAdapter da; DataSet ds = new DataSet(); SqlCommand cmd; int EID = 0; protected void Page_Load(object sender, EventArgs e) { con = new SqlConnection("Server=.;Integrated Security=SSPI;Database=ASPNET7"); da = new SqlDataAdapter("SELECT *FROM EMP", con); da.Fill(ds, "EMP"); if (!IsPostBack) { if (EID < ds.Tables[0].Rows.Count) { TextBox1.Text = ds.Tables[0].Rows[EID][0].ToString(); TextBox2.Text = ds.Tables[0].Rows[EID][1].ToString(); TextBox3.Text = ds.Tables[0].Rows[EID][2].ToString(); } else { Label4.Text = "data is completed"; } } } protected void Button1_Click(object sender, EventArgs e) { EID++; } protected void Button2_Click(object sender, EventArgs e) { TextBox1.Text = " "; TextBox2.Text = " "; TextBox3.Text = " "; } protected void Button3_Click(object sender, EventArgs e) { con = new SqlConnection("Server=.;Integrated Security=SSPI;Database=ASPNET7"); da = new SqlDataAdapter("SELECT *FROM EMP", con); da.Fill(ds, "EMP"); int previous = ds.Tables[0].Rows.Count; DataRow dr = ds.Tables[0].NewRow(); dr[0] = TextBox1.Text; dr[1] = TextBox2.Text; dr[2] = TextBox3.Text; ds.Tables[0].Rows.Add(dr); SqlCommandBuilder cb = new SqlCommandBuilder(da); da.Update(ds, "EMP"); TextBox1.Text = " "; TextBox2.Text = " "; TextBox3.Text = " "; int present = ds.Tables[0].Rows.Count; if(present>previous) { Label4.Text = "record is inserted"; } else { Label4.Text = "record is not inserted"; } } protected void Button5_Click(object sender, EventArgs e) { int previous = Convert.ToInt32(ds.Tables[0].Rows[EID][2]); ds.Tables[0].Rows[EID][2] = TextBox1.Text; SqlCommandBuilder cb = new SqlCommandBuilder(da); da.Update(ds,"EMP"); TextBox1.Text = " "; int present = Convert.ToInt32(ds.Tables[0].Rows[EID][2]); if (present != previous) { Label4.Text = "price updated"; } else { Label4.Text = "price not updated"; } } }
using Microsoft.EntityFrameworkCore; using System; using User.Domain; using User.Domain.Model; namespace User1.Data.Context { public class UserContext : DbContext { public UserContext() { } public UserContext(DbContextOptions options) : base(options) { } public DbSet<TestUser> Users { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio2 { class SeleccaoNomes { static void Main(string[] args) { { string[] Nomes = { "Ana", "António", "Beatriz", "Joana", "Raul", "Vitoria" }; int X = 4; EscreverLista(Nomes, X); Console.WriteLine("Seleccionámos {0} de {1} nomes", X, Nomes.Length); } } static void EscreverLista(string[] Nomes, int Conta) { for (int I = 0; I < Conta; I++) { Console.WriteLine(Nomes[I]); } } } }
using KissLog; using KissLog.AspNetCore; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using RSS.Business.Interfaces; using RSS.Business.Notifications; using RSS.Business.Services; using RSS.Data.Context; using RSS.Data.Repository; using RSS.WebApi.Extensions; using RSS.WebApi.Services; using RSS.WebApi.Services.Interfaces; using Swashbuckle.AspNetCore.SwaggerGen; namespace RSS.WebApi.Configurations { public static class DependecyInjectionConfig { public static IServiceCollection ResolveDependencies(this IServiceCollection services) { services.AddScoped<CompleteAppDbContext>(); services.AddScoped<ISupplierRepository, SupplierRepository>(); services.AddScoped<IAddressRepository, AddressRepository>(); services.AddScoped<IProductRepository, ProductRepository>(); services.AddScoped<ISupplierService, SupplierService>(); services.AddScoped<IProductService, ProductService>(); services.AddScoped<IIdentityService, IdentityService>(); services.AddScoped<INotifiable, Notifiable>(); services.AddScoped<IUser, AspNetUser>(); //injeção de dependencia que viabiliza o acesso ao contexto da requisição em qualquer classe que receba a injeção de dependencia services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>(); return services; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ELearningPlatform.Models { public class Role { public const int RoleGuest = 1; public const int RoleStudent = 2; public const int RoleInstructor = 3; public int Id { get; set; } public string Label { get; set; } } }
namespace HandmadeHTTPServer.Data.Contracts { using System.Data.Entity; using SimpleHttpServer.Models; public interface ISharpStoreContext { DbSet<Knife> Knives { get; set; } DbSet<Message> Messages { get; set; } int SaveChanges(); } }
using System; using Uintra.Core.User.Models; using Uintra.Features.Permissions.Models; namespace Uintra.Core.Member.Abstractions { public interface IIntranetMember { Guid Id { get; set; } string DisplayedName { get; } string FirstName { get; set; } string LastName { get; set; } string LoginName { get; set; } string Email { get; set; } string Phone { get; set; } string Department { get; set; } string Photo { get; set; } int? PhotoId { get; set; } IntranetMemberGroup[] Groups { get; set; } IIntranetUser RelatedUser { get; set; } int UmbracoId { get; set; } bool Inactive { get; set; } bool IsSuperUser { get; set; } } }
using CalculatorService.Domain.Models; using OperationModel = CalculatorService.Domain.Models.Operation; using System.Threading.Tasks; using CalculatorService.CrossCutting; namespace CalculatorService.Domain { public class ServiceTracked<P, R> : IOperationService<P, R> where P : ParamsOperationBase where R : ResultOperationBase { private readonly ITimeProvider timeProvider; private readonly IOperationService<P, R> innerOperation; private readonly IRepository<OperationModel> repository; private readonly int trackId; public ServiceTracked(IOperationService<P, R> innerOperation, int trackId, ITimeProvider timeProvider, IRepository<OperationModel> repository) { this.timeProvider = timeProvider; this.innerOperation = innerOperation; this.trackId = trackId; this.repository = repository; } public Task<R> Execute(P parameters) { var task = innerOperation .Execute(parameters) .ContinueWith(async (a) => { var result = a.Result; var operation = new OperationModel() { TrackId = trackId, OperationType = innerOperation.GetServiceName(), Calculation = innerOperation.GetDescription(parameters, result), DateTime = this.timeProvider.GetNow(), }; await repository.Add(operation); await repository.Save(); return result; }, TaskContinuationOptions.OnlyOnRanToCompletion) .Unwrap(); return task; } public string GetDescription(P parameters, R result) => string.Empty; } }
using UnityEngine; using System.Collections; using System.IO; static public class DirectoryUtility { static public string ExternalAssets() { // switch ( Application.platform ) // { // default: return Application.streamingAssetsPath; // case RuntimePlatform.OSXEditor: // case RuntimePlatform.WindowsEditor: // return Application.dataPath + "/../ExternalAssets/"; // case RuntimePlatform.OSXPlayer: // case RuntimePlatform.WindowsPlayer: // case RuntimePlatform.IPhonePlayer: // case RuntimePlatform.LinuxPlayer: // return Application.dataPath + "/ExternalAssets/"; // } } }
using System; public class GClass4 { public static byte[] smethod_0(int int_0) { byte[] bytes = BitConverter.GetBytes(int_0); if (!BitConverter.IsLittleEndian) { Array.Reverse(bytes); } return bytes; } public static int smethod_1(byte[] byte_0) { if (!BitConverter.IsLittleEndian) { Array.Reverse(byte_0); } return BitConverter.ToInt32(byte_0, 0); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Views.ThumbNails { /// <summary> /// UcThumbNailList.xaml에 대한 상호 작용 논리 /// </summary> public partial class UcThumbNailList : UserControl { public UcThumbNailList() { InitializeComponent(); } public delegate void ThumbNailClick(object sender, EventArgs e); public event ThumbNailClick ThumbNailClik; private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var listbox = sender as ListBox; if (listbox == null || listbox.SelectedItem == null) { return; } this.ThumbNailClik?.Invoke(listbox.SelectedItem, new EventArgs()); } public void InsertThumbNail(Models.ViewModels.ThumbNails.ThumbNailViewModel thumbnail) { UcThumbNail ucThumbNail = new UcThumbNail(); ucThumbNail.DataContext = thumbnail; this.ListBox.Items.Add(thumbnail); } } }
namespace com.Sconit.Web.Controllers.PRD { using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using com.Sconit.Entity.PRD; using com.Sconit.Service; using com.Sconit.Web.Models; using com.Sconit.Web.Models.SearchModels.PRD; using com.Sconit.Utility; using Telerik.Web.Mvc; using com.Sconit.Entity.SCM; using System; using System.Text; using com.Sconit.Entity.Exception; using com.Sconit.Entity.INV; using com.Sconit.Entity.MD; using com.Sconit.Entity.ORD; using com.Sconit.Web.Models.SearchModels.ORD; using System.Data.SqlClient; using System.Data; public class ProdIOController : WebAppBaseController { #region Properties //public IGenericMgr genericMgr { get; set; } #endregion private static string selectDetailCountStatement = "select count(*) from OrderDetail as d"; private static string selectDetailStatement = "select d from OrderDetail as d"; private static string selectOrderBackflushDetailStatement = "select b from OrderBackflushDetail as b"; [SconitAuthorize(Permissions = "Url_Production_ProdIO")] public ActionResult Index() { return View(); } [SconitAuthorize(Permissions = "Url_Production_ProdIO")] public ActionResult List(GridCommand command, OrderMasterSearchModel searchModel) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel); if (this.CheckSearchModelIsNull(searchCacheModel.SearchObject)) { TempData["_AjaxMessage"] = ""; } else { SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions); } ViewBag.DisplayType = searchModel.DisplayType; return View(); } #region detail [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_Production_ProdIO")] public ActionResult _OrderDetailHierarchyAjax(GridCommand command, OrderMasterSearchModel searchModel) { if (!this.CheckSearchModelIsNull(searchModel)) { return PartialView(new GridModel(new List<OrderDetail>())); } SearchStatementModel searchStatementModel = this.PrepareSearchStatement(command, searchModel, false); return PartialView(GetAjaxPageData<OrderDetail>(searchStatementModel, command)); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_Production_ProdIO")] public ActionResult _OrderBackflushDetailHierarchyAjax(int orderDetailId) { string hql = "select f from OrderBackflushDetail as f where f.OrderDetailId = ?"; IList<OrderBackflushDetail> orderBackflushDetailList = genericMgr.FindAll<OrderBackflushDetail>(hql, orderDetailId); return PartialView(new GridModel(orderBackflushDetailList)); } #endregion #region summary [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_Production_ProdIO")] public ActionResult _OrderSummaryHierarchyAjax(GridCommand command, OrderMasterSearchModel searchModel) { SearchStatementModel searchStatementModel = this.PrepareSearchStatement(command, searchModel, true); IList<OrderDetail> orderDetailList = queryMgr.FindAll<OrderDetail>(searchStatementModel.GetSearchStatement(), searchStatementModel.Parameters); var summaryOrderDetailList = from d in orderDetailList group d by new { d.Item, d.ItemDescription, d.ReferenceItemCode, d.Uom } into result select new OrderDetail { Item = result.Key.Item, ItemDescription = result.Key.ItemDescription, ReferenceItemCode = result.Key.ReferenceItemCode, Uom = result.Key.Uom, ReceivedQty = result.Sum(r => r.ReceivedQty) }; return PartialView(new GridModel(summaryOrderDetailList)); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_Production_ProdIO")] public ActionResult _OrderBackflushSummaryHierarchyAjax(GridCommand command, OrderMasterSearchModel searchModel, string item) { searchModel.Item = item; SearchStatementModel searchStatementModel = this.PrepareSearchSummaryStatement(command, searchModel); IList<OrderBackflushDetail> orderBackflushDetailList = queryMgr.FindAll<OrderBackflushDetail>(searchStatementModel.GetSearchStatement(), searchStatementModel.Parameters); var summaryOrderBackflushDetailList = from d in orderBackflushDetailList group d by new { d.Item, d.ItemDescription, d.ReferenceItemCode, d.Uom } into result select new OrderBackflushDetail { Item = result.Key.Item, ItemDescription = result.Key.ItemDescription, ReferenceItemCode = result.Key.ReferenceItemCode, Uom = result.Key.Uom, BackflushedQty = result.Sum(r => r.BackflushedQty) }; return PartialView(new GridModel(summaryOrderBackflushDetailList)); } #endregion private SearchStatementModel PrepareSearchStatement(GridCommand command, OrderMasterSearchModel searchModel, bool isSummary) { string whereStatement = "where d.OrderType = ? and d.ReceivedQty > 0 and exists(select 1 from OrderMaster as m where d.OrderNo = m.OrderNo "; IList<object> param = new List<object>(); param.Add((int)com.Sconit.CodeMaster.OrderType.Production); HqlStatementHelper.AddEqStatement("Flow", searchModel.Flow, "m", ref whereStatement, param); HqlStatementHelper.AddEqStatement("PartyTo", searchModel.PartyTo, "m", ref whereStatement, param); if (searchModel.DateFrom != null) { HqlStatementHelper.AddGeStatement("StartDate", searchModel.DateFrom, "m", ref whereStatement, param); } if (searchModel.DateTo != null) { HqlStatementHelper.AddLeStatement("StartDate", searchModel.DateTo, "m", ref whereStatement, param); } SecurityHelper.AddRegionPermissionStatement(ref whereStatement, "m", "PartyTo"); whereStatement += ")"; HqlStatementHelper.AddEqStatement("Item", searchModel.Item, "d", ref whereStatement, param); string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); if (!isSummary) { if (command.SortDescriptors.Count == 0) { sortingStatement = " order by d.OrderNo desc"; } } SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = selectDetailCountStatement; searchStatementModel.SelectStatement = selectDetailStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = sortingStatement; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } private SearchStatementModel PrepareSearchSummaryStatement(GridCommand command, OrderMasterSearchModel searchModel) { string whereStatement = "where b.Item = ? and exists(select 1 from OrderMaster as m,OrderDetail as d where d.OrderNo = m.OrderNo and d.OrderType = m.Type and m.Type = ? and d.Item = ? and b.OrderDetailId = d.Id"; IList<object> param = new List<object>(); param.Add(searchModel.Item); param.Add((int)com.Sconit.CodeMaster.OrderType.Production); param.Add(searchModel.Item); HqlStatementHelper.AddEqStatement("Flow", searchModel.Flow, "m", ref whereStatement, param); HqlStatementHelper.AddEqStatement("PartyTo", searchModel.PartyTo, "m", ref whereStatement, param); if (searchModel.DateFrom != null) { HqlStatementHelper.AddGeStatement("StartDate", searchModel.DateFrom, "m", ref whereStatement, param); } if (searchModel.DateTo != null) { HqlStatementHelper.AddLeStatement("StartDate", searchModel.DateTo, "m", ref whereStatement, param); } SecurityHelper.AddRegionPermissionStatement(ref whereStatement, "m", "PartyTo"); whereStatement += ")"; SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = string.Empty; searchStatementModel.SelectStatement = selectOrderBackflushDetailStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = string.Empty; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } [SconitAuthorize(Permissions = "Url_Production_ProdIOFI")] public ActionResult ProdIOFI() { return View(); } [SconitAuthorize(Permissions = "Url_Production_ProdIOMI")] public ActionResult ProdIOMI() { return View(); } [SconitAuthorize(Permissions = "Url_Production_ProdIOEX")] public ActionResult ProdIOEX() { return View(); } [SconitAuthorize(Permissions = "Url_Production_ForceMaterial")] public ActionResult ForceMaterial() { return View(); } [SconitAuthorize(Permissions = "Url_Production_ProdIOMI,Url_Production_ProdIOFI,Url_Production_ProdIOEX")] public string _GetProductionInOut(string ResourceGroup, string Flow, DateTime DateFrom, DateTime DateTo,string SPName,string SearchType) { SqlParameter[] sqlParams = new SqlParameter[5]; sqlParams[0] = new SqlParameter(SPName.Substring(23,2)=="EX"?"@OrderNo":"@ResourceGroup", ResourceGroup); sqlParams[1] = new SqlParameter("@Flow", Flow); sqlParams[2] = new SqlParameter("@DateFrom", DateFrom); sqlParams[3] = new SqlParameter("@DateTo", DateTo); if (!string.IsNullOrWhiteSpace(SearchType)) { sqlParams[4] = new SqlParameter("@SearchType", SearchType); } DataSet ds = genericMgr.GetDatasetByStoredProcedure(SPName, sqlParams); //var q= from p in ds group p by p. StringBuilder str = new StringBuilder("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"datatable\" width=\"100%\"><thead><tr>"); //库位 物料 描述 单位 #region Head str.Append("<th>"); str.Append(Resources.EXT.ControllerLan.Con_RowCount); str.Append("</th>"); str.Append("<th>"); str.Append((SearchType == "1" ? Resources.EXT.ControllerLan.Con_FinishGood : Resources.EXT.ControllerLan.Con_SourceMaterial)); str.Append("</th>"); str.Append("<th>"); str.Append((SearchType == "1" ? Resources.EXT.ControllerLan.Con_FinishGoodDescription : Resources.EXT.ControllerLan.Con_SourceMaterialDescription)); str.Append("</th>"); str.Append("<th>"); str.Append((SearchType == "1" ? Resources.EXT.ControllerLan.Con_FinishGoodUom : Resources.EXT.ControllerLan.Con_SourceMaterialUom)); str.Append("</th>"); if (SearchType == "1" || SearchType == null) { str.Append("<th>"); str.Append(Resources.EXT.ControllerLan.Con_OutputQuantity); str.Append("</th>"); } //成品描述 成品单位 产出数量 原材料 描述 零件单位 理论用量 实际用量 偏差 str.Append("<th>"); str.Append((SearchType == "1" ? Resources.EXT.ControllerLan.Con_SourceMaterial : Resources.EXT.ControllerLan.Con_FinishGood)); str.Append("</th>"); str.Append("<th>"); str.Append((SearchType == "1" ? Resources.EXT.ControllerLan.Con_SourceMaterialDescription : Resources.EXT.ControllerLan.Con_FinishGoodDescription)); str.Append("</th>"); str.Append("<th>"); str.Append((SearchType == "1" ? Resources.EXT.ControllerLan.Con_SourceMaterialUom : Resources.EXT.ControllerLan.Con_FinishGoodUom)); str.Append("</th>"); if (SearchType == "2") { str.Append("<th>"); str.Append(Resources.EXT.ControllerLan.Con_OutputQuantity); str.Append("</th>"); } str.Append("<th>"); str.Append(Resources.EXT.ControllerLan.Con_TheoreticalAmount); str.Append("</th>"); str.Append("<th>"); str.Append(Resources.EXT.ControllerLan.Con_ActualAmount); str.Append("</th>"); str.Append("<th>"); str.Append(Resources.EXT.ControllerLan.Con_Deviation); str.Append("</th>"); str.Append("</tr></thead><tbody>"); #endregion int l = 0; int m = 0;//变合并单元格的颜色 string style = string.Empty; //SP 结果集多返回两列,倒数第一列是以成品为单位给零件号排序,倒数第二列是每个成品的两件个数,即需要合并的行数。 foreach (DataRow dr in ds.Tables[0].Rows) { l++; str.Append("<tr>"); if ((int)dr.ItemArray[11] == 1) { m++; if (m % 2 != 0)//奇数单元格为灰色 { style = "<td bgcolor=#E0E0E0 rowspan=" + (int)dr.ItemArray[10] + ">"; } else//偶数不变色 { style = "<td rowspan=" + (int)dr.ItemArray[10] + ">"; } if ((string)dr.ItemArray[0] == Resources.EXT.ControllerLan.Con_NotBeenUsedStockTakeMaterial)//未被使用的盘点材料背景为黄色 { style = "<td bgcolor=yellow rowspan=" + (int)dr.ItemArray[10] + ">"; } str.Append(style); str.Append(m); str.Append("</td>"); str.Append(style); str.Append(dr.ItemArray[0]); str.Append("</td>"); str.Append(style); str.Append(dr.ItemArray[1]); str.Append("</td>"); str.Append(style); str.Append(dr.ItemArray[2]); str.Append("</td>"); if (SearchType == "1" || SearchType == null) { str.Append(style); str.Append(dr.ItemArray[3]); str.Append("</td>"); } } if (l % 2 == 0)//明细的偶数单元格为灰色 { style = "<td bgcolor=#E0E0E0>"; } else//明细奇数不变色 { style = "<td>"; } if ((string)dr.ItemArray[0] == Resources.EXT.ControllerLan.Con_NotBeenUsedStockTakeMaterial)//未被使用的盘点材料背景为黄色 { style = "<td bgcolor=yellow>"; } str.Append(style); str.Append(dr.ItemArray[4]); str.Append("</td>"); str.Append(style); str.Append(dr.ItemArray[5]); str.Append("</td>"); str.Append(style); str.Append(dr.ItemArray[6]); str.Append("</td>"); if (SearchType == "2") { str.Append(style); str.Append(dr.ItemArray[3]); str.Append("</td>"); } str.Append(style); str.Append(((decimal)dr.ItemArray[7]).ToString("0.##")); str.Append("</td>"); str.Append(style); str.Append(((decimal)dr.ItemArray[8]).ToString("0.##")); str.Append("</td>"); str.Append(style); str.Append(dr.ItemArray[9]); str.Append("</td>"); str.Append("</tr>"); } str.Append("</tbody></table>"); return str.ToString(); } #region Force Material [SconitAuthorize(Permissions = "Url_Mrp_MrpSnap_MachineInstance")] public string _GetForceMaterialView(string orderNo, DateTime? DateFrom, DateTime? DateTo) { int tableColumnCount; int mergerRows; SqlParameter[] sqlParams = new SqlParameter[3]; sqlParams[0] = new SqlParameter("@OrderNo", orderNo); sqlParams[1] = new SqlParameter("@DateFrom", DateFrom); sqlParams[2] = new SqlParameter("@DateTo", DateTo); DataSet ds = genericMgr.GetDatasetByStoredProcedure("USP_Report_InPutOutPut_ForceMaterial", sqlParams); //table returned from SP is a temporary table ,so colculate columns in SP. tableColumnCount = (int)ds.Tables[0].Rows[0][0]; mergerRows = (int)ds.Tables[1].Rows[0][0]; StringBuilder str = new StringBuilder("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"datatable\" width=\"100%\"><thead><tr>"); if (tableColumnCount == 0) { str.Clear(); str.Append("<p>"); str.Append(Resources.EXT.ControllerLan.Con_NoData); str.Append("</p>"); return str.ToString(); } #region Head for (int i = 1; i < tableColumnCount; i++) { //SP return each column's length str.Append("<th style='min-width:" + (int)ds.Tables[2].Rows[0][i] + "px'>"); str.Append(ds.Tables[1].Columns[i].ColumnName); str.Append("</th>"); } str.Append("</tr></thead><tbody>"); #endregion int l = 0; int markMerge = 0; string trcss = string.Empty; for (int i = 0; i < ds.Tables[1].Rows.Count; i++) { for (int j = 1; j < tableColumnCount; j++) { if (markMerge == 0 && ( j == 1||j == 2||j == 3 ||j == 4)) { if (j == 1) { l++; trcss = ""; if (l % 2 == 0) { trcss = "t-alt"; } str.Append("<tr class=\""); str.Append(trcss); str.Append("\">"); } str.Append("<td rowspan=\"" + mergerRows + "\" style=\"text-align:center\" >"); str.Append(ds.Tables[1].Rows[i][j]); str.Append("</td>"); } if (j > 4) { if (markMerge != 0 && j==5) { str.Append("<tr class=\""); str.Append(trcss); str.Append("\" >"); } str.Append("<td>"); str.Append(ds.Tables[1].Rows[i][j]); str.Append("</td>"); } } str.Append("</tr>"); markMerge++; if (markMerge == mergerRows && i != ds.Tables[1].Rows.Count-1) { markMerge = 0; mergerRows = (int)ds.Tables[1].Rows[i+1][0]; } } str.Append("</tbody></table>"); return str.ToString(); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine; using UnityEngine.UI; [System.Serializable] public struct CutsceneImage { public Sprite image; public AudioClip audio; public float delay; } public class Cutscene : MonoBehaviour { public string nextScene; public Image image; public List<CutsceneImage> cutscenes; public AudioSource audio; public int currentImage; public bool changing = false; // Use this for initialization void Start() { } // Update is called once per frame void Update() { if (Input.touchCount == 1) { var touchInfo = InputManager.ProcessTapInput (Input.GetTouch (0)); if (touchInfo.tapCount == 1 && touchInfo.phase == TouchPhase.Ended) { var touchLoc = touchInfo.touchLocation; if (touchLoc.x > .5) { ForceNext (); } else if (touchLoc.x < .5) { Previous (); } } } else if (Input.touchCount == 2) { StartCoroutine ("Wait"); SceneManager.LoadScene (nextScene); } Next(); } IEnumerator Wait() { yield return new WaitForSeconds (0.1f); } public void Next() { if (!audio.isPlaying) { ForceNext(); } } public void ForceNext() { if (currentImage == cutscenes.Count) { SceneManager.LoadScene(nextScene); return; } audio.clip = cutscenes[currentImage].audio; audio.Play(0); image.sprite = cutscenes[currentImage].image; currentImage++; } public void Previous() { currentImage--; if (currentImage == -1) { SceneManager.LoadScene ("Menu"); } audio.clip = cutscenes[currentImage].audio; audio.Play(0); image.sprite = cutscenes[currentImage].image; } }
using UnityEngine; public class ItemManager : MonoBehaviour { public enum Items { COINS, FUEL } private const float REDUCE = 5f; private float coinOffset = 1f; private float fuelOffset = 1f; public GameObject coin; public GameObject fuel; void Awake() { int c = PlayerPrefs.GetInt(Items.COINS.ToString().ToLower(), 0); int f = PlayerPrefs.GetInt(Items.FUEL.ToString().ToLower(), 0); coinOffset = GetReducer(c); fuelOffset = GetReducer(f); } private float GetReducer(int level) { int multuplier = 0; for (int i = 0; i < level; i++) { if ( i % 10 == 0) { multuplier++; } } float reducer = (REDUCE * multuplier) / 100f; return 1f - reducer; } public void newChunk(Chunk c){ Vector3[] vert = c.vertices; // Coins int v = 0; for (int i = 0; i < c.GetResolution(); i+=2) { if (i % 5 != 0) { continue; } float range = Random.Range(0f, 1f); if (range > coinOffset) { Vector3 p = c.transform.position + vert[v]; p.y++; GameObject obj = Instantiate (coin, p, Quaternion.identity); obj.transform.parent = c.transform; } v += 2; } // Fuel v = 0; for (int i = 0; i < c.GetResolution(); i++) { float range = Random.Range(0f, 1f); if (range > fuelOffset) { Vector3 p = c.transform.position + vert[v]; p.y++; GameObject obj = Instantiate (fuel, p, Quaternion.identity); obj.transform.localScale = new Vector3(.5f, .5f, .5f); obj.transform.parent = c.transform; break; } v += 2; } // int v = 0; // float seedCoins = UnityEngine.Random.Range(0f, 1000); // float seedFuel = UnityEngine.Random.Range(0f, 1000); // // for(int i = 0; i < c.GetResolution(); i++){ // Vector3 a = vert [v]; // Vector2 b = vert[v + 1]; // // // float h = Mathf.PerlinNoise (a.x * c.x + seedCoins, 0f); // Debug.Log(h); // // if(h > coinOffset){ // Vector3 p = c.transform.position + a; // p.y++; // GameObject obj = Instantiate (coin, p, Quaternion.identity); // obj.transform.parent = c.transform; // } // // v += 2; // // } // v = 0; // for(int i = 0; i < c.GetResolution(); i++){ // Vector3 a = vert [v]; // // float h = Mathf.PerlinNoise (a.x * c.x + seedFuel, 0f); // // if(h > fuelOffset){ // Vector3 p = c.transform.position + a; // p.y++; // GameObject obj = Instantiate (fuel, p, Quaternion.identity); // obj.transform.parent = c.transform; // return; // } // // v += 2; // // } } }
using System; using System.Collections.Generic; using System.Text; namespace DesignPatterns.Singleton.Example1 { //https://csharpindepth.com/articles/Singleton /// <summary> /// not thread-safe /// </summary> public class Singleton { private static Singleton _instance; private int count; private Singleton() { } public static Singleton Instance { get { if (_instance == null) _instance = new Singleton(); return _instance; } } internal void DoStuff() { count += 1; } } public class SampleUse { public void SomeMethod() { //call method Singleton.Instance.DoStuff(); //assign to another variable var myObject = Singleton.Instance; myObject.DoStuff(); //pass as parameter SomeOtherMethod(Singleton.Instance); } private void SomeOtherMethod(Singleton instance) { instance.DoStuff(); } } }
namespace Airelax.Defines { public class PhotoUploadSetting { public string BaseUrl { get; set; } public string CloudName { get; set; } public string UploadImageApi { get; set; } } }
namespace ComputersApplication { public class LaptopBattery { //constructors internal LaptopBattery() { this.Percentage = 100 / 2; } //properties internal int Percentage { get; set; } //methods internal void Charge(int percentLeft) { Percentage += percentLeft; if (Percentage > 100) { Percentage = 100; } if (Percentage < 0) { Percentage = 0; } } } }
using CrossPieCharts.FormsPlugin.Abstractions; using System; using Xamarin.Forms; using CrossPieCharts.FormsPlugin.iOSUnified; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(CrossPieChartView), typeof(CrossPieChartRenderer))] namespace CrossPieCharts.FormsPlugin.iOSUnified { /// <summary> /// CrossPieCharts Renderer /// </summary> public class CrossPieChartRenderer //: TRender (replace with renderer type { /// <summary> /// Used for registration with dependency service /// </summary> public static void Init() { } } }
using System; using System.Collections.Generic; using System.Drawing; using DelftTools.Utils; using SharpMap.Layers; using SharpMap.Styles; using GeoAPI.Extensions.Feature; using SharpMap.Topology; using SharpMap.UI.FallOff; using SharpMap.UI.Mapping; using GeoAPI.Geometries; using SharpMap.Converters.Geometries; using System.Windows.Forms; using System.Reflection; using SharpMap.UI.Snapping; namespace SharpMap.UI.Editors { public class LineStringEditor : FeatureEditor { public ITrackerFeature AllTracker { get; private set; } static private Bitmap trackerSmallStart; static private Bitmap trackerSmallEnd; static private Bitmap trackerSmall; static private Bitmap selectedTrackerSmall; public LineStringEditor(ICoordinateConverter coordinateConverter, ILayer layer, IFeature feature, VectorStyle vectorStyle, IEditableObject editableObject) : base(coordinateConverter, layer, feature, vectorStyle, editableObject) { Init(); } private void Init() { CreateTrackers(); } /// <summary> /// NS 2013-03-05 19:51, override fungsi ini agar point dapat bergerak, /// untuk lebih jelasnya lihat fungsi FetureEditor.AllowMoveCore() /// </summary> /// <returns>true</returns> protected override bool AllowMoveCore() { return true; } /// <summary> /// NS 2013-03-05 19:51, seperti halnya fungsi diatas, /// untuk lebih jelasnya lihat di FetureEditor.AllowSingleClickAndMove() /// </summary> /// <returns>true</returns> public override bool AllowSingleClickAndMove() { return true; } protected override void CreateTrackers() { if (trackerSmallStart == null) { trackerSmallStart = TrackerSymbolHelper.GenerateSimple(new Pen(Color.Blue), new SolidBrush(Color.DarkBlue), 6, 6); trackerSmallEnd = TrackerSymbolHelper.GenerateSimple(new Pen(Color.Tomato), new SolidBrush(Color.Maroon), 6, 6); //NS, 2013-10-11, Warna track symbol dari Green ke Red trackerSmall = TrackerSymbolHelper.GenerateSimple(new Pen(Color.Red), new SolidBrush(Color.OrangeRed), 6, 6);//TrackerSymbolHelper.GenerateSimple(new Pen(Color.Green), new SolidBrush(Color.Lime), 6, 6); selectedTrackerSmall = TrackerSymbolHelper.GenerateSimple(new Pen(Color.DarkMagenta), new SolidBrush(Color.Magenta), 6, 6); } trackers.Clear(); // optimization: SourceFeature.Geometry.Coordinates is an expensive operation if(SourceFeature.Geometry == null) { return; } ICoordinate[] coordinates = SourceFeature.Geometry.Coordinates; //NS, 2014-05-06 //Untuk point akhir dari polygon tidak dibuatkan tracker int coordCount = 0; if (SourceFeature.Geometry.GeometryType == "Polygon") coordCount = coordinates.Length - 1; else coordCount = coordinates.Length; //for (int i = 0; i < coordinates.Length; i++) for (int i = 0; i < coordCount; i++) { ICoordinate coordinate = coordinates[i]; IPoint selectPoint = GeometryFactory.CreatePoint(coordinate.X, coordinate.Y); if (0 == i) trackers.Add(new TrackerFeature(this, selectPoint, i, trackerSmallStart)); else if ((coordinates.Length - 1) == i) trackers.Add(new TrackerFeature(this, selectPoint, i, trackerSmallEnd)); else trackers.Add(new TrackerFeature(this, selectPoint, i, trackerSmall)); } AllTracker = new TrackerFeature(this, null, -1, null); } public override ITrackerFeature GetTrackerAtCoordinate(ICoordinate worldPos) { ITrackerFeature trackerFeature = base.GetTrackerAtCoordinate(worldPos); if (null == trackerFeature) { ICoordinate org = CoordinateConverter.ImageToWorld(new PointF(0, 0)); ICoordinate range = CoordinateConverter.ImageToWorld(new PointF(6, 6)); // todo make attribute if (SourceFeature.Geometry.Distance(GeometryFactory.CreatePoint(worldPos)) < Math.Abs(range.X - org.X)) return AllTracker; } return trackerFeature; } public override bool MoveTracker(ITrackerFeature trackerFeature, double deltaX, double deltaY, ISnapResult snapResult) { if (trackerFeature == AllTracker) { int index = -1; IList<int> handles = new List<int>(); IList<IGeometry> geometries = new List<IGeometry>(); for (int i = 0; i < trackers.Count; i++) { geometries.Add(trackers[i].Geometry); //if (trackers[i].Selected) { handles.Add(i); } if (trackers[i] == trackerFeature) { index = i; } } if (0 == handles.Count) return false; if (null == FallOffPolicy) { FallOffPolicy = new NoFallOffPolicy(); } FallOffPolicy.Move(TargetFeature.Geometry, geometries, handles, index, deltaX, deltaY); foreach (IFeatureRelationEditor topologyRule in TopologyRules) { topologyRule.UpdateRelatedFeatures(SourceFeature, TargetFeature.Geometry, new List<int> { 0 }); } return true; } return base.MoveTracker(trackerFeature, deltaX, deltaY, snapResult); } public override Cursor GetCursor(ITrackerFeature trackerFeature) { // ReSharper disable AssignNullToNotNullAttribute if (trackerFeature == AllTracker) return Cursors.SizeAll; return new Cursor(Assembly.GetExecutingAssembly().GetManifestResourceStream("SharpMap.UI.Cursors.moveTracker.cur")); // ReSharper restore AssignNullToNotNullAttribute } public override void Select(ITrackerFeature trackerFeature, bool select) { trackerFeature.Selected = select; trackerFeature.Bitmap = select ? selectedTrackerSmall : trackerSmall; } } }
using System; using System.Collections.Generic; using System.Linq; /* * tags: bfs/dp * Time(n2^n), Space(n2^n) * dp(state|next, next) = min(dp(state|next, next), dp(state, head) + 1), for each edge (head -> next) * the state can be a bitwise integer. * Relax/tighten the distance from state with head vertex to state|next with head next vertex until we get the final state(2^n-1) */ namespace leetcode { public class Lc847_Shortest_Path_Visiting_All_Nodes { public int ShortestPathLength(int[][] graph) { int n = graph.Length; int INF = n * n; int finalState = (1 << n) - 1; var dist = new int[1 << n, n]; var q = new LinkedList<State>(); for (int v = 0; v < n; v++) { for (int s = 0; s < dist.GetLength(0); s++) dist[s, v] = INF; dist[1 << v, v] = 0; q.AddLast(new State(1 << v, v)); } while (q.Count > 0) { var currState = q.First.Value; q.RemoveFirst(); if (currState.Cover == finalState) return dist[currState.Cover, currState.Head]; foreach (var next in graph[currState.Head]) { var nextState = new State(currState.Cover | (1 << next), next); if (dist[nextState.Cover, nextState.Head] > dist[currState.Cover, currState.Head] + 1) { dist[nextState.Cover, nextState.Head] = dist[currState.Cover, currState.Head] + 1; q.AddLast(nextState); } } } return -1; } class State { public int Cover; public int Head; public State(int cover, int head) { Cover = cover; Head = head; } } public void Test() { var grap = new int[][] { new int[] { 1, 2, 3 }, new int[] { 0 }, new int[] { 0 }, new int[] { 0 } }; Console.WriteLine(ShortestPathLength(grap) == 4); grap = new int[][] { new int[] { 1 }, new int[] { 0, 2, 4 }, new int[] { 1, 3, 4 }, new int[] { 2 }, new int[] { 1, 2 } }; Console.WriteLine(ShortestPathLength(grap) == 4); grap = new int[][] { new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, new int[] { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, new int[] { 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, new int[] { 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11 }, new int[] { 0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11 }, new int[] { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11 }, new int[] { 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11 }, new int[] { 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11 }, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11 }, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 }, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 }, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }; Console.WriteLine(ShortestPathLength(grap) == 11); } } }
using System; using System.Collections.Generic; using System.Text; namespace SAAS.FrameWork.Extensions { public static partial class ByteDataExtensions { public static int ByteDataCount(this List<ArraySegment<byte>> byteData) { if (null == byteData || byteData.Count == 0) return 0; int count = 0; foreach (var item in byteData) { if (null != item) { count += item.Count; } } return count; } #region ByteData <--> Bytes public static byte[] ByteDataToBytes(this List<ArraySegment<byte>> byteData) { int count = 0; foreach (var item in byteData) { count += item.Count; } var bytes = new byte[count]; int curIndex = 0; foreach (var item in byteData) { if (null == item.Array || item.Count == 0) continue; item.CopyTo(bytes, curIndex); curIndex += item.Count; } return bytes; } #endregion #region ByteData <--> String public static string ByteDataToString(this List<ArraySegment<byte>> data) { return data.ByteDataToBytes().BytesToString(); } public static List<ArraySegment<byte>> StringToByteData(this string data) { return new List<ArraySegment<byte>> { data.StringToArraySegmentByte() }; } #endregion } }
using System; using System.Text; class chapt7 { static void Main() { string s1 = "foobar"; string s2 = "foobar"; int compVal = String.Compare(s1, s2); switch(compVal) { case 0 : Console.WriteLine(s1 + " " + s2 + " are equal"); break; case 1 : Console.WriteLine(s1 + " is less than " + s2); break; case 2 : Console.WriteLine(s1 + " is greater than" + s2); break; default : Console.WriteLine("Can't compare"); break; } } }
using System; namespace Theatre.Model { public class DataMenuItem { public string Title { get; set; } public string Icon { get; set; } public Type TargetType { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class VRMove : MonoBehaviour { public static VRMove singleton; void Awake(){ if(VRMove.singleton==null){ VRMove.singleton = this; } } public float moveSpeed; public float rotationSpeed; public Vector2 moveStick; public Vector2 rotateStick; Vector3 moveVector; public Transform head; public Transform toRotate; Quaternion myRotation; // Use this for initialization public Vector3 myOffset; void Start() { myOffset = transform.localPosition; } // Update is called once per frame void FixedUpdate() { OVRInput.Update(); moveStick = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick); rotateStick = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick); //---------movement---------------// //myRotation = Quaternion.LookRotation(new Vector3(head.forward.x, 0, head.forward.z).normalized, Vector3.up); //moveVector = myRotation * (transform.forward * moveStick.y + transform.right * moveStick.x); moveVector = (head.forward * moveStick.y + head.right * moveStick.x); moveVector = new Vector3(moveVector.x,0,moveVector.z); //transform.Translate(moveVector * moveSpeed * Time.deltaTime); //transform.Translate(moveVector * moveSpeed * Time.deltaTime,Space.Self); transform.position = transform.position + moveVector* moveSpeed * Time.deltaTime; //--------------rotation--------------// toRotate.RotateAround(head.position, Vector3.up, Time.deltaTime * rotationSpeed * rotateStick.x); } public void TeleportToPosition(Vector3 targetPosition){ Vector3 distanceToHead = transform.position-head.position; distanceToHead.y = 0; transform.position = myOffset+targetPosition+(distanceToHead); } }
using AlintaEnergy.Application.Extensions; using AlintaEnergy.ViewModels; using AutoMapper; using DataContext.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlintaEnergy.Application.AutoMapper { public class ViewModelToDomainMappingProfile : Profile { public ViewModelToDomainMappingProfile() { CreateMap<CustomerVM, Customer>() .ForMember(dest => dest.DoB, opt => opt.MapFrom(src => src.DoB.ParseDate())); } } }
using Common.Data; using Common.Exceptions; using Common.Extensions; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Runtime.Serialization; namespace Entity { [DataContract] public partial class SystemRPSFileType : IMappable { #region Constructors public SystemRPSFileType() { } #endregion #region Public Properties /// <summary> /// Gets the name of the table to which this object maps. /// </summary> public string TableName { get { return "System_RPS_FileType"; } } [DataMember] public string File_Type { get; set; } #endregion #region Public Methods public SystemRPSFileType GetRecord(string connectionString, string sql, SqlParameter[] parameters = null) { SystemRPSFileType result = null; using (Database database = new Database(connectionString)) { try { CommandType commandType = CommandType.Text; if (parameters != null) commandType = CommandType.StoredProcedure; using (DataTable table = database.ExecuteSelect(sql, commandType, parameters)) { if (table.HasRows()) { Mapper<SystemRPSFileType> m = new Mapper<SystemRPSFileType>(); result = m.MapSingleSelect(table); } } } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public List<SystemRPSFileType> GetList(string connectionString, string sql, SqlParameter[] parameters = null) { List<SystemRPSFileType> result = new List<SystemRPSFileType>(); using (Database database = new Database(connectionString)) { try { CommandType commandType = CommandType.Text; if (parameters != null) commandType = CommandType.StoredProcedure; using (DataTable table = database.ExecuteSelect(sql, commandType, parameters)) { if (table.HasRows()) { Mapper<SystemRPSFileType> m = new Mapper<SystemRPSFileType>(); result = m.MapListSelect(table); } } } catch (Exception e) { throw new EntityException(sql, e); } } return result; } #endregion } }
using UnityEngine; using UnityEngine.Rendering; public class PlayerHealthController : MonoBehaviour { #region Variables #region Components private HitFlash m_hitFlash; private BoxCollider2D m_playerCollider; #endregion #region Public Variables #endregion #region Private Variables #region Serializable Variables [SerializeField] private uint m_maxHealth; [SerializeField] private HeartsHealthVisual m_HeartsHealthVisual; [Space] [SerializeField] private float m_hitFlashTime; [SerializeField] private float m_invulnerabilityTime; [Space] [SerializeField] private GameObject m_deathAnimation; #endregion #region Non-Serializable Variables private AudioManager m_audioManager; private CameraController m_cameraController; private uint m_currentHealth; private float m_currentInvulnerabilityTime; #endregion #endregion #endregion #region BuiltIn Methods void Start() { m_currentHealth = m_maxHealth; m_HeartsHealthVisual.InitHealth(m_currentHealth); m_cameraController = Camera.main.GetComponent<CameraController>(); m_audioManager = GameObject.FindGameObjectWithTag("AudioManager").GetComponent<AudioManager>(); m_hitFlash = GetComponent<HitFlash>(); m_playerCollider = GetComponent<BoxCollider2D>(); } void FixedUpdate() { if (m_currentInvulnerabilityTime > 0) { m_currentInvulnerabilityTime = Mathf.Max(0, m_currentInvulnerabilityTime - Time.deltaTime); } if (m_currentInvulnerabilityTime == 0) if (!m_playerCollider.enabled) m_playerCollider.enabled = true; } void LateUpdate() { if (m_currentHealth == 0) { Die(); } } void OnTriggerEnter2D(Collider2D col) { //ENEMY PROJECTILES if (col.gameObject.layer == 14) { if (m_currentInvulnerabilityTime <= 0) { if (col.gameObject.GetComponent<EnemyProjectileController>()) { TakeDamage(col.gameObject.GetComponent<EnemyProjectileController>().GetDamage()); Destroy(col.gameObject); } if (col.gameObject.GetComponent<EvilProjectileController>()) { if (col.gameObject.GetComponent<EvilProjectileController>().GetDamage() > 0) { TakeDamage(col.gameObject.GetComponent<EvilProjectileController>().GetDamage()); Destroy(col.gameObject); } else { col.gameObject.GetComponent<EvilProjectileController>().CustomProjectileStart(); Destroy(col.gameObject); } } } } //PLAYER AREA DAMAGE if (col.gameObject.layer == 18) { if (m_currentInvulnerabilityTime <= 0) { TakeDamage(3); } } //ENEMY AREA DAMAGE if (col.gameObject.layer == 19) { if (m_currentInvulnerabilityTime <= 0) { TakeDamage(3); } } //PICKABLE if (col.gameObject.layer == 9) { m_audioManager.Play("SFX", "Pickup"); if (col.gameObject.CompareTag("HealingPickup")) { if (col.gameObject.GetComponent<HealingPickup>()) Heal(col.gameObject.GetComponent<HealingPickup>().amount); } Destroy(col.gameObject); } } void OnCollisionStay2D(Collision2D col) { if (col.gameObject.CompareTag("Enemy")) { if (m_currentInvulnerabilityTime <= 0) { TakeDamage(col.gameObject.GetComponent<EnemyMovement>().touchDamage); } } } void OnParticleCollision(GameObject other) { if (other.gameObject.layer == 14) { if (m_currentInvulnerabilityTime <= 0) { TakeDamage(1); } } } #endregion #region Custom Methods void TakeDamage(uint damage) { if (m_currentHealth <= damage) m_currentHealth = 0; else m_currentHealth -= damage; m_currentInvulnerabilityTime = m_invulnerabilityTime; m_hitFlash.Flash(m_hitFlashTime); m_audioManager.Play("SFX", "HurtPlayer"); m_HeartsHealthVisual.UpdateHealth(m_currentHealth); m_cameraController.Shake(); m_playerCollider.enabled = false; } void Heal(uint amount) { m_currentHealth += amount; m_HeartsHealthVisual.UpdateHealth(m_currentHealth); } private void Die() { GameObject deathAnimation = Instantiate(Instantiate(m_deathAnimation, transform.position, Quaternion.identity)); m_audioManager.Play("SFX", "EvilLaugh"); m_audioManager.Stop("Music", 3f); m_cameraController.transform.parent.GetComponent<SlowFollow>().followSpeed = 0.01f; m_cameraController.transform.parent.GetComponent<SlowFollow>().followTransform = deathAnimation.transform.GetChild(0); if (transform.GetChild(0).childCount > 0) PlayerPrefs.SetInt(transform.GetChild(0).GetChild(0).GetComponent<AbstractSpell>().evilName, 1); GameObject.Find("Load Manager").GetComponent<LoadManager>().LoadNextLevel(4); int currentScore = GameObject.FindGameObjectWithTag("ScoreManager").GetComponent<ScoreManager>().GetScore(); if (currentScore > PlayerPrefs.GetInt("highscore")) { PlayerPrefs.SetInt("highscore", currentScore); } PlayerPrefs.SetInt("played", 1); Destroy(gameObject); } #endregion }
using System.Collections.Generic; using System.Linq; namespace CIS016_2.Common.ExtensionMethods { public static class ListExtensions { /// <summary> /// Allows to divide source list into list of smaller lists of selected size /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">source list</param> /// <param name="chunkSize">Size to what the list will be divided</param> /// <returns></returns> public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize) { return source.Select((x, i) => new { Index = i, Value = x }) .GroupBy(x => x.Index / chunkSize) .Select(x => x.Select(v => v.Value) .ToList()).ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Runtime.InteropServices; namespace identity { public class Gameplay { public Game1 game; Texture2D Kurt, Stam, Heal, lantern; public static Vector2 KurtPos; public static int Health; public static double Stamina; Vector2 StamPos = new Vector2(50, 60); Vector2 HealthPos = new Vector2(50, 30); Vector2 MovePos; public static Rectangle KurtRect; float walktime; int step; int stampowerup = 1; float stamtimer; float healthtimer; private KeyboardState newState; public static float KurtOpaque = 1; public Rectangle lanpos = new Rectangle(1050, 20, 80, 108); public float lantscale = 0.3f; Point frameSize = new Point(94, 108); public static Point currentFrame = new Point(0, 0); Point sheetSize = new Point(3, 0); int timeSinceLastFrame = 0; int millisecondsPerFrame = 100; public Gameplay(Game1 game) { this.game = game; Kurt = game.Content.Load<Texture2D>("images/KURT SPREEDSHEET 2"); Stam = game.Content.Load<Texture2D>("images/Stamina"); Heal = game.Content.Load<Texture2D>("images/Health"); lantern = game.Content.Load<Texture2D>("images/lantern"); Health = 1000; Stamina = 1000; } public void Update(GameTime Gametime) { //Movement KeyboardState keyboardState = Keyboard.GetState(); newState = keyboardState; if (walktime == 0) { if (Text.textpause == 0) { if (newState.IsKeyDown(Keys.Up)) { step = 1; currentFrame.Y = 1; } if (newState.IsKeyDown(Keys.Down)) { step = 2; currentFrame.Y = 0; } if (newState.IsKeyDown(Keys.Left)) { step = 3; currentFrame.Y = 2; } if (newState.IsKeyDown(Keys.Right)) { step = 4; currentFrame.Y = 3; } } if (newState.IsKeyUp(Keys.Right) && newState.IsKeyUp(Keys.Left) && newState.IsKeyUp(Keys.Up) && newState.IsKeyUp(Keys.Down)) { currentFrame.X = 0; } } if (step == 1) { walktime += 1; KurtPos.Y -= MovePos.Y; } if (step == 2) { walktime += 1; KurtPos.Y += MovePos.Y; } if (step == 3) { walktime += 1; KurtPos.X -= MovePos.X; } if (step == 4) { walktime += 1; KurtPos.X += MovePos.X; } if (step == 1 || step == 2) { if (walktime >= 18) { step = 0; walktime = 0; } } if (step == 3 || step == 4) { if (walktime >= 17) { step = 0; walktime = 0; } } if (walktime >= 1) { if (newState.IsKeyDown(Keys.LeftShift)) { if (Stamina > 0) { MovePos = new Vector2(10, 12); } else { MovePos = new Vector2(5, 6); } Stamina -= 5; stamtimer = 0; } else if (newState.IsKeyDown(Keys.RightShift)) { MovePos = new Vector2(2, 2); } else { MovePos = new Vector2(5, 6); } } //Sprite Movement if (step != 0) { timeSinceLastFrame += Gametime.ElapsedGameTime.Milliseconds; if (timeSinceLastFrame > millisecondsPerFrame) { timeSinceLastFrame -= millisecondsPerFrame; ++currentFrame.X; if (currentFrame.X > sheetSize.X) { currentFrame.X = 0; } } } KurtRect = new Rectangle((int)KurtPos.X, (int)KurtPos.Y, 84, 108); //Stamina and Health Regen if (Stamina <= 0) { Stamina = 0; } if (Stamina >= 1000) { Stamina = 1000; } if (newState.IsKeyUp(Keys.LeftShift)) { stamtimer += 0.016666f; if (stamtimer >= 3) Stamina += 0.4f * stampowerup; } if (newState.IsKeyDown(Keys.P)) { game.pausegame = 1; } if (Health <= 0) { Health = 0; } if (Health >= 1000) { Health = 1000; } } public void Draw(SpriteBatch spritebatch) { spritebatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend); spritebatch.Draw(Kurt, KurtPos, new Rectangle(currentFrame.X * frameSize.X, currentFrame.Y * frameSize.Y, frameSize.X, frameSize.Y), Color.White * KurtOpaque, 0, Vector2.Zero, 1, SpriteEffects.None, 0); spritebatch.Draw(Stam, StamPos, new Rectangle(0, 0, (int)((0.255 * Stamina) + 5), 23), Color.White * 0.6f, 0, Vector2.Zero, game.scale, SpriteEffects.None, 0); spritebatch.Draw(Heal, HealthPos, new Rectangle(0, 0, (int)((0.255 * Health) + 5), 23), Color.White * 0.6f, 0, Vector2.Zero, game.scale, SpriteEffects.None, 0); if (Chapter2b.langet == 1) { spritebatch.Draw(lantern, new Vector2(lanpos.X, lanpos.Y), null, Color.White, 0, Vector2.Zero, lantscale, SpriteEffects.None, 1); } spritebatch.End(); } } }
#region License //*****************************************************************************/ // Copyright (c) 2012 Luigi Grilli // // 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. //*****************************************************************************/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using ByteArray = Grillisoft.ImmutableArray.ImmutableArray<byte>; namespace Grillisoft.FastCgi.Protocol { public class NameValuePairCollection : IEnumerable<NameValuePair> { private Dictionary<string, NameValuePair> _dictionary = new Dictionary<string, NameValuePair>(); public NameValuePairCollection() { } public NameValuePairCollection(Stream stream) { using (BinaryReader reader = new BinaryReader(stream, Encoding.UTF8)) { this.ReadCollection(reader); } } private void ReadCollection(BinaryReader reader) { var stream = reader.BaseStream; while (stream.Position < stream.Length /* check for stream EOF */) { try { this.Add(new NameValuePair(reader)); } catch (EndOfStreamException) { break; //exit loop } } } public string GetValue(string name) { NameValuePair ret; return _dictionary.TryGetValue(name, out ret) ? ret.Value : null; } public NameValuePair GetPair(string name) { NameValuePair ret; return _dictionary.TryGetValue(name, out ret) ? ret : null; } public void Add(NameValuePair pair) { _dictionary.Add(pair.Name, pair); } public void Add(IEnumerable<NameValuePair> collection) { foreach (NameValuePair item in collection) this.Add(item); } public int Count { get { return _dictionary.Count; } } public bool ContainsKey(string name) { return _dictionary.ContainsKey(name); } #region IEnumerable implementation public IEnumerator<NameValuePair> GetEnumerator() { return _dictionary.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _dictionary.Values.GetEnumerator(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using Common; using ComplexSystems; namespace EconomicModels { public class Member { public Member(double a) { assets = a; memberId = Guid.NewGuid(); } Guid memberId; private double assets { get; set; } public void AddAssets(double a) { assets += a; } public double AssetsToAddNextTurn = 0; public double GetAssets() { return assets; } public override bool Equals(object obj) { Guid g = ((Member)obj).memberId; return memberId.Equals(g); } public override int GetHashCode() { return memberId.GetHashCode(); } Dictionary<Member, double> investors = new Dictionary<Member, double>(); double totalInvestment = 0; public void TakeInvestment(Member e, double amount) { totalInvestment += amount; if (investors.ContainsKey(e)) { throw new Exception(); } else { investors.Add(e, amount); } } public void UpdateAssets() { AddAssets(AssetsToAddNextTurn); AssetsToAddNextTurn = 0; } public void ClearAllInvestors() { totalInvestment = 0; investors = new Dictionary<Member, double>(); } public void PayInvestors() { double interest = 1; ///double interest = 7 / 50; double totalPaid = 0; double fullAssets = assets; for (int i = 0; i < investors.Count(); i++) { var a = investors.ElementAt(i); double amountToPay = (fullAssets * (a.Value / totalInvestment)); //amountToPay *= interest; totalPaid += amountToPay; assets -= amountToPay; //a.Key.AddAssets(amountToPay) a.Key.AssetsToAddNextTurn += amountToPay; } } } public class Economy2 { List<Member> Members = new List<Member>(); static Random rand = new Random(); static public int iterationIdx= 0; int numberOfMembers; public Economy2(int members, int iterations) { numberOfMembers = members; for(int i=0;i < members; i++){ //Members.Add(new Member(rand.Next(10,20))); Members.Add(new Member(15)); } Debug.Print(members.ToString() + " members in this economy, iterating " + iterations.ToString() + " times."); PrintWealth(); while (iterationIdx++ < iterations) { Debug.Print("Iteration IDX: " + iterationIdx.ToString()); InvestMoney(); PayInvesors(); ClearInvestors(); PrintWealth(); } } public void ClearInvestors() { foreach (var a in Members) { a.ClearAllInvestors(); a.UpdateAssets(); } } public void InvestMoney() { int numberOfInvestments = numberOfMembers; //The index doing the investing: for(int i=0 ;i < numberOfMembers; i++){ var investor = this.Members[i]; List<double> partitions = new List<double>(); //Generate N random numbers for (int j = 0; j < numberOfInvestments -1 ; j++) { partitions.Add(rand.NextDouble()); } partitions.Add(1); //Sort the numbers partitions.Sort(); //Each partition corresponds to the investment amount in order //The index getting the investment double totalPercentInvested = 0; double totalMoneyInvested = 0; for (int j = 0; j < numberOfInvestments; j++) { double percentToInvest = (partitions[j] - totalPercentInvested); var investee = this.Members[j]; investee.TakeInvestment(investor, percentToInvest * investor.GetAssets()); totalMoneyInvested += percentToInvest * investor.GetAssets() ; totalPercentInvested += percentToInvest; } //Debug.Print("Total percent invested: " + totalPercentInvested.ToString()); //Debug.Print("Total monies invested: " + totalMoneyInvested.ToString()); } } public void PayInvesors() { foreach (var a in Members) { a.PayInvestors(); //Check that assets are now zero and if not throw an exception } } Signal cumulativeSignal = new Signal(); public void PrintWealth() { double totalValue = 0; List<double> assets = new List<double>(); for(int i=0; i < Members.Count(); i++){ var a = Members[i].GetAssets(); //Debug.Print(i.ToString() + ": " + Members[i].GetAssets().ToString()); totalValue += a; assets.Add(a); //cumulativeSignal.Add(a); } //if (iterationIdx > 300) { var h = new Histogram(new Signal(assets), .3); //h.Graph(); h.SaveImage("chart " + iterationIdx.ToString() + ".bmp"); //cumulativeSignal.RankOrder().Graph(); //} double average = assets.Average(); double SD = assets.CalculateStdDev(); Debug.Print("Total value: " + totalValue.ToString() +" average wealth: " + average.ToString() + " standard deviation: " + SD.ToString()); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallReturn : MonoBehaviour { private BallLauncher ballLauncher; private void Awake() { ballLauncher = FindObjectOfType<BallLauncher>(); } private void OnCollisionEnter2D(Collision2D collision) { collision.gameObject.transform.GetComponent<Rigidbody2D>().velocity = new Vector2(0,0); ballLauncher.ReturnBall(); collision.collider.gameObject.SetActive(false); } }
using EntityLayer.AdminDetails; using System.Collections.Generic; using System.Threading.Tasks; namespace EntityLayer.IAdminRepositorys { public interface IAdminRepository { Task Add<T>(T entity) where T : class; Task<Admin> GetOneAdmin(int id); Task<List<Admin>> GetAllAdmin(); void Delete<T>(T entity) where T : class; Task<bool> SaveAllChangesAsync(); void Update<T>(T entity) where T : class; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BackToBasics { public class Pony { int taille; ConsoleColor Color; public Pony(ConsoleColor Couleur) { Random rnd = new Random(); this.taille = rnd.Next(2, 10); this.Color = Couleur; } public void display() { string poney = "."; for (int i = 0; i < taille; i++) { poney += "="; } poney += ".°"; ConsoleColor old = Console.ForegroundColor; Console.ForegroundColor = Color; Console.Write(poney); Console.ForegroundColor = old; } } }
using DgKMS.Cube.CubeCore; using DgKMS.Cube.CubeCore.Dtos; using Microsoft.EntityFrameworkCore; using Shouldly; using System; using System.Threading.Tasks; using Xunit; namespace DgKMS.Cube.Tests.EvernoteTags { public class EvernoteTagAppService_Tests : CubeTestBase { private readonly IEvernoteTagAppService _evernoteTagAppService; public EvernoteTagAppService_Tests() { _evernoteTagAppService = Resolve<IEvernoteTagAppService>(); } [Fact] public async Task CreateEvernoteTag_Test() { await _evernoteTagAppService.CreateOrUpdate(new CreateOrUpdateEvernoteTagInput { EvernoteTag = new EvernoteTagEditDto { Guid = "test", Name = "test", ParentGuid = "test", //CreationTime = DateTime.Now, } }); await UsingDbContextAsync(async context => { var dystopiaEvernoteTag = await context.EvernoteTags.FirstOrDefaultAsync(); dystopiaEvernoteTag.ShouldNotBeNull(); } ); } [Fact] public async Task GetEvernoteTags_Test() { // Act var output = await _evernoteTagAppService.GetPaged(new GetEvernoteTagsInput { MaxResultCount = 20, SkipCount = 0 }); // Assert output.Items.Count.ShouldBeGreaterThanOrEqualTo(0); } //// custom codes //// custom codes end } }
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // Copyright (c) 2017, Stefan Fritsch // // 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. namespace SafetySharp.Bayesian { using System.Collections.Generic; /// <summary> /// Configurations for learning bayesian networks /// </summary> public struct BayesianLearningConfiguration { /// <summary> /// Use the results of a DCCA for the structure learning algorithms, the DCCA structure will be guaranteed in the learned model /// </summary> public bool UseDccaResultsForLearning { get; set; } /// <summary> /// The maximal size for condition sets while learning conditional independencies /// </summary> public int MaxConditionSize { get; set; } /// <summary> /// Flag whether to use the actual probabilities while generating the simulation data. If false, a uniform distribution will be used /// </summary> public bool UseRealProbabilitiesForSimulation { get; set; } /// <summary> /// Optional file path for serializing the calculated probabilites while modelchecking /// </summary> public string ProbabilitySerializationFilePath { get; set; } /// <summary> /// Optional file path for deserializing already known probabilities for modelchecking /// </summary> public string ProbabilityDeserializationFilePath { get; set; } /// <summary> /// Optional file path for serializing the bayesian network result /// </summary> public string BayesianNetworkSerializationPath { get; set; } public IList<string> FurtherSimulationDataFiles { get; set; } public static BayesianLearningConfiguration Default => new BayesianLearningConfiguration { UseDccaResultsForLearning = true, MaxConditionSize = int.MaxValue, UseRealProbabilitiesForSimulation = true, ProbabilitySerializationFilePath = "", ProbabilityDeserializationFilePath = "", BayesianNetworkSerializationPath = "", FurtherSimulationDataFiles = new List<string>() }; } }