content
stringlengths
23
1.05M
using System; using System.Text; namespace CsrBleLibrary.BleV1 { public class BleDevice { //private static int index; public string Address; public string Name; //public string Service; //public string Manu; internal uint ConnHandle; internal uint ReadHandle; internal uint WriteHandle; public BleDevice() { //Service = index++.ToString(); } public BleDevice(string dev) { string[] devStrings = dev.Split('|'); if (devStrings.Length < 2) { throw new FormatException("Device String Format Error"); } Name = devStrings[0].Remove(0, devStrings[0].IndexOf(":", StringComparison.Ordinal)+1); Address = devStrings[1].Remove(0, devStrings[1].IndexOf(":", StringComparison.Ordinal) + 1); //Service = devStrings[2].Remove(0, 8); //Manu = devStrings[3].Remove(0, 5); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(string.Format("设备:{0}|", string.IsNullOrEmpty(Name) ? "[NULL]" : Name)); sb.Append(string.Format("地址:{0}|", Address)); //sb.Append(string.Format("Service:{0}|", Service)); //sb.Append(string.Format("Manu:{0}", Manu)); return sb.ToString(); } } }
using Google.Apis.Auth.OAuth2; using Google.Apis.Gmail.v1; using Google.Apis.Gmail.v1.Data; using Google.Apis.Services; using Google.Apis.Util.Store; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace GmailParserConsoleClient { public class GmailParser { private static string[] Scopes = { GmailService.Scope.GmailReadonly }; private static string ApplicationName = "GmailParser"; public void AuthorizeApplication() { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "me", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Gmail API service. var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me"); // List labels. IList<Label> labels = request.Execute().Labels; Console.WriteLine("Labels:"); if (labels != null && labels.Count > 0) { foreach (var labelItem in labels) { Console.WriteLine("{0}", labelItem.Name); } } else { Console.WriteLine("No labels found."); } } public GmailService GetGmailService() { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "me", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Gmail API service. var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); return service; } public List<Message> ListMessages(GmailService service, String userId, String query) { List<Message> result = new List<Message>(); UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId); request.Q = query; do { try { ListMessagesResponse response = request.Execute(); result.AddRange(response.Messages); request.PageToken = response.NextPageToken; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } } while (!String.IsNullOrEmpty(request.PageToken)); return result; } public Message GetMessage(GmailService service, String userId, String messageId) { try { var messagesApiCall = service.Users.Messages.Get(userId, messageId); messagesApiCall.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full; return messagesApiCall.Execute(); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } return null; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Chocolatey" file="PersistenceService.cs"> // Copyright 2017 - Present Chocolatey Software, LLC // Copyright 2014 - 2017 Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.IO; using ChocolateyGui.Common.Services; using Microsoft.Win32; namespace ChocolateyGui.Common.Windows.Services { public class PersistenceService : IPersistenceService { public Stream OpenFile(string defaultExtension, string filter) { var fd = new OpenFileDialog { DefaultExt = defaultExtension, Filter = filter }; var result = fd.ShowDialog(); return result != null && result.Value ? fd.OpenFile() : null; } public Stream SaveFile(string defaultExtension, string filter) { var fd = new SaveFileDialog { DefaultExt = defaultExtension, Filter = filter }; var result = fd.ShowDialog(); return result != null && result.Value ? fd.OpenFile() : null; } public string GetFilePath(string defaultExtension, string filter) { var fd = new SaveFileDialog { DefaultExt = defaultExtension, Filter = filter }; var result = fd.ShowDialog(); return result != null && result.Value ? fd.FileName : null; } } }
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Todo.Data.Seeds { public static class UserSeed { public static void Seed(UserManager<IdentityUser> userManager) { if (userManager.FindByEmailAsync("admin@todo.com").Result != null) { return; } var user = new IdentityUser { UserName = "admin@todo.com", Email = "admin@todo.com" }; var result = userManager.CreateAsync(user, "AdminTodo123!").Result; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class DynamicObjectPool<T_PoolOf> where T_PoolOf : MonoBehaviour { private GameObject _prefab; private RectTransform _container; private List<T_PoolOf> _objectPool; private int _itemCount = 0; public delegate void ObjectCreatedDelegate(T_PoolOf created); private ObjectCreatedDelegate OnObjectCreatedEvent; public void Init(GameObject prefab, RectTransform container, ObjectCreatedDelegate onObjectCreated = null) { _prefab = prefab; _container = container; if (onObjectCreated != null) { OnObjectCreatedEvent += onObjectCreated; } } //Getting the object at index so you can use pool[i] to set and get public T_PoolOf this[int key] { get { return GetValue(key); } set { SetValue(key, value); } } private void SetValue(int key, T_PoolOf value) { _objectPool[key] = value; } private T_PoolOf GetValue(int key) { return _objectPool[key]; } public List<T_PoolOf> GetPooledObjects(bool activeOnly = true) { if(_objectPool != null) { if (activeOnly) { List<T_PoolOf> activeItems = null; for (int i = 0; i < _objectPool.Count; i++) { if(_objectPool[i].gameObject.activeInHierarchy) { if(activeItems == null) { activeItems = new List<T_PoolOf>(); } activeItems.Add(_objectPool[i]); } } return activeItems; } else { return _objectPool; } } return null; } public void AddItem(ref int nextChildCount) { if(_objectPool == null) { _objectPool = new List<T_PoolOf>(); } if(_itemCount >= _objectPool.Count || _objectPool[_itemCount] == null) { GameObject item = UnityEngine.Object.Instantiate(_prefab); item.transform.SetParent(_container, false); item.transform.localScale = Vector3.one; item.transform.SetSiblingIndex(nextChildCount); item.name = string.Format("item_{0}_{1}", nextChildCount, (typeof(T_PoolOf)).ToString()); T_PoolOf pooledObject = item.GetComponent<T_PoolOf>(); _objectPool.Add(pooledObject); _itemCount++; nextChildCount++; if(OnObjectCreatedEvent != null) { OnObjectCreatedEvent(pooledObject); } } else { T_PoolOf item = _objectPool[_itemCount]; item.transform.SetSiblingIndex(nextChildCount); item.name = string.Format("item_{0}_{1}", nextChildCount, (typeof(T_PoolOf)).ToString()); _itemCount++; nextChildCount++; item.gameObject.SetActive(true); if (OnObjectCreatedEvent != null) { OnObjectCreatedEvent(item); } } } public void RemoveAll() { if (_objectPool != null) { int destroyItemsCount = _objectPool.Count; for (int i = _objectPool.Count - 1; i >= 0; i--) { RemoveItem(i, ref destroyItemsCount); } } } public void RemoveItem(int index, ref int nextChildCount) { if(_objectPool == null) { return; } if(index >= _objectPool.Count || _objectPool[index] == null) { return; } if(_objectPool[index].isActiveAndEnabled) { T_PoolOf item = _objectPool[index]; item.gameObject.SetActive(false); _itemCount--; nextChildCount--; } } public void DestroyAll() { if(_objectPool != null) { int destroyItemsCount = _objectPool.Count; for (int i = _objectPool.Count - 1; i >= 0; i--) { DestroyItem(i, ref destroyItemsCount); } } } public void DestroyItem(int index, ref int nextChildCount) { if (_objectPool == null) { return; } if (index >= _objectPool.Count) { return; } if (_objectPool[index] != null) { T_PoolOf item = _objectPool[index]; _objectPool.RemoveAt(index); item.gameObject.SetActive(false); UnityEngine.Object.Destroy(item); } else { _objectPool.RemoveAt(index); } _itemCount--; nextChildCount--; } }
using System; using System.Collections.Generic; using System.Text; namespace eventizr.Controls { public class AdControlView : Xamarin.Forms.View { } }
using System; namespace BenchmarkDotNet.Toolchains.CoreRt { [Obsolete("Please use NativeAotToolchainBuilder instead.", true)] public class CoreRtToolchainBuilder { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using System.Net; using System.Text; using System.Net.Sockets; using System.Threading; public class ClientManager : MonoBehaviour { private static ClientManager instance; public static ClientManager Instance { get { if (instance == null) { instance = FindObjectOfType<ClientManager>(); } return instance; } } public int port = 20084; public string serverIP = "192.168.1.112"; private Socket udpclient; private IPAddress iP; private EndPoint ep; private byte[] data = new byte[2048]; private int length = 0; private string message; private string allMessage; // public string inputMessage; // public string outMessage; private void Start() { StartClient(); } public void StartClient() { udpclient = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); iP = IPAddress.Parse(serverIP); ep = new IPEndPoint(iP,port); } public bool SendMessageToServer(Vector3 pos) { float[] posArr = new float[] { pos.x, pos.y, pos.z}; message = string.Join( "|",posArr); Debug.Log(message); data = Encoding.UTF8.GetBytes(message); udpclient.SendTo(data,ep); return true; } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Toggl.Shared { public struct Option<T> : IEquatable<Option<T>> { private readonly T value; private readonly bool hasValue; private Option(T value) { hasValue = true; this.value = value; } public static Option<T> None => default; internal static Option<T> Some(T value) => new Option<T>(value); public Option<TOut> Select<TOut>(Func<T, TOut> selector) => hasValue ? Option.Some(selector(value)) : Option<TOut>.None; public Option<TOut> SelectMany<TOut>(Func<T, Option<TOut>> selector) => hasValue ? selector(value) : Option<TOut>.None; public Option<T> Where(Func<T, bool> predicate) => hasValue && predicate(value) ? this : None; public void Match(Action<T> onSome) { if (hasValue) onSome(value); } public void Match(Action<T> onSome, Action onNone) { if (hasValue) { onSome(value); } else { onNone(); } } public TResult Match<TResult>(Func<T, TResult> onSome, Func<TResult> onNone) => hasValue ? onSome(value) : onNone(); public bool Equals(Option<T> other) => hasValue == other.hasValue && EqualityComparer<T>.Default.Equals(value, other.value); public override bool Equals(object obj) => obj is Option<T> other && Equals(other); public override int GetHashCode() => hasValue ? EqualityComparer<T>.Default.GetHashCode(value) : 0; public override string ToString() => hasValue ? $"Some {value}" : "None"; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Option<T>(NothingOption _) => None; } public static class Option { public static Option<T> FromNullable<T>(T value) where T : class => value == null ? None : Option<T>.Some(value); public static Option<T> FromNullable<T>(T? value) where T : struct => value.HasValue ? Option<T>.Some(value.Value) : None; public static Option<T> Some<T>(T value) => Option<T>.Some(value); public static NothingOption None => default; } public struct NothingOption { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item : MonoBehaviour { public int index; public int label; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void Click() { print("Clicked! " + index); GameObject.FindGameObjectWithTag("LadderManager").GetComponent<Level1Manager>().itemIndex = index; GameObject.FindGameObjectWithTag("LadderManager").GetComponent<Level1Manager>().itemChoose = label; GameObject.FindGameObjectWithTag("UI").GetComponent<UIManager>().ShowHint(2); } }
/* * Copyright © 2008, Textfyre, Inc. - All Rights Reserved * Please read the accompanying COPYRIGHT file for licensing resstrictions. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace FyreVM { /// <summary> /// Represents the ROM and RAM of a Glulx game image. /// </summary> internal class UlxImage { private byte[] memory; private uint ramstart; private Stream originalStream; private byte[] originalRam, originalHeader; /// <summary> /// Initializes a new instance from the specified stream. /// </summary> /// <param name="stream">A stream containing the Glulx image.</param> public UlxImage(Stream stream) { originalStream = stream; LoadFromStream(stream); } private void LoadFromStream(Stream stream) { if (stream.Length > int.MaxValue) throw new ArgumentException(".ulx file is too big"); if (stream.Length < Engine.GLULX_HDR_SIZE) throw new ArgumentException(".ulx file is too small"); // read just the header, to find out how much memory we need memory = new byte[Engine.GLULX_HDR_SIZE]; stream.Seek(0, SeekOrigin.Begin); stream.Read(memory, 0, Engine.GLULX_HDR_SIZE); if (memory[0] != (byte)'G' || memory[1] != (byte)'l' || memory[2] != (byte)'u' || memory[3] != (byte)'l') throw new ArgumentException(".ulx file has wrong magic number"); uint endmem = ReadInt32(Engine.GLULX_HDR_ENDMEM_OFFSET); // now read the whole thing memory = new byte[endmem]; stream.Seek(0, SeekOrigin.Begin); stream.Read(memory, 0, (int)stream.Length); // verify checksum uint checksum = CalculateChecksum(); if (checksum != ReadInt32(Engine.GLULX_HDR_CHECKSUM_OFFSET)) throw new ArgumentException(".ulx file has incorrect checksum"); ramstart = ReadInt32(Engine.GLULX_HDR_RAMSTART_OFFSET); } /// <summary> /// Gets the address at which RAM begins. /// </summary> /// <remarks> /// The region of memory below RamStart is considered ROM. Addresses /// below RamStart are readable but unwritable. /// </remarks> public uint RamStart { get { return ramstart; } } /// <summary> /// Gets or sets the address at which memory ends. /// </summary> /// <remarks> /// This can be changed by the game with @setmemsize (or managed /// automatically by the heap allocator). Addresses above EndMem are /// neither readable nor writable. /// </remarks> public uint EndMem { get { return (uint)memory.Length; } set { // round up to the next multiple of 256 if (value % 256 != 0) value = (value + 255) & 0xFFFFFF00; if ((uint)memory.Length != value) { byte[] newMem = new byte[value]; Array.Copy(memory, newMem, (int)Math.Min((uint)memory.Length, (int)value)); memory = newMem; } } } /// <summary> /// Reads a single byte from memory. /// </summary> /// <param name="offset">The address to read from.</param> /// <returns>The byte at the specified address.</returns> public byte ReadByte(uint offset) { return memory[offset]; } /// <summary> /// Reads a big-endian word from memory. /// </summary> /// <param name="offset">The address to read from</param> /// <returns>The word at the specified address.</returns> public ushort ReadInt16(uint offset) { return BigEndian.ReadInt16(memory, offset); } /// <summary> /// Reads a big-endian double word from memory. /// </summary> /// <param name="offset">The address to read from.</param> /// <returns>The 32-bit value at the specified address.</returns> public uint ReadInt32(uint offset) { return BigEndian.ReadInt32(memory, offset); } /// <summary> /// Writes a single byte into memory. /// </summary> /// <param name="offset">The address to write to.</param> /// <param name="value">The value to write.</param> /// <exception cref="VMException">The address is below RamStart.</exception> public void WriteByte(uint offset, byte value) { if (offset < ramstart) throw new VMException("Writing into ROM"); memory[offset] = value; } /// <summary> /// Writes a big-endian 16-bit word into memory. /// </summary> /// <param name="offset">The address to write to.</param> /// <param name="value">The value to write.</param> /// <exception cref="VMException">The address is below RamStart.</exception> public void WriteInt16(uint offset, ushort value) { if (offset < ramstart) throw new VMException("Writing into ROM"); BigEndian.WriteInt16(memory, offset, value); } /// <summary> /// Writes a big-endian 32-bit word into memory. /// </summary> /// <param name="offset">The address to write to.</param> /// <param name="value">The value to write.</param> /// <exception cref="VMException">The address is below RamStart.</exception> public void WriteInt32(uint offset, uint value) { if (offset < ramstart) throw new VMException("Writing into ROM"); BigEndian.WriteInt32(memory, offset, value); } /// <summary> /// Calculates the checksum of the image. /// </summary> /// <returns>The sum of the entire image, taken as an array of /// 32-bit words.</returns> public uint CalculateChecksum() { uint end = ReadInt32(Engine.GLULX_HDR_EXTSTART_OFFSET); // negative checksum here cancels out the one we'll add inside the loop uint sum = (uint)(-ReadInt32(Engine.GLULX_HDR_CHECKSUM_OFFSET)); System.Diagnostics.Debug.Assert(end % 4 == 0); // Glulx spec 1.2 says ENDMEM % 256 == 0 for (uint i = 0; i < end; i += 4) sum += ReadInt32(i); return sum; } /// <summary> /// Gets the entire contents of memory. /// </summary> /// <returns>An array containing all VM memory, ROM and RAM.</returns> public byte[] GetMemory() { return memory; } /// <summary> /// Sets the entire contents of RAM, changing the size if necessary. /// </summary> /// <param name="newBlock">The new contents of RAM.</param> /// <param name="embeddedLength">If true, indicates that <paramref name="newBlock"/> /// is prefixed with a 32-bit word giving the new size of RAM, which may be /// more than the number of bytes actually contained in the rest of the array.</param> public void SetRAM(byte[] newBlock, bool embeddedLength) { uint length; int offset; if (embeddedLength) { offset = 4; length = (uint)((newBlock[0] << 24) + (newBlock[1] << 16) + (newBlock[2] << 8) + newBlock[3]); } else { offset = 0; length = (uint)newBlock.Length; } EndMem = ramstart + length; Array.Copy(newBlock, offset, memory, (int)ramstart, newBlock.Length - offset); } /// <summary> /// Obtains the initial contents of RAM from the game file. /// </summary> /// <returns>The initial contents of RAM.</returns> public byte[] GetOriginalRAM() { if (originalRam == null) { int length = (int)(ReadInt32(Engine.GLULX_HDR_ENDMEM_OFFSET) - ramstart); originalRam = new byte[length]; originalStream.Seek(ramstart, SeekOrigin.Begin); originalStream.Read(originalRam, 0, length); } return originalRam; } /// <summary> /// Obtains the header from the game file. /// </summary> /// <returns>The first 128 bytes of the game file.</returns> public byte[] GetOriginalIFHD() { if (originalHeader == null) { originalHeader = new byte[128]; originalStream.Seek(0, SeekOrigin.Begin); originalStream.Read(originalHeader, 0, 128); } return originalHeader; } /// <summary> /// Copies a block of data out of RAM. /// </summary> /// <param name="address">The address, based at <see cref="RamStart"/>, /// at which to start copying.</param> /// <param name="length">The number of bytes to copy.</param> /// <param name="dest">The destination array.</param> public void ReadRAM(uint address, uint length, byte[] dest) { Array.Copy(memory, (int)(ramstart + address), dest, 0, (int)length); } /// <summary> /// Copies a block of data into RAM, expanding the memory map if needed. /// </summary> /// <param name="address">The address, based at <see cref="RamStart"/>, /// at which to start copying.</param> /// <param name="src">The source array.</param> public void WriteRAM(uint address, byte[] src) { EndMem = Math.Max(EndMem, ramstart + (uint)src.Length); Array.Copy(src, 0, memory, (int)(ramstart + address), src.Length); } /// <summary> /// Reloads the game file, discarding all changes that have been made /// to RAM and restoring the memory map to its original size. /// </summary> public void Revert() { LoadFromStream(originalStream); } } }
using Assignment4.Core; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Query; using System.Data; using System; using System.Linq; namespace Assignment4.Entities { public class TaskRepository : ITaskRepository { private readonly IKanbanContext _context; public TaskRepository(IKanbanContext context) { _context = context; } public (Response, IReadOnlyCollection<TaskDTO>) All() { var tasks = from t in GetSource() select TaskToTaskDTO(t); return (Response.Success, tasks.ToList()); } public (Response, IReadOnlyCollection<TaskDTO>) AllRemoved() { var tasks = from t in GetSource() where t.State == State.Removed select TaskToTaskDTO(t); return (Response.Success, tasks.ToList()); } public (Response, IReadOnlyCollection<TaskDTO>) AllByTag(string tag) { var tasks = from t in GetSource() where t.Tags.Where(t => t.Name == tag).Any() select TaskToTaskDTO(t); return (Response.Success, tasks.ToList()); } public (Response, IReadOnlyCollection<TaskDTO>) AllByUser(int userId) { var tasks = from t in GetSource() where t.AssignedTo.Id == userId select TaskToTaskDTO(t); return (Response.Success, tasks.ToList()); } public (Response, IReadOnlyCollection<TaskDTO>) AllByState(State state) { var tasks = from t in GetSource() where t.State == state select TaskToTaskDTO(t); return (Response.Success, tasks.ToList()); } public (Response, TaskDTO) Create(TaskCreateDTO task) { var user = GetUser(task.AssignedToId); if (user == null && task.AssignedToId != null) { return (Response.BadRequest, null); } var tags = GetTags(task.Tags); var created = new Task { Title = task.Title, Description = task.Description, AssignedTo = user, Tags = tags.ToList(), State = State.New, Created = DateTime.UtcNow, StateUpdated = DateTime.UtcNow }; _context.Tasks.Add(created); _context.SaveChanges(); return (Response.Created, TaskToTaskDTO(created)); } public Response Delete(int taskId) { var entity = _context.Tasks.Find(taskId); if (entity == null) { return Response.NotFound; } switch (entity.State) { case State.New: _context.Tasks.Remove(entity); break; case State.Active: entity.State = State.Removed; break; case State.Resolved: case State.Closed: case State.Removed: default: return Response.Conflict; } _context.SaveChanges(); return Response.Deleted; } public (Response, TaskDetailsDTO) FindById(int id) { var tasks = from t in (_context .Tasks .Include(t => t.Tags) .Include(t => t.AssignedTo) ) where t.Id == id select new TaskDetailsDTO( t.Id, t.Title, t.Description, t.Created, t.AssignedTo == null ? "" : t.AssignedTo.Name, t.Tags.Select(tag => tag.Name).ToList(), t.State, t.StateUpdated ); var entity = tasks.FirstOrDefault(); if (entity == null) { return (Response.NotFound, null); } return (Response.Success, tasks.FirstOrDefault()); } public Response Update(TaskUpdateDTO task) { var entity = _context.Tasks.Find(task.Id); if (entity == null) { return Response.NotFound; } if (task.Tags != null) { entity.Tags = GetTags(task.Tags).ToList(); } var assignedTo = GetUser(task.AssignedToId); if (assignedTo == null && task.AssignedToId != null) { return Response.BadRequest; } entity.AssignedTo = assignedTo; entity.Title = task.Title; entity.Description = task.Description; if (task.State != entity.State) { entity.State = task.State; entity.StateUpdated = DateTime.UtcNow; } _context.SaveChanges(); return Response.Updated; } private IIncludableQueryable<Task, User> GetSource() { return _context .Tasks .Include(t => t.Tags) .Include(t => t.AssignedTo); } private User GetUser(int? userId) { if (userId == null) { return null; } return _context.Users.Find(userId); } private IEnumerable<Tag> GetTags(IEnumerable<string> tags) { // FIXME: There is no guarantee that all the tags specified are actually here var entities = _context.Tags.Where(t => tags.Contains(t.Name)).ToDictionary(t => t.Name); foreach (var tag in tags) { yield return entities.TryGetValue(tag, out var t) ? t : new Tag { Name = tag }; } } private static TaskDTO TaskToTaskDTO(Task task) { return new TaskDTO( task.Id, task.Title, task.AssignedTo == null ? "" : task.AssignedTo.Name, task.Tags.Select(t => t.Name).ToList(), task.State ); } public void Dispose() { _context.Dispose(); } } }
using Hangfire; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Workers { public partial class Worker { #region Instance Methods // The following job won't be retried if it fails // It will be logged // and marked as a failure (you can set it to delete) [AutomaticRetry(Attempts = 0, LogEvents = true, OnAttemptsExceeded = AttemptsExceededAction.Fail)] public void RecurringMinutely() { RecurringJob.AddOrUpdate(() => Console.WriteLine("Minute Job" + Guid.NewGuid().ToString()), Cron.Minutely); } public void FireAndForget(int count) { Parallel.For(0, count, i => { Console.WriteLine("Fire-and-forget " + i.ToString()); }); } public void FirstContinuation() { Console.WriteLine("Hello, "); Thread.Sleep(1000 * 30); } public void SecondContinuation() { Console.WriteLine("world!"); } public void AllMyContinuations(WorkerDelegate[] actions) { if (actions.Length.Equals(0)) throw new Exception("I can't do this with nothing"); var id = BackgroundJob.Enqueue(() => actions[0]()); for (var i = 1; i < actions.Length; i++) { id = BackgroundJob.ContinueWith(id, () => actions[i]()); } } public void RandomTask(int seconds)//, bool shouldIFail) { attempts++; if (attempts < 10) { Thread.Sleep(1000 * seconds); //if (shouldIFail) throw new Exception("I failed for some reason"); } } public void LongRunningMethod(IJobCancellationToken jobCancellationToken) { for (var i = 0; i < Int32.MaxValue; i++) { jobCancellationToken.ThrowIfCancellationRequested(); Thread.Sleep(TimeSpan.FromSeconds(1)); } } #endregion } }
using UnityEngine; [CreateAssetMenu] public class ScoreRewards : ScriptableObject { //Score gained for destroying an Asteroid [SerializeField] int scoreDestroyedAsteroid = 10; public int ScoreDestroyedAsteroid => scoreDestroyedAsteroid; //Score gained for near misses. [SerializeField] int scoreDodgedAsteroid = 20; public int ScoreDodgedAsteroid => scoreDodgedAsteroid; }
using System.Text; using KDLib; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace KDCryptoUtils.Encrypter { public class JsonEncrypter : BaseEncrypter<object> { public JsonEncrypter(string key, int iterations = 10000, byte[] salt = null) : base(key, iterations, salt) { } public JsonEncrypter(byte[] key, int iterations = 10000, byte[] salt = null) : base(key, iterations, salt) { } protected override byte[] ConvertToBytes(object value) { var jsonObject = JToken.FromObject(value); var jsonString = JsonConvert.SerializeObject(jsonObject); return Encoding.UTF8.GetBytes(jsonString); } protected override object ConvertFromBytes(byte[] data) { return JToken.Parse(Encoding.UTF8.GetString(data)); } public T Decrypt<T>(byte[] data) { var rawValue = (JToken)Decrypt(data); return rawValue.ToObject<T>(); } public T DecryptFromString<T>(string data, BinaryEncoding encoding = BinaryEncoding.Base64) { var rawValue = (JToken)DecryptFromString(data, encoding); return rawValue.ToObject<T>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Behavior_Control_Advanced_Twitter { internal class ControlCommands { public readonly static string GET_LATEST_MENTION = "GetLatestMention"; public readonly static string GET_LATEST_TWEET = "GetLatestTweet"; } }
// Decompiled with JetBrains decompiler // Type: SimpleCamera.CameraOrigin // Assembly: SimpleCamera, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null namespace SimpleCamera { internal enum CameraOrigin { Target, Eye, } }
using TMPro; using UnityEngine; using UnityEngine.SceneManagement; public class HUD_Manager : MonoBehaviour { public static HUD_Manager instance; private LevelManager _lm; private int langIndex; [Header("HUD Elements")] [SerializeField] private GameObject HUD_Canvas = null; [SerializeField] private TextMeshProUGUI TimeRemaining = null; [SerializeField] private TextMeshProUGUI TotalScore = null; [SerializeField] private TextMeshProUGUI Multiplier = null; [Header("Multilanguage Objects")] [SerializeField] private MultilanguageSO ML_TimeRemaning = null; [SerializeField] private MultilanguageSO ML_TotalScore = null; [SerializeField] private MultilanguageSO ML_Multiplier = null; //Static instance check private void Awake() { if (instance == null) instance = this; else Destroy(this); } //Display Inital Values private void Start() { _lm = LevelManager.instance; langIndex = GameManager.instance.languageIndex; UpdateMultiplier(1); UpdateScore(0); } /// <summary> /// Update time display with given seconds converted to TimeSpan /// </summary> /// <param name="timeRemaining"></param> public void UpdateTime(ref float timeRemaining) { var span = new System.TimeSpan(0, 0, (int)timeRemaining); TimeRemaining.text = string.Format("{0}: {1}", ML_TimeRemaning.GetText(langIndex), span); } /// <summary> /// Update score with total score plus value /// </summary> /// <param name="value"></param> public void UpdateScore(int totalScore) { TotalScore.text = string.Format("{0}: {1}", ML_TotalScore.GetText(langIndex), totalScore); } /// <summary> /// Update multiplier with value /// </summary> /// <param name="value"></param> public void UpdateMultiplier(int value) { Multiplier.text = string.Format("{0} (x{1})", ML_Multiplier.GetText(langIndex), value); } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using RTLib.Util; namespace RTLib.Material.Texture { public class RawTexture : ITexture { public int Width { get; set; } public int Height { get; set; } public RenderColor[,] Texture { get; set; } public bool BilinearFilter { get; set; } public RenderColor GetTexel(double u, double v) { if (BilinearFilter) { throw new NotImplementedException("Bilinear filtering is not currently supported."); } else { double x = u * Width; double y = v * Height; int tx = (int)MathHelper.Clamp(x, 0, Width - 1); int ty = (int)MathHelper.Clamp(y, 0, Height - 1); return Texture[tx, ty]; } } } }
using FS.DBAccess; using FS.I18N; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FS.DbModelTool { public partial class FormMain : Form { #region Vars private string currentDbName = null; #endregion #region Init public FormMain() { InitializeComponent(); this.Load += FormLoaded; } private void FormLoaded(object sender, EventArgs e) { cbAllTables.CheckedChanged += CbAllTables_CheckedChanged; this.btnGenFiles.Click += async (s, o) => await BeginToGenFiles(); //InitUIMessage(); InitSettings(); InitDbNames(); lbConStringName.DoubleClick += (s, o) => SelectDbName(); btnSettingNext.Click += (s, o) => tabControl1.SelectedIndex = 1; btnDbNext.Click += (s, o) => tabControl1.SelectedIndex = 2; btnTableNext.Click += (s, o) => tabControl1.SelectedIndex = 3; btnDbReload.Click += async (s, o) => { btnDbReload.Enabled = false; await ReloadTables(currentDbName); btnDbReload.Enabled = true; }; } #endregion #region Page-Config private List<LanguageSimpleInfo> langs = null; private async void InitSettings() { langs = await Task.Run(() => LangHelper.GetAllSupportLanguages()); cbLanguage.Items.Clear(); cbLanguage.DataSource = langs; cbLanguage.DisplayMember = "Name"; cbLanguage.SelectedIndexChanged += CbLanguage_SelectedIndexChanged; var clang = langs.FirstOrDefault(x => x.Code == LangHelper.CurrentLanguage.Code); if (clang != null) { cbLanguage.SelectedIndex = langs.IndexOf(clang); } else { if (langs.Exists(x => x.Name == "English")) { cbLanguage.SelectedIndex = langs.IndexOf(langs.Find(x => x.Name == "English")); } else cbLanguage.SelectedIndex = 0; } var selTemp = Properties.Settings.Default.ModelTemlpateName; cbTemplateName.Items.Clear(); cbTemplateName.Items.Add("Default"); var temps = MainManager.GetTemplates(); foreach (var item in temps) { cbTemplateName.Items.Add(item); } cbTemplateName.SelectedIndex = 0; if (!string.IsNullOrEmpty(selTemp) && selTemp.ToLower() != "default") { var it = temps.FirstOrDefault(x => x == selTemp); if (it != null) cbTemplateName.SelectedIndex = temps.IndexOf(it) + 1; } } #endregion #region UI-Language private void CbLanguage_SelectedIndexChanged(object sender, EventArgs e) { var cb = sender as ComboBox; var lang = cb.SelectedItem as LanguageSimpleInfo; if (lang == null) return; string langCode = lang.Code; LangHelper.LoadLanguage(langCode); LangHelper.SetUICulture(langCode); ChangeLanguage(); } /// <summary> /// 切换语言 /// </summary> private void ChangeLanguage() { var msg = string.Empty; foreach (Control ctrl in GetSelfAndChildrenRecursive(this)) { if (ctrl.Tag == null) continue; msg = GetResByTag(ctrl.Tag); if (string.IsNullOrEmpty(msg)) continue; ctrl.Text = msg; } this.Text += " by Fallstar v" + this.ProductVersion; } /// <summary> /// 递归获得所有子控件 /// </summary> /// <param name="parent"></param> /// <returns></returns> private IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent) { List<Control> controls = new List<Control>(); foreach (Control child in parent.Controls) { controls.AddRange(GetSelfAndChildrenRecursive(child)); } controls.Add(parent); return controls; } /// <summary> /// 通过分析Tag来判断获取资源 /// </summary> /// <param name="tag"></param> /// <returns></returns> private string GetResByTag(object tag) { var t = tag.ToString().Trim(); if (string.IsNullOrEmpty(t)) return null; if (t.StartsWith("ResID:")) { t = t.Replace("ResID:", string.Empty); uint id = 0; if (uint.TryParse(t, out id)) return GetRes(id); return null; } if (t.StartsWith("ResKey:")) { t = t.Replace("ResKey:", string.Empty); return GetRes(t); } return null; } /// <summary> /// 获取资源 /// </summary> /// <param name="id"></param> /// <param name="defaultValue"></param> /// <param name="pars"></param> /// <returns></returns> private string GetRes(uint id, string defaultValue = null, params object[] pars) { return LangHelper.GetRes(id, defaultValue, pars); } /// <summary> /// 获取资源 /// </summary> /// <param name="id"></param> /// <param name="defaultValue"></param> /// <param name="pars"></param> /// <returns></returns> private string GetRes(LangMsgKeys id, string defaultValue = null, params object[] pars) { return LangHelper.GetRes(id, defaultValue, pars); } /// <summary> /// 获取资源 /// </summary> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <param name="pars"></param> /// <returns></returns> private string GetRes(string key, string defaultValue = null, params object[] pars) { return LangHelper.GetRes(key, defaultValue, pars); } #endregion #region Page-DbNames private void InitDbNames() { var dbNames = MainManager.GetDbConnectionNames(); lbConStringName.Items.Clear(); foreach (var item in dbNames) { lbConStringName.Items.Add(item); } if (dbNames.Count > 0) lbConStringName.SelectedIndex = 0; } private async void SelectDbName() { if (lbConStringName.SelectedIndex == -1) { return; } var dbName = lbConStringName.SelectedItem.ToString(); if (dbName == currentDbName) return; currentDbName = dbName; var ret = MainManager.Logic.SetDbConnection(dbName); if (!ret.IsSuccess) { MessageBox.Show(ret.ReplyMsg); return; } await ReloadTables(dbName); tabControl1.SelectedIndex = 2; } #endregion #region Page-Table private List<DbTableInfo> tableInfos = null; private void CbAllTables_CheckedChanged(object sender, EventArgs e) { var isCheck = cbAllTables.Checked; for (int i = 0; i < cblbTables.Items.Count; i++) { cblbTables.SetItemChecked(i, isCheck); } } /// <summary> /// 读取所有表的信息 /// </summary> /// <param name="dbName"></param> private async Task ReloadTables(string dbName) { if (string.IsNullOrEmpty(dbName)) { MessageBox.Show(GetRes(1514)); return; } btnDbNext.Enabled = false; var result = await Task.Run(() => MainManager.GetTableNames(dbName)); btnDbNext.Enabled = true; if (!result.IsSuccess) { MessageBox.Show(result.ReplyMsg); return; } if (result.Result == null || result.Result.Count == 0) return; tableInfos = result.Result; cblbTables.Items.Clear(); foreach (var item in result.Result) { cblbTables.Items.Add(item.TableName); } } #endregion #region Page-Result private async Task BeginToGenFiles() { var nameSpace = txtNameSpace.Text.Trim(); var fileDir = txtGenPath.Text.Trim(); if (string.IsNullOrEmpty(nameSpace)) nameSpace = "Model"; if (string.IsNullOrEmpty(fileDir)) fileDir = "Models\\"; var temp = cbTemplateName.SelectedItem.ToString(); Properties.Settings.Default.ModelNameSpace = nameSpace; Properties.Settings.Default.ModelGeneratePath = fileDir; Properties.Settings.Default.ModelTemlpateName = temp; Properties.Settings.Default.Save(); txtResultLog.Clear(); AddResultLog(LangHelper.GetRes(1502)); if (tableInfos == null) { AddResultLog(LangHelper.GetRes(1503)); return; } var selTables = new List<DbTableInfo>(); foreach (var item in cblbTables.CheckedItems) { var t = item.ToString(); var it = tableInfos.FirstOrDefault(x => x.TableName == t); if (it == null) continue; selTables.Add(it); } AddResultLog(LangHelper.GetRes(1504, "Tables need to proccess :") + selTables.Count); var mo = new GenFileModel() { FilePath = fileDir, NameSpace = nameSpace, Tables = selTables, TemplateName = temp, }; btnGenFiles.Enabled = false; await Task.Run(() => MainManager.GenFiles(mo, AddResultLog)); btnGenFiles.Enabled = true; } /// <summary> /// 输出结果日志 /// </summary> /// <param name="msg"></param> private void AddResultLog(string msg) { Action act = () => txtResultLog.AppendText(msg + Environment.NewLine); if (txtResultLog.InvokeRequired) txtResultLog.Invoke(act); else act(); } #endregion } }
using Battles.Cdn.FileServices; using Microsoft.AspNetCore.Mvc; namespace Battles.Cdn.Controllers { public class ContentController : Controller { private readonly FileStreams _fileStreams; public ContentController(FileStreams fileStreams) { _fileStreams = fileStreams; } [HttpGet("static/{fileName}")] [ResponseCache(CacheProfileName = "Monthly6")] public FileStreamResult GetStaticImage(string fileName) => new FileStreamResult(_fileStreams.StaticImageStream(fileName), "image/png"); [HttpGet("image/img/{id}/{fileName}")] [ResponseCache(CacheProfileName = "Monthly6")] public FileStreamResult GetUserImage(string id, string fileName) => new FileStreamResult(_fileStreams.UserImageStream(id, fileName), "image/jpg"); [HttpGet("image/thumb/{id}/{fileName}")] [ResponseCache(CacheProfileName = "Monthly6")] public FileStreamResult GetVideoThumbnail(string id, string fileName) => new FileStreamResult(_fileStreams.ThumbImageStream(id, fileName), "image/jpg"); [HttpGet("video/{id}/{fileName}")] [ResponseCache(CacheProfileName = "Monthly6")] public FileStreamResult GetVideo(string id, string fileName) => new FileStreamResult(_fileStreams.VideoStream(id, fileName), "video/mp4") { EnableRangeProcessing = true }; } }
using System.Data; using Xunit; namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public static class SqlCommandCompletedTest { private static readonly string s_connStr = (new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString) { PacketSize = 512 }).ConnectionString; private static int completedHandlerExecuted = 0; [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void VerifyStatmentCompletedCalled() { string tableName = DataTestUtility.GetUniqueNameForSqlServer("stmt"); using (var conn = new SqlConnection(s_connStr)) using (var cmd = conn.CreateCommand()) { try { cmd.StatementCompleted += StatementCompletedHandler; conn.Open(); cmd.CommandText = $"CREATE TABLE {tableName} (c1 int)"; var res = cmd.ExecuteScalar(); cmd.CommandText = $"INSERT {tableName} VALUES(1)"; //DML (+1) res = cmd.ExecuteScalar(); cmd.CommandText = $"Update {tableName} set c1=2"; //DML (+1) res = cmd.ExecuteScalar(); cmd.CommandText = $"SELECT * from {tableName}"; //DQL (+1) res = cmd.ExecuteScalar(); cmd.CommandText = $"DELETE FROM {tableName}"; //DML (+1) res = cmd.ExecuteScalar(); } finally { cmd.CommandText = $"DROP TABLE {tableName}"; var res = cmd.ExecuteScalar(); } } // DDL and DQL queries that return DoneRowCount are accounted here. Assert.True(completedHandlerExecuted == 4); } private static void StatementCompletedHandler(object sender, StatementCompletedEventArgs args) { // Increment on event pass through completedHandlerExecuted++; } } }
using System.Collections.Generic; using Microsoft.CodeAnalysis; using Tbc.Host.Services.Patch.Models; namespace Tbc.Host.Services.Patch { public class DisambiguationRewriterConfig { public SemanticModel Model { get; set; } public List<CSharpReloadableInput> Inputs { get; set; } public List<string> Usings { get; set; } public List<DependencyNode> DependencyNodes { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using ReflectionMagic; namespace Kledex.Domain { public abstract class AggregateRoot : IAggregateRoot { public Guid Id { get; protected set; } public int Version { get; private set; } private readonly List<IDomainEvent> _events = new List<IDomainEvent>(); public ReadOnlyCollection<IDomainEvent> Events => _events.AsReadOnly(); protected AggregateRoot() { Id = Guid.NewGuid(); } protected AggregateRoot(Guid id) { if (id == Guid.Empty) id = Guid.NewGuid(); Id = id; } public void LoadsFromHistory(IEnumerable<IDomainEvent> events) { var domainEvents = events as IDomainEvent[] ?? events.ToArray(); foreach (var @event in domainEvents) this.AsDynamic().Apply(@event); Version = domainEvents.Length; } /// <summary> /// Adds the event to the new events collection. /// </summary> /// <param name="event">The event.</param> protected void AddEvent(IDomainEvent @event) { _events.Add(@event); } /// <summary> /// Adds the event to the new events collection and calls the related apply method. /// </summary> /// <param name="event">The event.</param> protected void AddAndApplyEvent(IDomainEvent @event) { _events.Add(@event); this.AsDynamic().Apply(@event); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Microsoft.Identity.Client.Kerberos { /// <summary> /// The Kerberos key types used in this assembly. /// </summary> public enum KerberosKeyTypes { /// <summary> /// None. /// </summary> None = 0, /// <summary> /// dec-cbc-crc ([RFC3961] section 6.2.3) /// </summary> DecCbcCrc = 1, /// <summary> /// des-cbc-md5 ([RFC3961] section 6.2.1) /// </summary> DesCbcMd5 = 3, /// <summary> /// aes128-cts-hmac-sha1-96 ([RFC3962] section 6) /// </summary> Aes128CtsHmacSha196 = 17, /// <summary> /// aes256-cts-hmac-sha1-96 ([RFC3962] section 6) /// </summary> Aes256CtsHmacSha196 = 18, } }
// This code is part of the Fungus library (https://github.com/snozbot/fungus) // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEditor; using UnityEngine; using System.IO; namespace Fungus.EditorUtils { [CustomEditor(typeof(Localization))] public class LocalizationEditor : Editor { protected SerializedProperty activeLanguageProp; protected SerializedProperty localizationFileProp; protected virtual void OnEnable() { activeLanguageProp = serializedObject.FindProperty("activeLanguage"); localizationFileProp = serializedObject.FindProperty("localizationFile"); } public override void OnInspectorGUI() { serializedObject.Update(); Localization localization = target as Localization; EditorGUILayout.PropertyField(activeLanguageProp); EditorGUILayout.PropertyField(localizationFileProp); GUILayout.Space(10); EditorGUILayout.HelpBox("Exports a localization csv file to disk. You should save this file in your project assets and then set the Localization File property above to use it.", MessageType.Info); if (GUILayout.Button(new GUIContent("Export Localization File"))) { ExportLocalizationFile(localization); } GUILayout.Space(10); EditorGUILayout.HelpBox("Exports all standard text in the scene to a text file for easy editing in a text editor. Use the Import option to read the standard text back into the scene.", MessageType.Info); if (GUILayout.Button(new GUIContent("Export Standard Text"))) { ExportStandardText(localization); } if (GUILayout.Button(new GUIContent("Import Standard Text"))) { ImportStandardText(localization); } serializedObject.ApplyModifiedProperties(); } public virtual void ExportLocalizationFile(Localization localization) { string path = EditorUtility.SaveFilePanelInProject("Export Localization File", "localization.csv", "csv", "Please enter a filename to save the localization file to"); if (path.Length == 0) { return; } string csvData = localization.GetCSVData(); File.WriteAllText(path, csvData); AssetDatabase.ImportAsset(path); TextAsset textAsset = AssetDatabase.LoadAssetAtPath(path, typeof(TextAsset)) as TextAsset; if (textAsset != null) { localization.LocalizationFile = textAsset; } ShowNotification(localization); } public virtual void ExportStandardText(Localization localization) { string path = EditorUtility.SaveFilePanel("Export Standard Text", "Assets/", "standard.txt", ""); if (path.Length == 0) { return; } localization.ClearLocalizeableCache(); string textData = localization.GetStandardText(); File.WriteAllText(path, textData); AssetDatabase.Refresh(); ShowNotification(localization); } public virtual void ImportStandardText(Localization localization) { string path = EditorUtility.OpenFilePanel("Import Standard Text", "Assets/", "txt"); if (path.Length == 0) { return; } localization.ClearLocalizeableCache(); string textData = File.ReadAllText(path); localization.SetStandardText(textData); ShowNotification(localization); } protected virtual void ShowNotification(Localization localization) { FlowchartWindow.ShowNotification(localization.NotificationText); localization.NotificationText = ""; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Hidening : MonoBehaviour { [Range(0.0f, 1.0f)] public float hiddenLevel; // from 0.0f to 1.0f [SerializeField] private float defaultHiddenLevel = 0.0f; public void SetHiddenLevel(float value) { hiddenLevel = value; } public float GetHiddenLevel() { return hiddenLevel; } public void SetDefaultHiddenLevel() { hiddenLevel = defaultHiddenLevel; } }
using System.Net; using System.Web.Http; using System.Web.Http.Results; using Thinktecture.Relay.Server.Http.Filters; using Thinktecture.Relay.Server.Repository; namespace Thinktecture.Relay.Server.Controller.ManagementWeb { [AllowAnonymous] [ManagementWebModuleBindingFilter] [NoCache] public class SetupController : ApiController { private readonly IUserRepository _userRepository; public SetupController(IUserRepository userRepository) { _userRepository = userRepository; } [HttpGet] public IHttpActionResult NeedsFirstTimeSetup() { return _userRepository.Any() ? Ok() : (IHttpActionResult)new StatusCodeResult(HttpStatusCode.TemporaryRedirect, Request); } } }
using UnityEngine; /// <summary> /// Manages the UI for the jump energy /// /// Author: Tanat Boozayaangool /// </summary> public class JumpEnergyUI : MonoBehaviour { #region Fields private Transform healthBarPivot; private Movement player; #endregion #region Init Logic // Use this for initialization void Start() { healthBarPivot = transform.GetChild(0).GetChild(0); } /// <summary> /// A function that acts as the 'constructor' of sorts /// </summary> /// <param name="combat"></param> public void Init(Movement combat) { player = combat; } #endregion #region Life Cycle // Update is called once per frame void Update() { //calculate percentage //float energyPercentage = player.CurrJumpEnergy / player.jumpEnergyMax; //if (energyPercentage < 0f) // energyPercentage = 0f; //else if (energyPercentage > 1f) // energyPercentage = 1f; ////set the scale //Vector3 scale = healthBarPivot.localScale; //scale.x = Mathf.Lerp(scale.x, energyPercentage, Time.deltaTime * 20f); //healthBarPivot.localScale = scale; } #endregion }
using UnityEngine; namespace Replays { public struct TransformState { public Vector3 Position; public Vector3 Rotation; public Vector3 Scale; } }
using System.Collections.Generic; using NUnit.Framework; using Shouldly; using VeelenSoft.Validation.ValidationMessages; using VeelenSoft.Validation.Validators; namespace VeelenSoft.Validation.Tests.Validators { [TestFixture] [TestOf(typeof(ValidationResult))] public class ValidationResultTests { [Test] public void IsValid_WithoutValidationMessages_ReturnsTrue() { var validationResult = new ValidationResult(new List<ValidationMessage>()); validationResult.IsValid.ShouldBeTrue(); } [Test] public void IsValid_WithValidationMessages_ReturnsFalse() { var validationResult = new ValidationResult(new List<ValidationMessage> { new ValidationMessage("error") }); validationResult.IsValid.ShouldBeFalse(); } } }
using UnityEngine; [CreateAssetMenu(fileName = "New State", menuName = "AbilityData/StandUp")] public class StandUp : StateData { public override void OnEnter(CharacterState characterState, Animator animator, AnimatorStateInfo stateInfo) { animator.SetBool(TransitionParameter.Sit.ToString(), false); } public override void UpdateAbility(CharacterState characterState, Animator animator, AnimatorStateInfo stateInfo) { } public override void OnExit(CharacterState characterState, Animator animator, AnimatorStateInfo stateInfo) { } }
 using System.Collections.Generic; namespace ApiUtil.DataClasses { public class TestFileInfo { public TestFileInfo() { } public string TestName { get; set; } public string Descrip { get; set; } public string TGID { get; set; } public List<string> MethodList { get; set; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using NUnit.Framework; using QuantConnect.Util; using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; namespace QuantConnect.Tests.Common.Util { [TestFixture] public class RateGateTests { [Test, Ignore("Running multiple tests at once causes this test to fail")] public void RateGate_200InstancesWaitOnAveragePlus150msMinus20ms() { var gates = new Dictionary<int, RateGate>(); for (var i = 300; i < 500; i++) { gates[i] = new RateGate(10, TimeSpan.FromMilliseconds(i)); } foreach (var kvp in gates) { var gate = kvp.Value; var timer = Stopwatch.StartNew(); for (var i = 0; i <= 10; i++) { gate.WaitToProceed(); } timer.Stop(); var elapsed = timer.Elapsed; var lowerBound = TimeSpan.FromMilliseconds(kvp.Key - 20); var upperBound = TimeSpan.FromMilliseconds(kvp.Key + 150); Assert.GreaterOrEqual(elapsed, lowerBound, $"RateGate was early: {lowerBound - elapsed}"); Assert.LessOrEqual(elapsed, upperBound, $"RateGate was late: {elapsed - upperBound}"); gate.Dispose(); } } [Test] public void RateGate_400InstancesWaitOnAveragePlus150msMinus20msWithTimeout() { var gates = new Dictionary<int, RateGate>(); for (var i = 100; i < 500; i++) { gates[i] = new RateGate(10, TimeSpan.FromMilliseconds(i)); } Parallel.ForEach(gates, kvp => { var gate = kvp.Value; var timer = Stopwatch.StartNew(); for (var i = 0; i <= 10; i++) { gate.WaitToProceed(kvp.Key); } timer.Stop(); var elapsed = timer.Elapsed; var lowerBound = TimeSpan.FromMilliseconds(kvp.Key - 20); var upperBound = TimeSpan.FromMilliseconds(kvp.Key + 150); Assert.GreaterOrEqual(elapsed, lowerBound, $"RateGate was early: {lowerBound - elapsed}"); Assert.LessOrEqual(elapsed, upperBound, $"RateGate was late: {elapsed - upperBound}"); gate.Dispose(); }); } [Test] public void RateGate_ShouldSkipBecauseOfTimeout() { var gate = new RateGate(1, TimeSpan.FromSeconds(20)); var timer = Stopwatch.StartNew(); Assert.IsTrue(gate.WaitToProceed(-1)); Assert.IsFalse(gate.WaitToProceed(0)); timer.Stop(); Assert.LessOrEqual(timer.Elapsed, TimeSpan.FromSeconds(10)); gate.Dispose(); } } }
//--------------------------------------------------------------------- // <copyright file="IPayloadTransformFactory.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.Test.Taupo.Astoria.Contracts.OData { using Microsoft.Test.Taupo.Common; /// <summary> /// Generates instances of IPayloadTransform. /// </summary> [ImplementationSelector("IPayloadTransformFactory", DefaultImplementation = "Default", HelpText = "Generates payload transform instances.")] public interface IPayloadTransformFactory { /// <summary> /// Gets all the payload transforms of the specified type. /// </summary> /// <typeparam name="TPayload">Payload element object type.</typeparam> /// <returns>A composite instance of all payload transforms.</returns> IPayloadTransform<TPayload> GetTransform<TPayload>(); /// <summary> /// Gets a scope that can be used to modify what transforms are returned by the factory in a way that does not corrupt the factory itself. /// </summary> /// <param name="empty">A value indicating whether the scope should start out empty. If false, the current set of default transformations will be used.</param> /// <returns>A scope which can be used to fluently add/remove transforms without modifying the factory's long-term state.</returns> IPayloadTransformationScope GetScope(bool empty); } }
using System; using System.ComponentModel.DataAnnotations.Schema; using LiteDB; namespace Gouter.DataModels; /// <summary> /// アートワーク情報のデータモデル /// </summary> [Table("album_artworks")] internal class AlbumArtworksDataModel { /// <summary> /// アルバムID /// </summary> [BsonId(false)] public int AlbumId { get; set; } /// <summary> /// アートワーク /// </summary> [BsonField("artwork")] public byte[] Artwork { get; set; } /// <summary> /// 作成日時 /// </summary> [BsonField("created_at")] public DateTimeOffset CreatedAt { get; set; } /// <summary> /// 更新日時 /// </summary> [BsonField("updated_at")] public DateTimeOffset UpdatedAt { get; set; } }
using System.Threading; using System.Threading.Tasks; using NHSD.BuyingCatalogue.Solutions.Application.Domain; using NHSD.BuyingCatalogue.Solutions.Contracts.Persistence; namespace NHSD.BuyingCatalogue.Solutions.Application.Persistence { internal sealed class SolutionIntegrationsUpdater { /// <summary> /// Data access layer for the <see cref="Solution"/> entity. /// </summary> private readonly ISolutionRepository solutionRepository; public SolutionIntegrationsUpdater(ISolutionRepository solutionRepository) => this.solutionRepository = solutionRepository; public async Task Update(string solutionId, string url, CancellationToken cancellationToken) => await solutionRepository.UpdateIntegrationsAsync( new UpdateIntegrationsRequest(solutionId, url), cancellationToken); } }
namespace SceneKitSessionWWDC2013 { public class SlideExtendingOutline : Slide { public override void SetupSlide (PresentationViewController presentationViewController) { TextManager.SetTitle ("Extending Scene Kit with OpenGL"); TextManager.AddBulletAtLevel ("Scene delegate rendering", 0); TextManager.AddBulletAtLevel ("Node delegate rendering", 0); TextManager.AddBulletAtLevel ("Material custom program", 0); TextManager.AddBulletAtLevel ("Shader modifiers", 0); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core; namespace Azure.AI.TextAnalytics.Models { #pragma warning disable SA1402 // File may only contain a single type [CodeGenModel("CustomEntitiesResultDocumentsItem")] internal partial class CustomEntitiesResultDocumentsItem { } [CodeGenModel("CustomMultiLabelClassificationResultDocumentsItem")] internal partial class CustomMultiLabelClassificationResultDocumentsItem { } [CodeGenModel("CustomSingleLabelClassificationResultDocumentsItem")] internal partial class CustomSingleLabelClassificationResultDocumentsItem { } [CodeGenModel("EntitiesResultDocumentsItem")] internal partial class EntitiesResultDocumentsItem { } [CodeGenModel("EntityLinkingResultDocumentsItem")] internal partial class EntityLinkingResultDocumentsItem { } [CodeGenModel("ExtractiveSummarizationResultDocumentsItem")] internal partial class ExtractiveSummarizationResultDocumentsItem { } [CodeGenModel("HealthcareResultDocumentsItem")] internal partial class HealthcareResultDocumentsItem { } [CodeGenModel("KeyPhraseResultDocumentsItem")] internal partial class KeyPhraseResultDocumentsItem { } [CodeGenModel("PiiResultDocumentsItem")] internal partial class PiiResultDocumentsItem { } [CodeGenModel("SentimentResponseDocumentsItem")] internal partial class SentimentResponseDocumentsItem { } #pragma warning restore SA1402 // File may only contain a single type }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; namespace Nuget.PackageIndex.Models { /// <summary> /// Type metadata exposed publicly /// </summary> public class ModelBase { public List<string> TargetFrameworks { get; internal set; } public ModelBase() { TargetFrameworks = new List<string>(); } public void MergeTargetFrameworks(IEnumerable<string> newTargetFrameworks) { if (newTargetFrameworks == null) { return; } foreach(var newFx in newTargetFrameworks) { if (TargetFrameworks.All(x => !x.Equals(newFx, StringComparison.OrdinalIgnoreCase))) { TargetFrameworks.Add(newFx); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; namespace BlockLoader.DataLayer { public class RespondentRepository : IRespondentRepository { private const string RespondentElementName = "respondent"; private const string ReachedBlocksElementName = "reachedblocks"; private const string ReachedBlockElementName = "reachedblock"; private const string CodeElementName = "code"; private readonly XmlLoader _loader; private readonly string _filePath; public RespondentRepository(XmlLoader loader, string filePath) { _loader = loader; _filePath = filePath; } public IEnumerable<Respondent> LoadRespondents() { if (!File.Exists(_filePath)) { throw new FileNotFoundException(_filePath); } var doc = LoadDocument(_filePath); if (doc?.Root == null) { throw new InvalidOperationException("Xml file is empty, or invalid."); } var respondentElements = doc.Root.Elements(RespondentElementName); return respondentElements.Select(CreateRespondentFromElement).Where(b => b != null); } private Respondent CreateRespondentFromElement(XElement respondentElement) { HashSet<string> reachedBlocks = null; var reachedBlocksElement = respondentElement.Element(ReachedBlocksElementName); if (reachedBlocksElement == null) { throw new InvalidOperationException("RespondentElement missing ReachedBlocks Element"); } var reachedBlockElement = reachedBlocksElement.Elements(ReachedBlockElementName).Where(element => element != null); reachedBlocks = new HashSet<string>(); foreach (string code in reachedBlockElement.Select(GetCodeFromReachedBlockElement).Where(c => c != null)) { if (!reachedBlocks.Contains(code)) { reachedBlocks.Add(code); } } return new Respondent(reachedBlocks); } private string GetCodeFromReachedBlockElement(XElement reachedBlockElement) { var attribute = reachedBlockElement.Attribute(XName.Get(CodeElementName)); if (attribute == null) { throw new InvalidOperationException("ReachedBlockElement missing code attribute"); } if (attribute.Value == null) { throw new FormatException("Code is null"); } return attribute.Value; } private XDocument LoadDocument(string filePath) { return _loader.Load(filePath); } } }
using System; namespace Xposed { public partial class XC_MethodHook { public static XC_MethodHook Create(Action<XC_MethodHook.MethodHookParam> beforeHookedMethodHandler = null, Action<XC_MethodHook.MethodHookParam> afterHookedMethodHandler = null) { return new XC_MethodHook_Impl { BeforeHookedMethodHandler = beforeHookedMethodHandler, AfterHookedMethodHandler = afterHookedMethodHandler }; } } class XC_MethodHook_Impl : Xposed.XC_MethodHook { public Action<Xposed.XC_MethodHook.MethodHookParam> BeforeHookedMethodHandler; public Action<Xposed.XC_MethodHook.MethodHookParam> AfterHookedMethodHandler; protected override void BeforeHookedMethod(Xposed.XC_MethodHook.MethodHookParam param) { BeforeHookedMethodHandler?.Invoke(param); base.BeforeHookedMethod(param); } protected override void AfterHookedMethod(Xposed.XC_MethodHook.MethodHookParam param) { AfterHookedMethodHandler?.Invoke(param); base.AfterHookedMethod(param); } } }
using System; using System.Text.Json.Serialization; namespace PatreonClient.Models.Attributes { public class Media { [JsonPropertyName("file_name")] public string FileName { get; set; } [JsonPropertyName("size_bytes")] public int SizeBytes { get; set; } [JsonPropertyName("mimetype")] public string MimeType { get; set; } [JsonPropertyName("state")] public string State { get; set; } [JsonPropertyName("owner_type")] public string OwnerType { get; set; } [JsonPropertyName("owner_id")] public string OwnerId { get; set; } [JsonPropertyName("owner_relationship")] public string OwnerRelationship { get; set; } [JsonPropertyName("upload_expires_at")] public DateTimeOffset UploadExpiresAt { get; set; } [JsonPropertyName("upload_url")] public string UploadUrl { get; set; } [JsonPropertyName("upload_parameters")] public object UploadParameters { get; set; } [JsonPropertyName("download_url")] public string DownloadUrl { get; set; } [JsonPropertyName("image_urls")] public object ImageUrls { get; set; } [JsonPropertyName("created_at")] public DateTimeOffset CreatedAt { get; set; } [JsonPropertyName("metadata")] public object Metadata { get; set; } } }
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; namespace Milvasoft.SampleAPI.Utils.Swagger { /// <summary> /// Replaces version parameter. /// </summary> public class ReplaceVersionWithExactValueInPathFilter : IDocumentFilter { /// <summary> /// Applies configuration. /// </summary> /// <param name="swaggerDoc"></param> /// <param name="context"></param> public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var paths = swaggerDoc.Paths; swaggerDoc.Paths = new OpenApiPaths(); foreach (var path in paths) { var key = path.Key.Replace("v{version}", swaggerDoc.Info.Version); var value = path.Value; swaggerDoc.Paths.Add(key, value); } } } }
using Elements; using Elements.Conversion.Revit; using Elements.Conversion.Revit.Extensions; using Elements.Geometry; using System; using System.Collections.Generic; using System.Linq; using ADSK = Autodesk.Revit.DB; namespace HyparRevitRoofConverter { public class RoofConverter : IRevitConverter { public bool CanConvertToRevit => true; public bool CanConvertFromRevit => true; public ADSK.FilteredElementCollector AddElementFilters(ADSK.FilteredElementCollector collector) { //allows us to exclude in place roofs. ADSK.ElementClassFilter classFilter = new ADSK.ElementClassFilter(typeof(ADSK.RoofBase), false); return collector.OfCategory(ADSK.BuiltInCategory.OST_Roofs); } public Element[] FromRevit(ADSK.Element revitElement, ADSK.Document document) { return HyparRoofFromRevitRoof(revitElement); } public ADSK.ElementId[] ToRevit(Element hyparElement, LoadContext context) { return RevitRoofFromHypar(hyparElement, context); } public Element[] OnlyLoadableElements(Element[] allElements) { var types = allElements.Select(e => e.GetType()); var elemType = typeof(Elements.Roof); return allElements.Where(e => e.GetType().FullName == typeof(Elements.Roof).FullName).ToArray(); } private static Element[] HyparRoofFromRevitRoof(ADSK.Element revitRoof) { //return list var returnList = new List<Element>(); //document and element as roofbase (the base class for all Revit roofs) ADSK.Document doc = revitRoof.Document; ADSK.RoofBase roofBase = revitRoof as ADSK.RoofBase; //get the top and bottom materials var materials = roofBase.GetMaterials(); materials.TryGetValue("top", out var topMaterial); materials.TryGetValue("bottom", out var bottomMaterial); //use bounding box for elevation and high point var bBox = roofBase.get_BoundingBox(null); double elevation = Units.FeetToMeters(bBox.Min.Z); double highPoint = Units.FeetToMeters(bBox.Max.Z); //get thickness and area. these parameters apply to footprint or extrusion roofs double thickness = Units.FeetToMeters(roofBase.get_Parameter(ADSK.BuiltInParameter.ROOF_ATTR_THICKNESS_PARAM) .AsDouble()); double area = Units.FeetToMeters(roofBase.get_Parameter(ADSK.BuiltInParameter.HOST_AREA_COMPUTED) .AsDouble()); //get our return information ready Mesh topside = null; Mesh underside = null; Mesh envelope = null; //footprint roofs section //- these have nice API methods for getting top and bottom faces if (roofBase is ADSK.FootPrintRoof footprintRoof) { //create topside var topReferences = ADSK.HostObjectUtils.GetTopFaces(footprintRoof); var topFaces = topReferences.Select(r => footprintRoof.GetGeometryObjectFromReference(r)).ToList(); topside = Create.FacesToMesh(topFaces); //create underside var bottomReferences = ADSK.HostObjectUtils.GetBottomFaces(footprintRoof); var bottomFaces = bottomReferences.Select(r => footprintRoof.GetGeometryObjectFromReference(r)) .ToList(); underside = Create.FacesToMesh(bottomFaces); //create whole envelope var faces = footprintRoof.ExtractRoofFaces(); envelope = Create.FacesToMesh(faces); } //profile roofs section //- these do not have nice API methods for getting top and bottom faces 😥 but we have our own now 😅 if (roofBase is ADSK.ExtrusionRoof extrusionRoof) { //create topside and underside topside = extrusionRoof.ProfileRoofToMesh(); underside = extrusionRoof.ProfileRoofToMesh(false); //build whole envelope var faces = extrusionRoof.ExtractRoofFaces(); envelope = Create.FacesToMesh(faces); } //get the perimeter (same for both roof types) Polygon outerPerimeter = roofBase.ExtractRoofFootprint().First(); //build the roof Roof hyparRoof = new Roof(envelope, topside, underside, outerPerimeter, elevation, highPoint, thickness, area, new Transform(), topMaterial, null, false, Guid.NewGuid(), "Roof"); returnList.Add(hyparRoof); //create mesh element for visualization returnList.Add(new MeshElement(envelope, topMaterial)); return returnList.ToArray(); } private static ADSK.ElementId[] RevitRoofFromHypar(Element hyparElement, LoadContext context) { //our return list of element ids List<ADSK.ElementId> returnElementIds = new List<ADSK.ElementId>(); //document and roof var doc = context.Document; var hyparRoof = hyparElement as Elements.Roof; //instantiate our tesselated shape builder for meshes var tsb = new ADSK.TessellatedShapeBuilder() { Fallback = ADSK.TessellatedShapeBuilderFallback.Salvage, Target = ADSK.TessellatedShapeBuilderTarget.Mesh, GraphicsStyleId = ADSK.ElementId.InvalidElementId, }; tsb.OpenConnectedFaceSet(false); //extract triangles and iterate through adding faces to the mesh var triangles = hyparRoof.Envelope.Triangles.ToList(); foreach (var t in triangles) { var vertices = t.Vertices.Select(v => v.Position.ToXYZ(true)).ToList(); var face = new ADSK.TessellatedFace(vertices, ADSK.ElementId.InvalidElementId); tsb.AddFace(face); } //build the shape tsb.CloseConnectedFaceSet(); tsb.Build(); var result = tsb.GetBuildResult(); //generate a direct shape with it ADSK.DirectShape dShape = ADSK.DirectShape.CreateElement(doc, new ADSK.ElementId(-2000035)); dShape.SetShape(result.GetGeometricalObjects()); dShape.SetName("HYPAR_Roof"); //return the new stuff returnElementIds.Add(dShape.Id); return returnElementIds.ToArray(); } } }
#region Using Statements using System; using Cake.Core; using Cake.Core.IO; using Cake.Core.Annotations; using Cake.Core.Diagnostics; #endregion namespace Cake.SqlTools { /// <summary> /// Contains Cake aliases for executing sql queries /// </summary> [CakeAliasCategory("SqlTools")] public static class SqlQueryAliases { #region Methods /// <summary> /// Executes a sql query against a database /// </summary> /// <param name="context">The cake context.</param> /// <param name="query">The sql query to execute.</param> /// <param name="settings">The <see cref="SqlQuerySettings"/> to use to connect with.</param> [CakeMethodAlias] public static bool ExecuteSqlQuery(this ICakeContext context, string query, SqlQuerySettings settings) { if (String.IsNullOrEmpty(query)) { throw new ArgumentNullException("query"); } if (settings == null) { throw new ArgumentNullException("settings"); } ICakeLog log = settings.AllowLogs ? context.Log : new Logging.QuietLog(); ISqlQueryRepository repository = null; switch (settings.Provider) { case "MsSql": Initializer.InitializeNativeSearchPath(); repository = new MsSqlQueryRepository(log); break; case "MySql": repository = new MySqlQueryRepository(log); break; case "Npgsql": repository = new NpgsqlQueryRepository(log); break; } if (repository != null) { return repository.Execute(settings.ConnectionString, query); } else { log.Error("Unknown sql provider {0}", settings.Provider); return false; } } /// <summary> /// Executes a sql file against a database /// </summary> /// <param name="context">The cake context.</param> /// <param name="path">The path to the sql file to execute.</param> /// <param name="settings">The <see cref="SqlQuerySettings"/> to use to connect with.</param> [CakeMethodAlias] public static bool ExecuteSqlFile(this ICakeContext context, FilePath path, SqlQuerySettings settings) { if (path == null) { throw new ArgumentNullException("path"); } if (settings == null) { throw new ArgumentNullException("settings"); } ICakeLog log = settings.AllowLogs ? context.Log : new Logging.QuietLog(); IFile file = context.FileSystem.GetFile(path); if (file.Exists) { string query = file.ReadBytes().GetString(); return context.ExecuteSqlQuery(query, settings); } else { log.Error("Missing sql file {0}", path.FullPath); return false; } } #endregion } }
// // Copyright 2015 Blu Age Corporation - Plano, Texas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.Practices.ObjectBuilder2; using Summer.Batch.Common.Settings; using Summer.Batch.Common.Util; namespace Summer.Batch.Core.Unity.Injection { /// <summary> /// Dependency resolver that reads a property from the settings. /// </summary> public class SettingsDependencyResolverPolicy<T> : IDependencyResolverPolicy { private readonly string _propertyName; /// <summary> /// Constructs a new <see cref="SettingsDependencyResolverPolicy{T}"/>. /// </summary> /// <param name="propertyName">the name of the property to read</param> public SettingsDependencyResolverPolicy(string propertyName) { _propertyName = propertyName; } /// <summary> /// Resolve object from context. /// </summary> /// <param name="context"></param> /// <returns></returns> public object Resolve(IBuilderContext context) { var settingsManager = context.NewBuildUp<SettingsManager>(); return StringConverter.Convert<T>(settingsManager[_propertyName]); } } }
// This file is part of Core WF which is licensed under the MIT license. // See LICENSE file in the project root for full license information. namespace System.Activities { using System.Activities.Internals; using System.ComponentModel; internal static class ArgumentDirectionHelper { internal static bool IsDefined(ArgumentDirection direction) { return (direction == ArgumentDirection.In || direction == ArgumentDirection.Out || direction == ArgumentDirection.InOut); } public static void Validate(ArgumentDirection direction, string argumentName) { if (!IsDefined(direction)) { throw FxTrace.Exception.AsError( new InvalidEnumArgumentException(argumentName, (int)direction, typeof(ArgumentDirection))); } } public static bool IsIn(Argument argument) { return ArgumentDirectionHelper.IsIn(argument.Direction); } public static bool IsIn(ArgumentDirection direction) { return (direction == ArgumentDirection.In) || (direction == ArgumentDirection.InOut); } public static bool IsOut(Argument argument) { return ArgumentDirectionHelper.IsOut(argument.Direction); } public static bool IsOut(ArgumentDirection direction) { return (direction == ArgumentDirection.Out) || (direction == ArgumentDirection.InOut); } } }
using Microsoft.EntityFrameworkCore.Storage; using Mix.Cms.Lib.Models.Cms; using Mix.Domain.Core.ViewModels; using System.Collections.Generic; using System.Threading.Tasks; namespace Mix.Cms.Lib.ViewModels.MixRelatedAttributeDatas { public class Helper { public static async Task<RepositoryResponse<List<MixRelatedAttributeData>>> RemoveRelatedDataAsync( string parentId, MixEnums.MixAttributeSetDataType parentType, string specificulture , MixCmsContext context, IDbContextTransaction transaction) { var result = await MixRelatedAttributeDatas.DeleteViewModel.Repository.RemoveListModelAsync( true , a => a.ParentId == parentId && a.ParentType == parentType.ToString() && a.Specificulture == specificulture , context, transaction); return result; } } }
using System; class DayOfTheWeek { static void Main() { Console.WriteLine(DateTime.Now.DayOfWeek); } }
using UnityEngine; using Project.Combat; namespace Project.Tests { public class DamageableBuilder { private static DamageableSO _defaultData = null; public static DamageableSO DefaultData { get { if (_defaultData == null) { _defaultData = ScriptableObject.CreateInstance<DamageableSO>(); _defaultData.MaxHealth = 2; } return _defaultData; } } private DamageableSO _data = null; private int _health = 0; public DamageableBuilder WithData(DamageableSO data) { _data = data; return this; } public DamageableBuilder WithHealth(int health) { _health = health; return this; } public Damageable Build() { GameObject damageableGO = new GameObject(); Damageable damageable = damageableGO.AddComponent<Damageable>(); damageable.DamageableData = _data; damageable.Health = _health; return damageable; } public static implicit operator Damageable(DamageableBuilder builder) => builder.Build(); } }
using Models; using System.Collections.Generic; namespace Elastic.Communication { public interface IEntityHandler<TModel, TType> : IElasticHandler<TModel> where TModel : Entity<TType> { TModel GetEntity(TType id, string indexName); IEnumerable<TModel> GetEntities(TType[] ids, string indexName); void UpdateEntity(TModel newEntity, string indexName); void DeleteEntity(TType id, string indexName); } }
@using Extenso.AspNetCore.Mvc.Rendering @model IEnumerable<PersonModel> @{ ViewData["Title"] = "Home Page"; } @Html.Table(Model, new { @class = "table" }) <hr /> <form> <div class="form-group"> <label>Cultures</label> @Html.CulturesDropDownList("Cultures", htmlAttributes: new { @class = "form-control" }) </div> <div class="form-group"> <label>Time Zones</label> @Html.TimeZonesDropDownList("TimeZones", htmlAttributes: new { @class = "form-control" }) </div> <div class="form-group"> <label>CheckBox List</label> @Html.CheckBoxList( "DaysOfWeek", Html.GetEnumSelectList<DayOfWeek>(), null, new { @class = "form-check-label" }, new { @class = "form-check-input" }, inputInsideLabel: true, wrapInDiv: true, wrapperHtmlAttributes: new { @class = "form-check" }) </div> </form>
using Core.Common.Media; using Core.Common.Models.Configurations; using FileProcessor.Actions; using FileProcessor.Actions.Crop; using FileProcessor.Actions.Preview; using FileProcessor.Actions.Resize; using FileProcessor.Actions.Trim; using FileProcessor.Actions.Unknown; using FileProcessor.Engines.FFMPEG; using FileProcessor.Files; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System.IO; namespace FileProcessor.Composition { public static class ActionsComposition { public static void ComposeActions( this IServiceCollection services, IConfiguration configuration) { var processingConfig = GetProcessingConfig(services, configuration); Directory.CreateDirectory(processingConfig.Actions.BaseFilePath); ComposeFfmpeg(services, processingConfig); ComposeActions(services, processingConfig); ComposeHandlers(services); } private static void ComposeHandlers(IServiceCollection services) { services.AddTransient<ResizeActionHandler>(); services.AddTransient<CropActionHandler>(); services.AddTransient<TrimActionHandler>(); services.AddTransient<GeneratePreviewActionHandler>(); services.AddTransient<UnknownActionHandler>(); } private static ProcessingConfiguration GetProcessingConfig( IServiceCollection services, IConfiguration configuration) { var processingConfig = new ProcessingConfiguration(); configuration.GetSection("Processing").Bind(processingConfig); services.AddSingleton(processingConfig); return processingConfig; } private static void ComposeActions(IServiceCollection services, ProcessingConfiguration config) { services.AddTransient<IActionsFileStore, LocalFileStoreAdapter>( x => new LocalFileStoreAdapter( new LocalFileStoreOptions { BaseFilePath = config.Actions.BaseFilePath} )); services.AddTransient<ILocalRecordsComponent, LocalRecordComponent>(); services.AddTransient<IExtensionToMediaTypeMapper, ExtensionToMediaTypeMapper>(); services.AddTransient<IActionsMappings, ActionsMappings>(); services.AddTransient<IActionsHandlerFactory, ActionsHandlerFactory>(); services.AddTransient<IActionsProcessorFacade, ActionsProcessorFacade>(); services.AddTransient<IJsonActionsParser, JsonActionsParser>(); } private static void ComposeFfmpeg(IServiceCollection services, ProcessingConfiguration processingConfig) { var ffmpegDiretory = Path.GetDirectoryName(processingConfig.Actions.FfmpegPath); Xabe.FFmpeg.FFmpeg.SetExecutablesPath(ffmpegDiretory); services.AddTransient<IFFmpegEngine, FFmpegEngine>(); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class MuestraEventos : MonoBehaviour { public UnityEvent MiEventoUnity; public event EventHandler EnCasoDeEspacioPresionado; // Start is called before the first frame update void Start() { EnCasoDeEspacioPresionado += EventoEscuchado; } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Space)) { EnCasoDeEspacioPresionado?.Invoke(this, EventArgs.Empty); MiEventoUnity.Invoke(); } } public void EventoEscuchado(object sender, EventArgs e) { Debug.Log("el evento se escucho correctamente"); } public void EventoUnityDisparado() { Debug.Log("El Evento Unity se disparo correctamente"); } }
namespace Outracks.Fuse.Inspector.Sections { using Fusion; class EachSection { public static IControl Create(IElement element, IEditorFactory editors) { var items = element.GetString("Items", ""); var count = element.GetDouble("Count", 0); return Layout.StackFromTop( Spacer.Medium, Layout.StackFromLeft( editors.Field(items).WithLabelAbove("Items"), Spacer.Medium, editors.Field(count).WithLabelAbove("Count")) .WithInspectorPadding(), Spacer.Medium) .MakeCollapsable(RectangleEdge.Bottom, element.Is("Fuse.Reactive.Each")); } } }
namespace Onos.Net.Utils.Misc.OnLab.Graph { /// <summary> /// Enables implementing classes to represent a graph path search algorithm. /// </summary> /// <typeparam name="V">The vertex type.</typeparam> /// <typeparam name="E">The edge type.</typeparam> public interface IGraphPathSearch<V, E> where V : class, IVertex where E : class, IEdge<V> { /// <summary> /// Searches the specified graph for paths between vertices. /// </summary> /// <param name="graph">The graph to be searched.</param> /// <param name="src">An optional source vertex.</param> /// <param name="dst">An optional destination vertex. /// If null, all destinations will be searched.</param> /// <param name="weighter">An optional edge weigher. /// If null, <see cref="DefaultEdgeWeigher{V, E}"/> will be used. </param> /// <param name="maxPaths"></param> /// <returns></returns> IResult<V, E> Search(IGraph<V, E> graph, V src, V dst, IEdgeWeigher<V, E> weighter, int maxPaths = -1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mobet.Caching { public interface ICacheManager { /// <summary> /// 获取缓存 /// </summary> /// <param name="key">缓存键</param> object Get(string key); /// <summary> /// 获取缓存 /// </summary> /// <param name="key">缓存键</param> /// <param name="invoker">若缓存不存在,则调用invoker获取结果</param> T Get<T>(string key, Func<T> invoker = null); /// <summary> /// 获取多个缓存对象 /// </summary> IDictionary<string, object> MultiGet(IEnumerable<string> keys); /// <summary> /// 获取多个缓存对象 /// </summary> IEnumerable<T> MultiGet<T>(IEnumerable<string> keys); /// <summary> /// 获取多个缓存对象,缓存中遗漏的使用invoker方法补全 /// </summary> IEnumerable<T> MultiGet<T>(IEnumerable<string> keys, Func<IEnumerable<string>, IEnumerable<T>> invoker); /// <summary> /// 缓存数据,覆盖原有键值 /// </summary> void Set(string key, object value); /// <summary> /// 缓存数据,覆盖原有键值 /// 失效条件:到达了失效时间 /// </summary> void Set(string key, object value, DateTime invalidatedTime); /// <summary> /// 缓存数据,覆盖原有键值 /// 失效条件:约定时间内没有被访问 /// </summary> void Set(string key, object value, TimeSpan invalidatedSpan); /// <summary> /// 从缓存中读取value并作出修改后,将value重新存入缓存,存入value时需进行并发校验 /// 失效条件:无 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="invoker"></param> T Modify<T>(string key, Func<T, T> invoker); /// <summary> /// 从缓存中读取value并作出修改后,将value重新存入缓存,存入value时需进行并发校验 /// 失效条件:到达了失效时间 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="invoker"></param> T Modify<T>(string key, Func<T, T> invoker, DateTime expireAt); /// <summary> /// 从缓存中读取value并作出修改后,将value重新存入缓存,存入value时需进行并发校验 /// 失效条件:约定时间内没有被访问 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="invoker"></param> T Modify<T>(string key, Func<T, T> invoker, TimeSpan validFor); /// <summary> /// 获取缓存,如果不存在,则缓存invoker的执行结果 /// </summary> T Retrive<T>(string key, Func<T> invoker); /// <summary> /// 获取缓存,如果不存在,则缓存invoker的执行结果 /// 失效条件:到达了失效时间 /// </summary> T Retrive<T>(string key, Func<T> invoker, DateTime invalidatedTime); /// <summary> /// 获取缓存,如果不存在,则缓存invoker的执行结果 /// 失效条件:约定时间内没有被访问 /// </summary> T Retrive<T>(string key, Func<T> invoker, TimeSpan invalidatedSpan); /// <summary> /// 延长缓存寿命 /// </summary> T Lengthen<T>(string key, Func<T, Tuple<T, bool>> lengthenInvoker, Func<T> initInvoker, DateTime expireAt); /// <summary> /// 延长缓存寿命 /// </summary> T Lengthen<T>(string key, Func<T, Tuple<T, bool>> lengthenInvoker, Func<T> initInvoker, TimeSpan validFor); /// <summary> /// 移除指定缓存 /// </summary> void Remove(string key); /// <summary> /// 清空所有缓存 /// </summary> void FlushAll(); #region 为减少并发冲突,在服务端实现计数更新 /// <summary> /// 计数增加,只有当key存在时,才进行计数 /// </summary> /// <param name="key"></param> /// <param name="delta">增加数</param> void Increment(string key, int delta); /// <summary> /// 计数增加,只有当key存在时,才进行计数 /// </summary> /// <param name="key"></param> /// <param name="delta">增加数</param> /// <param name="expiresAt">在指定时间过期</param> void Increment(string key, int delta, DateTime expiresAt); /// <summary> /// 计数增加,只有当key存在时,才进行计数 /// </summary> /// <param name="key"></param> /// <param name="delta">增加数</param> /// <param name="validFor">有效期</param> void Increment(string key, int delta, TimeSpan validFor); /// <summary> /// 计数增加,提供默认值,如果key值不存在,则插入默认值 /// </summary> /// <param name="key"></param> /// <param name="defaultValue">默认值</param> /// <param name="delta">增加数</param> void Increment(string key, int defaultValue, int delta); /// <summary> /// 计数增加,提供默认值,如果key值不存在,则插入默认值 /// </summary> /// <param name="key"></param> /// <param name="defaultValue">默认值</param> /// <param name="delta">增加数</param> /// <param name="expiresAt">在指定时间过期</param> void Increment(string key, int defaultValue, int delta, DateTime expiresAt); /// <summary> /// 计数增加,提供默认值,如果key值不存在,则插入默认值 /// </summary> /// <param name="key"></param> /// <param name="defaultValue">默认值</param> /// <param name="delta">增加数</param> /// <param name="validFor">有效期</param> void Increment(string key, int defaultValue, int delta, TimeSpan validFor); /// <summary> /// 计数减少,只有当key存在时,才进行计数 /// </summary> /// <param name="key"></param> /// <param name="delta">减少数</param> void Decrement(string key, int delta); /// <summary> /// 计数减少,只有当key存在时,才进行计数 /// </summary> /// <param name="key"></param> /// <param name="delta">减少数</param> /// <param name="expiresAt">在指定时间过期</param> void Decrement(string key, int delta, DateTime expiresAt); /// <summary> /// 计数减少,只有当key存在时,才进行计数 /// </summary> /// <param name="key"></param> /// <param name="delta">减少数</param> /// <param name="validFor">有效期</param> void Decrement(string key, int delta, TimeSpan validFor); /// <summary> /// 计数减少,提供默认值,如果key值不存在,则插入默认值 /// </summary> /// <param name="key"></param> /// <param name="defaultValue">默认值</param> /// <param name="delta">减少数</param> void Decrement(string key, int defaultValue, int delta); /// <summary> /// 计数减少,提供默认值,如果key值不存在,则插入默认值 /// </summary> /// <param name="key"></param> /// <param name="defaultValue">默认值</param> /// <param name="delta">减少数</param> /// <param name="expiresAt">在指定时间过期</param> void Decrement(string key, int defaultValue, int delta, DateTime expiresAt); /// <summary> /// 计数减少,提供默认值,如果key值不存在,则插入默认值 /// </summary> /// <param name="key"></param> /// <param name="defaultValue">默认值</param> /// <param name="delta">减少数</param> /// <param name="validFor">有效期</param> void Decrement(string key, int defaultValue, int delta, TimeSpan validFor); #endregion } }
using UnityEngine; using System.Collections; using UnityEngine.AI; using UnityEngine.Networking; public class BotNavWandering : NetworkBehaviour { private ArrayList _patrolPoints; private Transform _currentTargetPatrol; public bool ByPassServerCheck = false; private BotMaster _botMaster; private NavMeshAgent _myNavMeshAgent; private float _checkRate; private float _nextCheck; private Transform _myTransform; private float _wanderRange = 10; private NavMeshHit _navHit; private bool _isCurrentTargetReached = true; private bool _isEnemySeen = false; void OnEnable() { SetInitialReferences(); _botMaster.EventEnemyReachNavTarget += CurrentTargetReached; _botMaster.EventEnemyFoundTarget += ISeeEnemy; _botMaster.EventEnemyLostTarget += ILostEnemy; } void OnDisable() { _botMaster.EventEnemyReachNavTarget -= CurrentTargetReached; _botMaster.EventEnemyFoundTarget -= ISeeEnemy; _botMaster.EventEnemyLostTarget -= ILostEnemy; } void CurrentTargetReached() { _isCurrentTargetReached = true; } void ISeeEnemy(Transform targetTransform) { _isEnemySeen = true; _isCurrentTargetReached = true; } void ILostEnemy(Transform lastSeenPlace) { _isEnemySeen = false; } void SetInitialReferences() { _patrolPoints = new ArrayList(); Transform botTargets = GameObject.Find(GameConstants.BotTargetsName).transform; foreach (Transform child in botTargets) { _patrolPoints.Add(child); } _currentTargetPatrol = (Transform)_patrolPoints[Random.Range(0, _patrolPoints.Count - 1)]; _botMaster = GetComponent<BotMaster>(); _checkRate = Random.Range(0.3f, 0.4f); if (GetComponent<NavMeshAgent>() != null) { _myNavMeshAgent = GetComponent<NavMeshAgent>(); } _myTransform = transform; } // Update is called once per frame void Update() { if (!isServer && !ByPassServerCheck) { return; } SearchInPatrols(); } void SearchInPatrols() { //Usage: Bot searches in predifined places //get a random portal not equal to the current one if (!_isEnemySeen && _isCurrentTargetReached && _nextCheck < Time.time) { _nextCheck = Time.time + _checkRate; int nextPatrolIndex = Random.Range(0, _patrolPoints.Count - 1); Transform nextPatrol = (Transform)_patrolPoints[nextPatrolIndex]; if (nextPatrol != _currentTargetPatrol && !_botMaster.isOnRoute && !_botMaster.isNavPaused) { _isCurrentTargetReached = false; _currentTargetPatrol = nextPatrol; _myNavMeshAgent.SetDestination(nextPatrol.position); _botMaster.CallEventEnemyWalk(nextPatrol.position); } else { SearchInPatrols(); } } } bool RandomWanderTarget(Vector3 centre, float range, out Vector3 result) { //Usage: Bot searches in random places Vector3 randomPoint = centre + Random.insideUnitSphere * _wanderRange; if (NavMesh.SamplePosition(randomPoint, out _navHit, 1.0f, NavMesh.AllAreas)) { result = _navHit.position; return true; } else { result = centre; return false; } } void DisableThis() { this.enabled = false; } }
namespace Abstractions { public interface IRepository { string GetContent(); } }
using System.Threading; using System.Threading.Tasks; namespace Manatee.Trello { /// <summary> /// A collection of comment reactions. /// </summary> public interface ICommentReactionCollection : IReadOnlyCollection<ICommentReaction> { /// <summary> /// Creates a new comment reaction. /// </summary> /// <param name="emoji">The <see cref="Emoji"/> to add.</param> /// <param name="ct">(Optional) A cancellation token.</param> /// <returns>The <see cref="ICommentReaction"/> generated by Trello.</returns> Task<ICommentReaction> Add(Emoji emoji, CancellationToken ct = default); } }
@{ ViewBag.Title = "创建新帐户"; } <script type="text/javascript"> $(function () { $("#btnReturn").button(); }); </script> <h2 class="ui-widget-header h2-center"">创建新帐户</h2> <p class="ui-state-highlight">创建新帐户成功</p> @Html.ActionLink("返回", "Register", "Account", new { onclick = "addToDiv(this);return false;",id="btnReturn" })
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- using System.ServiceModel; using System.Xml.Serialization; namespace Microsoft.Samples.WorkflowServicesSamples.EchoWorkflowClient { public class Expense { public double Amount { get; set; } public string Notes { get; set; } } public class Travel : Expense { public string From { get; set; } public string To { get; set; } public string Carrier { get; set; } } public class Meal : Expense { public string Vendor { get; set; } public string Location { get; set; } } public class PurchaseOrder { [XmlAttribute] public string Department { get; set; } public string Description { get; set; } public double RequestedAmount { get; set; } } [MessageContract] public class VendorRequest { [MessageHeader] public string requestingDepartment; [MessageBodyMember] public string Name; [MessageBodyMember] public string Address; } [MessageContract] public class VendorResponse { [MessageBodyMember] public bool isPreApproved; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class arrowButton : MonoBehaviour { public bool cw; public GameObject ring; public int w; Transform rt; bool prsd; void Start () { rt = ring.transform; prsd = false; } void Update() { if (prsd ) rt.RotateAround(rt.position, cw ? Vector3.back : Vector3.forward, w * Time.deltaTime); } void OnMouseDown() { prsd = true; } void OnMouseUp() { prsd = false; } }
// MIT License // Copyright (c) 2009 Javier Cañon https://www.javiercanon.com // https://github.com/JavierCanon/Shark.NET-Error-Reporter // using System.Collections.Generic; using System.Linq; #pragma warning disable 1591 namespace SharkErrorReporter.SystemInfo { /// <summary> /// SysInfoResult holds results from a (ultimately WMI) query into system information /// </summary> public class SysInfoResult { public SysInfoResult(string name) { Name = name; } public void AddNode(string node) { Nodes.Add(node); } public void AddChildren(IEnumerable<SysInfoResult> children) { ChildResults.AddRange(children); } public List<string> Nodes { get; } = new List<string>(); private void Clear() { Nodes.Clear(); } private void AddRange(IEnumerable<string> nodes) { Nodes.AddRange(nodes); } public string Name { get; } public List<SysInfoResult> ChildResults { get; } = new List<SysInfoResult>(); public SysInfoResult Filter(string[] filterStrings) { var filteredNodes = ( from node in ChildResults[0].Nodes from filter in filterStrings where node.Contains(filter + " = ") select node).ToList(); ChildResults[0].Clear(); ChildResults[0].AddRange(filteredNodes); return this; } } }
using UnityEngine; using System.Collections; public class HealthBehaviour : MonoBehaviour { public float health = 0; public float regenerationRate = 0; //OPTIMISE: delay between damage, probably depending on animation public float postDamageDelay = 0; public bool canTakeDamage = true; void Update () { //regen code, including time to mimic fixedupdate } public bool TryToDamage(float appliedDamage) { if (canTakeDamage) { health -= appliedDamage; //death if applicable if (health <= 0) { Death(); } return true; } else { return false; } } void Death () { //TODO: real death event + animation Debug.Log(this.name + " died (temp death script)."); if (gameObject.tag != "Player") { Destroy(gameObject); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Checkpoint : MonoBehaviour { private Mario mario; private int CurrentCheckpointIndex; // Use this for initialization void Start() { mario = FindObjectOfType<Mario>(); ResetCheckpoints(); } public void ResetCheckpoints() { CurrentCheckpointIndex = 0; gameObject.SetActive(true); } // Update is called once per frame void Update() { // update spawn pos if Player passes checkpoint if (mario.gameObject.transform.position.x >= transform.position.x) { CurrentCheckpointIndex = Mathf.Max(CurrentCheckpointIndex, gameObject.transform.GetSiblingIndex()); mario.AddReward(0.01f * CurrentCheckpointIndex); gameObject.SetActive(false); } } }
using OpenMod.API; namespace OpenMod.Extensions.Games.Abstractions { /// <summary> /// Represents common game capabilities. /// Can be used to check if the current game supports specific features. /// See <see cref="IOpenModHost.HasCapability"/>. /// </summary> public static class KnownGameCapabilities { public static readonly string Inventory = "games-inventory"; public static readonly string Health = "games-health"; public static readonly string Vehicles = "games-vehicles"; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace Microsoft.R.Components.Settings { public interface IRSettings { bool AlwaysSaveHistory { get; set; } bool ClearFilterOnAddHistory { get; set; } bool MultilineHistorySelection { get; set; } /// <summary> /// Path to 64-bit R installation such as /// 'C:\Program Files\R\R-3.2.2' without bin\x64 /// </summary> string RBasePath { get; set; } /// <summary> /// Selected CRAN mirror /// </summary> string CranMirror { get; set; } /// <summary> /// Additional command line arguments to pass /// to the R Host process /// </summary> string RCommandLineArguments { get; set; } /// <summary> /// Current working directory for REPL /// </summary> string WorkingDirectory { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GoalController : MonoBehaviour { [SerializeField] int PlayerId; void OnTriggerEnter(Collider collider) { if (collider.tag == "Ball") { gameObject.SendMessageUpwards("PlayerScored", PlayerId); } } }
using System.IO; namespace HmxLabs.Acct.Core.Test.Data.Config { public class ConfigFileLocations { public static readonly string ConfigDirectoryRelativePath = Path.Combine(".", "Data", "Config"); public static readonly string ConfigDirectoryAbsolutePath = Path.GetFullPath(ConfigDirectoryRelativePath); public const string SampleConfigFilename = "acct.config"; public static readonly string SampleConfig = Path.Combine(ConfigDirectoryAbsolutePath, SampleConfigFilename); } }
using System; using System.Collections.Generic; using System.Linq; using Baseline; using Marten.Events.Aggregation; namespace Marten.Events.Projections { /// <summary> /// Assigns an event to only one stream /// </summary> /// <typeparam name="TId"></typeparam> /// <typeparam name="TEvent"></typeparam> internal class SingleStreamGrouper<TId, TEvent> : IGrouper<TId> { private readonly Func<TEvent, TId> _func; public SingleStreamGrouper(Func<TEvent, TId> expression) { _func = expression; } public void Apply(IEnumerable<IEvent> events, ITenantSliceGroup<TId> grouping) { grouping.AddEvents(_func, events); } } }
using System; using Cake.Svn.Internal.Extensions; using SharpSvn; namespace Cake.Svn.Checkout { internal static class SvnCheckoutSettingsExtensions { internal static SvnCheckOutArgs ToSharpSvn(this SvnCheckoutSettings settings) { settings.NotNull(nameof(settings)); SvnRevision revision; if (settings.Revision == null ) { revision = SvnRevision.Head; } else { revision = new SvnRevision((long)settings.Revision); } return (new SvnCheckOutArgs { Depth = settings.Depth.ToSharpSvn(), IgnoreExternals = settings.IgnoreExternals, AllowObstructions = settings.AllowObstructions, Revision = revision }).SetBaseSettings(settings); } } }
using UnityEngine; using System.Collections; public class HUD : MonoBehaviour { public Texture2D[] items; public int currItem = 0; // Use this for initialization void Start () { } // Update is called once per frame void OnGUI () { currItem = Player.Instance.currentitem; Rect r = new Rect (Screen.width - 210, Screen.height - 75, 64, 64); for (int i =0; i<items.Length; i++) { if (i == 0 && Player.Instance.havePizza == false) continue; GUI.DrawTexture(r, items[i]); if (currItem == i) ROG.DrawBoxOutline (r, 4, Color.blue, 1.0f); r.x += 65; } } }
namespace Alpha.Travel.WebApi.UnitTests { using System; using System.Net.Http; using System.Reflection; using System.Collections.Generic; using Microsoft.AspNetCore; using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Hosting; using NUnit.Framework; using Host; using AutoMapper; using Application.Customers.Models; using Application.Customers.Mappings; using Application.Destinations.Models; using Application.Destinations.Mappings; using Alpha.Travel.WebApi.Models; using Newtonsoft.Json; using System.IO; public abstract class BaseTest { private static readonly string FixtureDir = "../../../fixtures/"; public DestinationPreviewDto Destination { get; private set; } public IList<DestinationPreviewDto> Destinations { get; private set; } public CustomerPreviewDto Customer { get; private set; } public IList<CustomerPreviewDto> Customers { get; private set; } public PagedResponse<Customer> PagedCustomers { get; private set; } public PagedResponse<Destination> PagedDestinations { get; private set; } public ApiSettings ApiSettings { get; private set; } public HttpClient Client { get; private set; } public TestServer Server { get; private set; } public IMapper Mapper { get; private set; } [TearDown] public virtual void Cleanup() { } [SetUp] public virtual void Init() { ApiSettings = new ApiSettings { ApiDocumentationUrl = "https://www.alphatravel.co.uk/v{VERSION}/documentation/", DefaultPageNumber = 1, DefaultPageSize = 20 }; Destination = new DestinationPreviewDto { Id = 1, Description = "This is a test destination", Name = "London" }; Customer = new CustomerPreviewDto { Id = 1, Email = "test@test.com", Firstname = "Jason", Surname = "Thomson", Password = "Password123" }; Destinations = new List<DestinationPreviewDto>{ new DestinationPreviewDto { Id = 1, Description = "This is a test destination", Name = "London" }, new DestinationPreviewDto { Id = 2, Description = "This is a test 2 destination", Name = "Paris" }, new DestinationPreviewDto { Id = 3, Description = "This is a test 3 destination", Name = "New York" } }; Customers = new List<CustomerPreviewDto>{ new CustomerPreviewDto { Id = 1, Email = "test@test.com", Firstname = "Jason", Surname = "Thomson", Password = "Password123" }, new CustomerPreviewDto { Id = 2, Email = "test@test.com", Firstname = "Jason", Surname = "Thomson", Password = "Password123" }, new CustomerPreviewDto { Id = 3, Email = "test@test.com", Firstname = "Jason", Surname = "Thomson", Password = "Password123" } }; PagedCustomers = GetFixture<PagedResponse<Customer>>("customers.json"); PagedDestinations = GetFixture<PagedResponse<Destination>>("destinations.json"); Server = new TestServer(WebHost.CreateDefaultBuilder().UseStartup<Startup>()); Client = Server.CreateClient(); Client.Timeout = TimeSpan.FromMinutes(20); Mapper = CreateMapper(); } private static T GetFixture<T>(string file) { return JsonConvert.DeserializeObject<T>(File.ReadAllText(Path.Combine(FixtureDir, file))); } private IMapper CreateMapper() { var mapperConfig = new MapperConfiguration(cfg => { cfg.AddProfiles(typeof(CustomerMappings).GetTypeInfo().Assembly); cfg.AddProfiles(typeof(DestinationMappings).GetTypeInfo().Assembly); cfg.ValidateInlineMaps = false; }); return mapperConfig.CreateMapper(); } } }
using Evo.WebApi.Models; using Evo.WebApi.Models.DataModel; using Evo.WebApi.Models.Requests; using System.Collections.Generic; using System.Threading.Tasks; namespace Evo.WebApi.Repositories.Interfaces { public interface IMovieRepository { IEnumerable<MovieDataModel> UpsertMovie(MovieRequest video); IEnumerable<MovieDataModel> GetMovies(string videoId = null); } }
/*! * https://github.com/SamsungDForum/JuvoPlayer * Copyright 2019, Samsung Electronics Co., Ltd * Licensed under the MIT license * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Subjects; using Configuration; using JuvoLogger; namespace JuvoPlayer.Player.EsPlayer { internal class DataClockProvider : IDisposable { private static readonly ILogger Logger = LoggerManager.GetInstance().GetLogger("JuvoPlayer"); private TimeSpan _bufferLimit = DataClockProviderConfig.TimeBufferDepthDefault; private TimeSpan _clock; private TimeSpan _synchronizerClock; // Start / Stop may be called from multiple threads. private volatile IDisposable _intervalConnection; private readonly IObservable<TimeSpan> _dataClockSource; private readonly IConnectableObservable<long> _intervalSource; private readonly Subject<TimeSpan> _dataClockSubject = new Subject<TimeSpan>(); private readonly PlayerClockProvider _playerClock; private IObservable<TimeSpan> _synchronizerClockSource; private IDisposable _synchronizerSubscription; private bool _isDisposed; private readonly IScheduler _scheduler; public TimeSpan BufferLimit { set => _bufferLimit = value; } public TimeSpan Clock { set => _clock = value; } public IObservable<TimeSpan> SynchronizerClock { set => _synchronizerClockSource = value; } public DataClockProvider(IScheduler scheduler, PlayerClockProvider playerClock) { _playerClock = playerClock; _scheduler = scheduler; _intervalSource = Observable.Interval(DataClockProviderConfig.ClockInterval, _scheduler) .Publish(); _dataClockSource = _intervalSource .Select(GetDataClock) .Multicast(_dataClockSubject) .RefCount(); } public IObservable<TimeSpan> DataClock() { return _dataClockSource; } private TimeSpan GetDataClock(long _) { var nextClock = _playerClock.Clock; if (nextClock == TimeSpan.Zero) nextClock = _synchronizerClock; if (nextClock > _clock) _clock = nextClock; return _clock + _bufferLimit; } private void SetSynchronizerClock(TimeSpan clock) => _synchronizerClock = clock; public void Stop() { _dataClockSubject.OnNext(TimeSpan.Zero); _synchronizerSubscription?.Dispose(); _synchronizerSubscription = null; _intervalConnection?.Dispose(); _intervalConnection = null; _clock = TimeSpan.Zero; _synchronizerClock = TimeSpan.Zero; Logger.Info("End"); } public void Start() { if (_intervalConnection != null) return; Logger.Info($"Clock {_clock} + Limit {_bufferLimit} = {_clock + _bufferLimit}"); _intervalConnection = _intervalSource.Connect(); _synchronizerSubscription = _synchronizerClockSource.ObserveOn(_scheduler).Subscribe(SetSynchronizerClock); Logger.Info("End"); } public void Dispose() { if (_isDisposed) return; Stop(); _dataClockSubject.Dispose(); _isDisposed = true; Logger.Info("End"); } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace RiotApi.NET.Objects.MatchApi { public class MatchTimeline { [JsonProperty("frames")] public IEnumerable<MatchFrame> Frames { get; set; } [JsonProperty("frameInterval")] public long FrameInterval { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using UniShop.Model.Models; namespace UniShop.Web.Models { public class OrderViewModel { public int ID { get; set; } [Required] [MaxLength(256)] public string CustomerName { get; set; } [Required] [MaxLength(256)] public string CustomerAddress { get; set; } [Required] [MaxLength(256)] public string CustomerEmail { get; set; } [Required] [MaxLength(50)] public string CustomerMobile { get; set; } [Required] [MaxLength(256)] public string CustomerMessage { get; set; } public DateTime? CreateDate { get; set; } public string CreateBy { get; set; } [MaxLength(256)] public string PaymentMethod { get; set; } public string PaymentStatus { get; set; } public bool Status { get; set; } [StringLength(128)] public string CustomerId { get; set; } public string BankCode { get; set; } public virtual IEnumerable<OrderDetail> OrderDetails { get; set; } } }
using TMPro; using UnityEngine; using UnityEngine.EventSystems; namespace UI.ContextMenu { public class MenuAction : MonoBehaviour, IPointerDownHandler, IPointerEnterHandler, IPointerExitHandler { public TextMeshProUGUI actionName = null; private ContextMenuManager contextMenuManager; private ContextMenu.Entry currentEntry; private Animator animator; public void Awake() { animator = GetComponent<Animator>(); } public bool Setup(ContextMenuManager manager, ContextMenu.Entry actionEntry) { if (actionEntry.EntryType != ContextMenu.EntryType.Action) return false; contextMenuManager = manager; currentEntry = actionEntry; actionName.text = currentEntry.Name; return true; } public void OnPointerDown(PointerEventData eventData) { if (eventData.button == PointerEventData.InputButton.Left) { contextMenuManager.NotifyClicked(this); currentEntry.Action?.Invoke(); } } public void OnPointerEnter(PointerEventData eventData) { if(animator != null) animator.Play("In"); } public void OnPointerExit(PointerEventData eventData) { if(animator != null) animator.Play("Out"); } } }
using AutoMapper; using OrderingService.API.Models; using OrderingService.Core.OrderAggregateRoot; namespace OrderingService.API.Profiles { public class OrderProfile : Profile { public OrderProfile() { CreateMap<Order, OrderDto>() .ForMember(dest =>dest.TotalPrice, opt=> opt.MapFrom(src => src.TotalPrice.Amount)) .ForMember(dest =>dest.PriceUnit, opt=> opt.MapFrom(src => src.TotalPrice.Unit)); CreateMap<Order, OrderDetailsShortenedDto>() .ForMember(dest =>dest.TotalPrice, opt=> opt.MapFrom(src => src.TotalPrice.Amount)) .ForMember(dest =>dest.PriceUnit, opt=> opt.MapFrom(src => src.TotalPrice.Unit)) .ForMember(dest => dest.Vendor, opt => opt.MapFrom((src, dest, arg3, ctx) => ctx.Options.Items["Vendor"])) .ForMember(dest => dest.Receipt, opt => opt.MapFrom((src, dest, arg3, ctx) => ctx.Options.Items["Receipt"])) .ForMember(dest => dest.Items, opt => opt.MapFrom((src, dest, arg3, ctx) => ctx.Options.Items["Items"]));; CreateMap<Order, OrderDetailsDto>() .ForMember(dest =>dest.TotalPrice, opt=> opt.MapFrom(src => src.TotalPrice.Amount)) .ForMember(dest =>dest.PriceUnit, opt=> opt.MapFrom(src => src.TotalPrice.Unit)) .ForMember(dest => dest.Customer, opt => opt.MapFrom((src, dest, arg3, ctx) => ctx.Options.Items["Customer"])) .ForMember(dest => dest.ShippingAddress, opt => opt.MapFrom((src, dest, arg3, ctx) => ctx.Options.Items["ShippingAddress"])) .ForMember(dest => dest.Vendor, opt => opt.MapFrom((src, dest, arg3, ctx) => ctx.Options.Items["Vendor"])) .ForMember(dest => dest.Receipt, opt => opt.MapFrom((src, dest, arg3, ctx) => ctx.Options.Items["Receipt"])) .ForMember(dest => dest.Items, opt => opt.MapFrom((src, dest, arg3, ctx) => ctx.Options.Items["Items"])); } } }
using System.Collections.Generic; using System.Collections.Specialized; using HttpMultipartParser; using Memorandum.Core; using Memorandum.Core.Domain; using Memorandum.Web.Middleware; namespace Memorandum.Web.Framework { internal interface IRequest { string Method { get; } string Path { get; } string ContentType { get; } /// <summary> /// Cookies from request /// </summary> NameValueCollection Cookies { get; } /// <summary> /// Query arguments /// </summary> NameValueCollection QuerySet { get; } /// <summary> /// POST arguments if Method == POST /// </summary> NameValueCollection PostArgs { get; } IEnumerable<FilePart> Files { get; } /// <summary> /// TODO: MOVE TO CUSTOM REQUEST OR WHATEVER /// </summary> SessionContext Session { get; set; } /// <summary> /// TODO: MOVE TO CUSTOM REQUEST OR WHATEVER /// </summary> UnitOfWork UnitOfWork { get; set; } /// <summary> /// TODO: MOVE TO CUSTOM REQUEST OR WHATEVER /// </summary> int? UserId { get; set; } /// <summary> /// TODO: MOVE TO CUSTOM REQUEST OR WHATEVER /// </summary> User User { get; } } }
using UnityEngine; namespace AGGE.BestPractices.DesignPatterns { class RigidbodyMover : IMover { public Rigidbody rigidbody; public void Move(Vector3 direction, float speed) { rigidbody.velocity = direction * speed; } } }
using System.Collections.Generic; namespace Solid.Isp.Certo.Interfaces { public interface IPessoa { string Nome { get; set; } IEnumerable<string> Telefones { get; set; } bool IsValid(); } }
using System.Runtime.InteropServices; using System.Threading.Tasks; using OpenRasta.Configuration; using OpenRasta.Hosting.InMemory; using Shouldly; using Xunit; namespace Tests.Scenarios.HandlerSelection.Scenarios.Codecs { public class codec_used_with_optional_parameters { InMemoryHost _server; public codec_used_with_optional_parameters() { _server = new InMemoryHost(() => { ResourceSpace.Has.ResourcesOfType<Kuku>() .AtUri("/old/{id}?a={a}") .And.AtUri("/new/{idWithNewOptional}?a={a}") .HandledBy<KukuHandler>() .AsJsonDataContract(); }); } [GitHubIssue(42)] public async Task parses_to_the_correct_parameter_for_old_style() { var response = await _server.Put("/old/1", "{ }", contentType: "application/json"); response.StatusCode.ShouldBe(200); response.ReadString().ShouldBe("old:id=1;a=False;dto=dto"); } [GitHubIssue(42)] public async Task parses_to_the_correct_parameter_for_new_style() { var response = await _server.Put("/new/1", "{ }", contentType: "application/json"); response.StatusCode.ShouldBe(200); response.ReadString().ShouldBe("new:id=1;a=False;dto=dto"); } public class Kuku { } public class KukuHandler { public string Put(int idWithNewOptional, Kuku dto, bool a = false) { return $"new:id={idWithNewOptional};a={a};dto={(dto == null ? "null" : "dto")}"; } public string Put(int id, [Optional, DefaultParameterValue(false)] bool a, Kuku dto) { return $"old:id={id};a={a};dto={(dto == null ? "null" : "dto")}"; } } } }
using System; using System.Collections.Generic; using System.Text; namespace VehiclesExtension { public class Truck : Vehicle { private const double consumptionIcreasedAC = 1.6; private const double percentageLostFuel = 5; public Truck(double fuelQuantity, double fuelConsumption, double tankCapacity) : base(fuelQuantity, fuelConsumption + consumptionIcreasedAC, tankCapacity) { } public override void Refuel(double liters) { base.Refuel(liters); this.fuelQuantity -= liters * (percentageLostFuel / 100); } } }
using Newtonsoft.Json; namespace Synology.FileStation.Common.Results { public abstract class TaskStartResult { [JsonProperty("taskid")] public string TaskId { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class PlayerProjectile : MonoBehaviour { private Rigidbody _rb; private float _speed; private float _charge; // How charged the projectile was (0..1) [SerializeField] float _maxDamage = 2.0f; // How much damage a fully charged projectile can inflict [SerializeField] ParticleSystem _impactParticles; [SerializeField] AudioClip _impactSound; [SerializeField] AudioClip _projectileFire; private CinemachineShake _cs; [SerializeField] float _shakeIntensity = 3f; [SerializeField] float _shakeTimer = 0.1f; public float Charge { get => _charge; set => _charge = value; } public float Speed { get => _speed; set => _speed = value; } private void Awake() { AudioHelper.PlayClip2D(_projectileFire, 1f); _cs = Camera.main.GetComponent<CinemachineShake>(); _rb = GetComponent<Rigidbody>(); _rb.useGravity = false; } private void FixedUpdate() { Move(); } protected void Move() { Vector3 moveOffset = transform.TransformDirection(Vector3.forward) * _speed * Time.fixedDeltaTime; _rb.MovePosition(_rb.position + moveOffset); } void OnCollisionEnter(Collision other) { PlayerProjectile otherProjectile = other.gameObject.GetComponent<PlayerProjectile>(); if(otherProjectile != null) { Physics.IgnoreCollision(otherProjectile.GetComponent<Collider>(), GetComponent<Collider>()); return; } IDamageable damageableObj = other.gameObject.GetComponent<IDamageable>(); if(damageableObj != null) { int damage = (int) (_charge * (_maxDamage - 1) + 1); damageableObj.Damage(damage); } ImpactFeedback(Quaternion.LookRotation(other.contacts[0].normal)); Destroy(gameObject); } void ImpactFeedback(Quaternion impactRotation) { if (_impactParticles != null) { _impactParticles = Instantiate(_impactParticles, transform.position, impactRotation); _impactParticles.Play(); } if (_impactSound != null) { AudioHelper.PlayClip2D(_impactSound, 1f); } } }
namespace telerikerpService.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.CustomerAddresses", c => new { Id = c.String(nullable: false, maxLength: 128, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Id") }, }), CustomerID = c.String(maxLength: 128), Primary = c.Boolean(nullable: false), Address = c.String(), City = c.String(), State = c.String(), Country = c.String(), POCode = c.String(), Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion", annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Version") }, }), CreatedAt = c.DateTimeOffset(nullable: false, precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "CreatedAt") }, }), UpdatedAt = c.DateTimeOffset(precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "UpdatedAt") }, }), Deleted = c.Boolean(nullable: false, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Deleted") }, }), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Customers", t => t.CustomerID) .Index(t => t.CustomerID) .Index(t => t.CreatedAt, clustered: true); CreateTable( "dbo.Customers", c => new { Id = c.String(nullable: false, maxLength: 128, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Id") }, }), CustomerNumber = c.String(), Name = c.String(), Email = c.String(), Phone = c.String(), Image = c.String(), DefaultDiscount = c.Decimal(nullable: false, precision: 18, scale: 2), CustomerSatisfaction = c.Decimal(nullable: false, precision: 18, scale: 2), PreferredCommunicationChannel = c.String(), Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion", annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Version") }, }), CreatedAt = c.DateTimeOffset(nullable: false, precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "CreatedAt") }, }), UpdatedAt = c.DateTimeOffset(precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "UpdatedAt") }, }), Deleted = c.Boolean(nullable: false, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Deleted") }, }), }) .PrimaryKey(t => t.Id) .Index(t => t.CreatedAt, clustered: true); CreateTable( "dbo.Orders", c => new { Id = c.String(nullable: false, maxLength: 128, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Id") }, }), OrderNumber = c.String(), CustomerID = c.String(maxLength: 128), ShippingAddressID = c.String(maxLength: 128), OrderDate = c.DateTimeOffset(nullable: false, precision: 7), DueDate = c.DateTimeOffset(nullable: false, precision: 7), ShipMethod = c.String(), IsOnline = c.Boolean(nullable: false), Status = c.String(), ShippingAddressModifiedDate = c.DateTimeOffset(precision: 7), Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion", annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Version") }, }), CreatedAt = c.DateTimeOffset(nullable: false, precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "CreatedAt") }, }), UpdatedAt = c.DateTimeOffset(precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "UpdatedAt") }, }), Deleted = c.Boolean(nullable: false, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Deleted") }, }), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Customers", t => t.CustomerID) .ForeignKey("dbo.CustomerAddresses", t => t.ShippingAddressID) .Index(t => t.CustomerID) .Index(t => t.ShippingAddressID) .Index(t => t.CreatedAt, clustered: true); CreateTable( "dbo.OrderDetails", c => new { Id = c.String(nullable: false, maxLength: 128, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Id") }, }), OrderID = c.String(maxLength: 128), ProductID = c.String(maxLength: 128), ModifiedDate = c.DateTime(nullable: false), ProductPrice = c.Decimal(nullable: false, precision: 18, scale: 2), Count = c.Int(nullable: false), Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion", annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Version") }, }), CreatedAt = c.DateTimeOffset(nullable: false, precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "CreatedAt") }, }), UpdatedAt = c.DateTimeOffset(precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "UpdatedAt") }, }), Deleted = c.Boolean(nullable: false, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Deleted") }, }), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Orders", t => t.OrderID) .ForeignKey("dbo.Products", t => t.ProductID) .Index(t => t.OrderID) .Index(t => t.ProductID) .Index(t => t.CreatedAt, clustered: true); CreateTable( "dbo.Products", c => new { Id = c.String(nullable: false, maxLength: 128, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Id") }, }), ProductNumber = c.String(), Name = c.String(), DateAdded = c.DateTimeOffset(nullable: false, precision: 7), Image = c.String(), Weight = c.Decimal(nullable: false, precision: 18, scale: 2), Price = c.Decimal(nullable: false, precision: 18, scale: 2), Location = c.String(), StockLevel = c.Int(nullable: false), Color = c.Int(nullable: false), Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion", annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Version") }, }), CreatedAt = c.DateTimeOffset(nullable: false, precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "CreatedAt") }, }), UpdatedAt = c.DateTimeOffset(precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "UpdatedAt") }, }), Deleted = c.Boolean(nullable: false, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Deleted") }, }), }) .PrimaryKey(t => t.Id) .Index(t => t.CreatedAt, clustered: true); CreateTable( "dbo.Vendors", c => new { Id = c.String(nullable: false, maxLength: 128, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Id") }, }), VendorNumber = c.String(), Name = c.String(), Image = c.String(), Rating = c.Byte(nullable: false), AnnualRevenue = c.Decimal(nullable: false, precision: 18, scale: 2), SalesAmmount = c.Decimal(nullable: false, precision: 18, scale: 2), Phone = c.String(), OrderFrequency = c.String(), LastOrderDate = c.DateTimeOffset(precision: 7), Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion", annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Version") }, }), CreatedAt = c.DateTimeOffset(nullable: false, precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "CreatedAt") }, }), UpdatedAt = c.DateTimeOffset(precision: 7, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "UpdatedAt") }, }), Deleted = c.Boolean(nullable: false, annotations: new Dictionary<string, AnnotationValues> { { "ServiceTableColumn", new AnnotationValues(oldValue: null, newValue: "Deleted") }, }), }) .PrimaryKey(t => t.Id) .Index(t => t.CreatedAt, clustered: true); } public override void Down() { DropForeignKey("dbo.CustomerAddresses", "CustomerID", "dbo.Customers"); DropForeignKey("dbo.Orders", "ShippingAddressID", "dbo.CustomerAddresses"); DropForeignKey("dbo.OrderDetails", "ProductID", "dbo.Products"); DropForeignKey("dbo.OrderDetails", "OrderID", "dbo.Orders"); DropForeignKey("dbo.Orders", "CustomerID", "dbo.Customers"); DropIndex("dbo.Vendors", new[] { "CreatedAt" }); DropIndex("dbo.Products", new[] { "CreatedAt" }); DropIndex("dbo.OrderDetails", new[] { "CreatedAt" }); DropIndex("dbo.OrderDetails", new[] { "ProductID" }); DropIndex("dbo.OrderDetails", new[] { "OrderID" }); DropIndex("dbo.Orders", new[] { "CreatedAt" }); DropIndex("dbo.Orders", new[] { "ShippingAddressID" }); DropIndex("dbo.Orders", new[] { "CustomerID" }); DropIndex("dbo.Customers", new[] { "CreatedAt" }); DropIndex("dbo.CustomerAddresses", new[] { "CreatedAt" }); DropIndex("dbo.CustomerAddresses", new[] { "CustomerID" }); DropTable("dbo.Vendors", removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>> { { "CreatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "CreatedAt" }, } }, { "Deleted", new Dictionary<string, object> { { "ServiceTableColumn", "Deleted" }, } }, { "Id", new Dictionary<string, object> { { "ServiceTableColumn", "Id" }, } }, { "UpdatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "UpdatedAt" }, } }, { "Version", new Dictionary<string, object> { { "ServiceTableColumn", "Version" }, } }, }); DropTable("dbo.Products", removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>> { { "CreatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "CreatedAt" }, } }, { "Deleted", new Dictionary<string, object> { { "ServiceTableColumn", "Deleted" }, } }, { "Id", new Dictionary<string, object> { { "ServiceTableColumn", "Id" }, } }, { "UpdatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "UpdatedAt" }, } }, { "Version", new Dictionary<string, object> { { "ServiceTableColumn", "Version" }, } }, }); DropTable("dbo.OrderDetails", removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>> { { "CreatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "CreatedAt" }, } }, { "Deleted", new Dictionary<string, object> { { "ServiceTableColumn", "Deleted" }, } }, { "Id", new Dictionary<string, object> { { "ServiceTableColumn", "Id" }, } }, { "UpdatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "UpdatedAt" }, } }, { "Version", new Dictionary<string, object> { { "ServiceTableColumn", "Version" }, } }, }); DropTable("dbo.Orders", removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>> { { "CreatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "CreatedAt" }, } }, { "Deleted", new Dictionary<string, object> { { "ServiceTableColumn", "Deleted" }, } }, { "Id", new Dictionary<string, object> { { "ServiceTableColumn", "Id" }, } }, { "UpdatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "UpdatedAt" }, } }, { "Version", new Dictionary<string, object> { { "ServiceTableColumn", "Version" }, } }, }); DropTable("dbo.Customers", removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>> { { "CreatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "CreatedAt" }, } }, { "Deleted", new Dictionary<string, object> { { "ServiceTableColumn", "Deleted" }, } }, { "Id", new Dictionary<string, object> { { "ServiceTableColumn", "Id" }, } }, { "UpdatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "UpdatedAt" }, } }, { "Version", new Dictionary<string, object> { { "ServiceTableColumn", "Version" }, } }, }); DropTable("dbo.CustomerAddresses", removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>> { { "CreatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "CreatedAt" }, } }, { "Deleted", new Dictionary<string, object> { { "ServiceTableColumn", "Deleted" }, } }, { "Id", new Dictionary<string, object> { { "ServiceTableColumn", "Id" }, } }, { "UpdatedAt", new Dictionary<string, object> { { "ServiceTableColumn", "UpdatedAt" }, } }, { "Version", new Dictionary<string, object> { { "ServiceTableColumn", "Version" }, } }, }); } } }
using PrintingManager.Data.Infrastructure; using PrintingManager.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PrintingManager.Data.Repositories { public class FormularRepository : RepositoryBase<T_Formular>, IFormularRepository { public FormularRepository(IDbFactory dbFactory) : base(dbFactory) { } } public interface IFormularRepository : IRepository<T_Formular> { } }
using System; using ProtoBuf; using UnityEngine; namespace ET { [ProtoContract] [SceneEntityInfo] public class TriggerBoxInfo:ISceneEntityInfo { [ProtoMember(1)] public float X; [ProtoMember(2)] public float Y; [ProtoMember(3)] public float Z; } }
using UnityEngine; using System.Collections; using Chess.Message; using UnityEngine.EventSystems; using UnityEngine.Events; using System.Collections.Generic; using DG.Tweening; using System.Linq; using Chess.Message.Enum; public class CardCtr : MonoBehaviour { public Vector3 Size = new Vector3(0.05207656f, 0.06724269f, 0.03182981f); public Vector3 TargetLocalPosition; public CardType CardType; public int Num; public int ID; public bool IsFront; public bool IsNew = true; private bool IsSelected = false; public PlayerCtr PlayerCtr = null; Vector3 currPosition; //拖拽前的位置 Vector3 newPosition; //拖拽后的位置 private void Start() { } public void SetUpright() { this.transform.localEulerAngles = new Vector3(0, 180, 0); } public void SetDown() { this.transform.localEulerAngles = new Vector3(90, 0, 0); } public void SetUp(bool playAnimation) { List<CardCtr> cardList = BattleRoomCtr.Instance.CurrentPlayer.HandCards.ListCards(); if (cardList.Contains(this)) { if (playAnimation) this.transform.DOLocalRotate(new Vector3(-110, 0, 180), 0.2f); else this.transform.localEulerAngles = new Vector3(-110, 0, 180); } else { if (playAnimation) this.transform.DOLocalRotate(new Vector3(-90, 180, 0), 0.2f); else this.transform.localEulerAngles = new Vector3(-90, 180, 0); } } public void SetSelected(bool isSelected) { IsSelected = isSelected; if (IsSelected) this.transform.DOLocalMoveY(TargetLocalPosition.y + Size.y * 0.5f, 0.1f); else this.transform.DOLocalMoveY(TargetLocalPosition.y, 0.1f); } public bool GetSelected() { return IsSelected; } private void OnMouseDown() { isMouseDrag = false; oldMousePY = Input.mousePosition.y; } private void OnMouseUp() { if (isMouseDrag) return; Debug.Log("=============== OnMouseDown"); if (!BattleRoomCtr.Instance.IsCanOutCard) return; if (PlayerCtr.UserID != BattleRoomCtr.Instance.SendCommand.UserID) return; if (IsFront) return; if (this.transform.parent.name.StartsWith("OutCards")) return; if (IsSelected) { BattleRoomCtr.Instance.SendCommand.HandOutCardBack(true, this.CardType, this.Num, this.ID); BattleRoomCtr.Instance.OutOrTouchCardFinished(); } else { foreach (var c in BattleRoomCtr.Instance.CurrentPlayer.HandCards.ListCards()) { c.SetSelected(false); } SetSelected(true); } } float oldMousePY = 0; bool isMouseDrag = false; private void OnMouseDrag() { if (GlobalVariable.IsBattleRecordPlay) return; if (!BattleRoomCtr.Instance.IsCanOutCard) return; if (this.transform.parent.name.StartsWith("OutCards")) return; if (this.IsFront) return; if (PlayerCtr.UserID != BattleRoomCtr.Instance.SendCommand.UserID) return; //判断是不是拖动 if (Mathf.Abs(oldMousePY - Input.mousePosition.y) < 0.01f) return; oldMousePY = Input.mousePosition.y; isMouseDrag = true; foreach (var c in BattleRoomCtr.Instance.CurrentPlayer.HandCards.ListCards()) { if (c != this) c.transform.localPosition = new Vector3(c.transform.localPosition.x, 0, c.transform.localPosition.z); } Camera wordCamera = BattleRoomCtr.Instance.BattleCamera; //1:把物体的世界坐标转为屏幕坐标 (依然会保留z坐标) currPosition = wordCamera.WorldToScreenPoint(transform.position); //2:更新物体屏幕坐标系的x,y currPosition = new Vector3(currPosition.x, Input.mousePosition.y, currPosition.z); //3:把屏幕坐标转为世界坐标 newPosition = wordCamera.ScreenToWorldPoint(currPosition); //4:更新物体的世界坐标 transform.position = newPosition; if (transform.localPosition.y < 0) transform.localPosition = new Vector3(transform.localPosition.x, 0, transform.localPosition.z); if (transform.localPosition.z < 0) transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, 0); if (transform.localPosition.y > 0.06f) { BattleRoomCtr.Instance.SendCommand.HandOutCardBack(true, this.CardType, this.Num, this.ID); BattleRoomCtr.Instance.OutOrTouchCardFinished(); } } }
using System; using System.Runtime.InteropServices; namespace libtcod { public enum RandomTypes { MersenneTwister = 0, ComplementaryMultiplyWithCarry = 1 } public enum RandomDistribution { Linear, Gaussian, GaussianRange, GaussianInverse, GaussianRangeInverse } public class Random : IDisposable { static IntPtr DefaultHandle; public static Random Default; [DllImport (Constants.LibraryName)] private extern static IntPtr TCOD_random_get_instance (); static Random () { DefaultHandle = TCOD_random_get_instance (); Default = new Random (DefaultHandle); } public IntPtr Handle { get; private set; } private Random (IntPtr handle) { Handle = handle; } [DllImport (Constants.LibraryName)] private extern static IntPtr TCOD_random_new (RandomTypes type); [DllImport (Constants.LibraryName)] private extern static IntPtr TCOD_random_new_from_seed (RandomTypes type, uint seed); public Random (RandomTypes type) { Handle = TCOD_random_new (type); } public Random (RandomTypes type, uint seed) { Handle = TCOD_random_new_from_seed (type, seed); } [DllImport (Constants.LibraryName)] private extern static void TCOD_random_delete (IntPtr mersenne); public void Dispose () { if (Handle != DefaultHandle) TCOD_random_delete (Handle); } [DllImport (Constants.LibraryName)] private extern static void TCOD_random_set_distribution (IntPtr mersenne, RandomDistribution distribution); public void SetRandomDistribution (RandomDistribution distribution) { TCOD_random_set_distribution (Handle, distribution); } [DllImport (Constants.LibraryName)] private extern static int TCOD_random_get_int (IntPtr mersenne, int min, int max); public int GetInt (int min, int max) { return TCOD_random_get_int (Handle, min, max); } [DllImport (Constants.LibraryName)] private extern static int TCOD_random_get_int_mean (IntPtr mersenne, int min, int max, int mean); public int GetInt (int min, int max, int mean) { return TCOD_random_get_int_mean (Handle, min, max, mean); } [DllImport (Constants.LibraryName)] private extern static float TCOD_random_get_float (IntPtr mersenne, float min, float max); public float GetFloat (float min, float max) { return TCOD_random_get_float (Handle, min, max); } [DllImport (Constants.LibraryName)] private extern static float TCOD_random_get_float_mean (IntPtr mersenne, float min, float max, float mean); public float GetFloat (float min, float max, float mean) { return TCOD_random_get_float_mean (Handle, min, max, mean); } [DllImport (Constants.LibraryName)] private extern static double TCOD_random_get_double (IntPtr mersenne, double min, double max); public double GetDouble (double min, double max) { return TCOD_random_get_double (Handle, min, max); } [DllImport (Constants.LibraryName)] private extern static double TCOD_random_get_double_mean (IntPtr mersenne, double min, double max, double mean); public double GetDouble (double min, double max, double mean) { return TCOD_random_get_double_mean (Handle, min, max, mean); } } }
// File generated from our OpenAPI spec namespace Stripe { using Newtonsoft.Json; public class TokenBankAccountOptions : INestedOptions { /// <summary> /// The name of the person or business that owns the bank account.This field is required /// when attaching the bank account to a <c>Customer</c> object. /// </summary> [JsonProperty("account_holder_name")] public string AccountHolderName { get; set; } /// <summary> /// The type of entity that holds the account. It can be <c>company</c> or /// <c>individual</c>. This field is required when attaching the bank account to a /// <c>Customer</c> object. /// One of: <c>company</c>, or <c>individual</c>. /// </summary> [JsonProperty("account_holder_type")] public string AccountHolderType { get; set; } /// <summary> /// The account number for the bank account, in string form. Must be a checking account. /// </summary> [JsonProperty("account_number")] public string AccountNumber { get; set; } /// <summary> /// The country in which the bank account is located. /// </summary> [JsonProperty("country")] public string Country { get; set; } /// <summary> /// The currency the bank account is in. This must be a country/currency pairing that <a /// href="https://stripe.com/docs/payouts">Stripe supports.</a>. /// </summary> [JsonProperty("currency")] public string Currency { get; set; } /// <summary> /// The routing number, sort code, or other country-appropriateinstitution number for the /// bank account. For US bank accounts, this is required and should bethe ACH routing /// number, not the wire routing number. If you are providing an IBAN /// for<c>account_number</c>, this field is not required. /// </summary> [JsonProperty("routing_number")] public string RoutingNumber { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace SharpLink { internal class Util { internal static ushort SwapEndianess(ushort value) { byte[] bytes = BitConverter.GetBytes(value); Array.Reverse(bytes); return BitConverter.ToUInt16(bytes, 0); } internal static ulong SwapEndianess(ulong value) { byte[] bytes = BitConverter.GetBytes(value); Array.Reverse(bytes); return BitConverter.ToUInt64(bytes, 0); } } }
using System.Collections.Generic; /* * Lesley Reller * ITSE 1430 * 03/26/2020 */ namespace CharacterCreator.Business { public interface ICharacterDatabase { Character Add ( Character character ); void Delete ( int id ); Character Get ( int id ); IEnumerable <Character> GetAll (); string Update ( int id, Character character ); } }
using System.Net; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.SwaggerGen; using Lykke.Service.BlockchainApi.Contract.Common; using Lykke.Service.Stellar.Api.Models; namespace Lykke.Service.Stellar.Api.Controllers { [Route("api/capabilities")] public class CapabilitiesController : Controller { /// <summary> /// Indicate if optional operations are supported /// </summary> [HttpGet] [SwaggerOperation("capabilities")] [ProducesResponseType(typeof(CapabilitiesResponse), (int)HttpStatusCode.OK)] public IActionResult Get() { return Ok(new CapabilitiesResponse { IsTransactionsRebuildingSupported = false, AreManyInputsSupported = false, AreManyOutputsSupported = false, IsTestingTransfersSupported = false }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System.IO; using System.Text; /// <summary> /// 导出图集配置工具 /// </summary> public class ExportAtlasCfg { //图集所在目录 private const string atlasPath = "Assets/Res/Arts/Atlas"; //导出路径 private const string atlasCfgPath = "Assets/LuaScripts/Cfg"; private const string writeSuffPath = "LuaScripts/Cfg/AtlasConfig.txt"; private const string cfgFileName = "Assets/LuaScripts/Cfg/AtlasConfig.txt"; [MenuItem("Assets/UI工具/导出图集配置", false, 3000)] public static void exportAtlasConfig() { checkExportPath(); doExport(atlasPath); } private static void checkExportPath() { if (!Directory.Exists(atlasCfgPath)) { Directory.CreateDirectory(atlasCfgPath); } if (File.Exists(cfgFileName)) { File.Delete(cfgFileName); } //File.Create(cfgFileName); } private static void doExport(string path) { if (!Directory.Exists(path)) { EditorUtility.DisplayDialog("不存在图集路径", "请检查图集路径", "Sure"); return; } string[] dirs = Directory.GetDirectories(path); for (int i = 0; i < dirs.Length; i++) { //获取文件夹下面所有文件 .png? string[] fils = Directory.GetFiles(dirs[i], "*.png"); for (int j = 0; j < fils.Length; j++) { AssetImporter imp = AssetImporter.GetAtPath(fils[i]); if (imp == null || !imp.assetBundleName.EndsWith(".assetbundle")) { Debug.LogError("请先导出导出一次资源,再导出图集配置"); } string bundleName = imp != null ? imp.assetBundleName : getFolderName(dirs[i]); string iconName = getFolderName(fils[j]); writeCfg(iconName, bundleName); } } AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); EditorUtility.DisplayDialog("导出图集配置完成", "生成目录 : " + cfgFileName, "确定"); } private static void writeCfg(string iconName, string bundleName) { string path = Path.Combine(Application.dataPath, writeSuffPath); FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); //开始写入 StringBuilder builder = new StringBuilder(); builder.Append(getIconName(iconName)); builder.Append(":"); builder.Append(getBundleName(bundleName)); builder.Append("\n"); sw.Write(builder.ToString()); //清空缓冲区 sw.Flush(); //关闭流 sw.Close(); fs.Close(); } static private string getIconName(string name) { string[] lst = name.Split('/'); string realName = lst.Length <= 1 ? lst[0] : lst[lst.Length - 1]; int index = realName.LastIndexOf('.'); realName = realName.Substring(0, index); return realName; } static private string getBundleName(string name) { if (name.EndsWith(".assetbundle")) { name = name.Replace(".assetbundle", ""); return name; } string[] lst = name.Split('\\'); string realName = lst.Length >= 2 ? lst[lst.Length - 2]+"\\"+ lst[lst.Length - 1]: lst[0]; return realName; } static private string getFolderName(string path) { string[] lst = path.Split('\\'); return lst[lst.Length - 1]; } }
using System; namespace codessentials.CGM { internal static class NumberExtensions { /// <summary> /// Gets the decimals before the separator /// </summary> /// <param name="value"></param> /// <returns></returns> public static int GetWholePart(this double value) { return (int)Math.Truncate(value); } /// <summary> /// Gets the decimals after the separator (e.g. 10.2 -> 0.2) /// </summary> /// <param name="value"></param> /// <returns></returns> public static double GetFractionalPart(this double value) { return value - Math.Truncate(value); } } }
namespace Infrastructure.Processes { using System; using System.Linq.Expressions; public interface IProcessManagerDataContext<T> : IDisposable where T : IProcessManager { T Find(T processManager); void Save(T processManager); T Find(Expression<Func<T, bool>> predicate, bool includeComplete = false); } }