private void UpdateDeleteButtonText() { long deleteSize = GetDeletableFolders().Sum(item => item.TotalSize); btnDelete.Text = $"Delete {Readable.FileSize(deleteSize)}"; btnDelete.Enabled = (deleteSize > 0); }
/// <summary>Initialize the channel.</summary> internal UnboundedChannel(bool runContinuationsAsynchronously) { _runContinuationsAsynchronously = runContinuationsAsynchronously; _completion = new TaskCompletionSource <VoidResult>(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); In = new Readable(this); Out = new Writable(this); }
/// <summary> /// 获取单条评论信息 /// </summary> /// <param name="CommonId"></param> /// <returns></returns> public Readable GetReadable(int CommonId) { string sql = "select `comment`.id,`comment`.content,`comment`.reply_at,readable.whether,author.loginname,dataresource.avatar_url,active.title from `comment` join readable on `comment`.id = readable.commentid join active ON `comment`.ActiveID = active.id join author ON author.id = `comment`.AuthorID join dataresource on dataresource.id = author.DataID where `comment`.id = " + CommonId + " ORDER BY readable.whether,`comment`.reply_at ASC"; Readable readable = MySqlDapper.Query <Readable>(sql).FirstOrDefault(); return(readable); }
private void frmFolderList_Load(object sender, System.EventArgs e) { if (Position != null) { Position.Apply(this); } try { SuspendLayout(); var list = new BindingList <FolderInfo>(); foreach (var folder in Folders.OrderByDescending(item => item.TotalSize)) { list.Add(folder); } BindingSource bs = new BindingSource(); bs.DataSource = list; dgvFolders.DataSource = bs; lblTotalSize.Text = Readable.FileSize(Folders.Sum(item => item.TotalSize)); _sorter = new FolderInfoSorter(dgvFolders, new DataGridViewSorter <FolderInfo> .ColumnInfo() { Column = colSize, IsAscending = false }); } finally { ResumeLayout(); } }
private void UpdateSelectedSize() { var dataSource = dgvFolders.DataSource as BindingSource; var list = dataSource.DataSource as BindingList <FolderInfo>; SelectedSize = list.Where(item => item.IsSelected).Sum(item => item.TotalSize); lblSelectedSize.Text = Readable.FileSize(SelectedSize); }
private static void Main(string[] args) { var cipherText = new B64(File.ReadAllText(@"..\..\..\data.txt")).GetBytes(); var key = new Readable("YELLOW SUBMARINE").GetASCIIBytes(); Console.WriteLine("Decrypted text:"); Console.WriteLine(Decrypt(cipherText, key)); }
/// <summary>Initializes the <see cref="BoundedChannel{T}"/>.</summary> /// <param name="bufferedCapacity">The positive bounded capacity for the channel.</param> /// <param name="mode">The mode used when writing to a full channel.</param> /// <param name="runContinuationsAsynchronously">Whether to force continuations to be executed asynchronously.</param> internal BoundedChannel(int bufferedCapacity, BoundedChannelFullMode mode, bool runContinuationsAsynchronously) { Debug.Assert(bufferedCapacity > 0); _bufferedCapacity = bufferedCapacity; _mode = mode; _runContinuationsAsynchronously = runContinuationsAsynchronously; _completion = new TaskCompletionSource <VoidResult>(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); In = new Readable(this); Out = new Writable(this); }
private static void Main(string[] args) { var key = new Readable("ICE"); var input = new Readable("Burning \'em, if you ain\'t quick and nimble\nI go crazy when I hear a cymbal"); var expected = new Hex("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"); Console.WriteLine($"Encoded: {EncodeMultiXOr(input.GetASCIIBytes(), key.GetASCIIBytes())}"); Console.WriteLine($"Expected: {expected}"); }
public void ShouldGive37AsHammingDistance() { var first = new Readable("this is a test"); var second = new Readable("wokka wokka!!!"); var expected = 37; var answer = Task6.Program.HammingDistance(first.GetASCIIBytes(), second.GetASCIIBytes()); Assert.Equal(expected, answer); }
private void Loop(ProcessStartInfo pi) { while (!disposed) { try { var first = new Disposer(); using (var disposer = new Disposer()) { disposer.Add(first); var proc = Process.Start(pi); disposer.Add(proc); disposer.Add(proc.Kill); var stateTask = Task.Factory.StartNew(() => ReadState(proc), opts); var errorTask = Task.Factory.StartNew(() => ReadError(proc), opts); first.Add(stateTask); first.Add(errorTask); while (true) { if (disposed) { break; } if (stateTask.IsCompleted && errorTask.IsCompleted) { break; } Thread.Sleep(10); } } } catch (Exception ex) { state.Enqueue(ex.Message); error.Enqueue(Readable.Make(pi.FileName)); error.Enqueue(Readable.Make(pi.Arguments)); error.Enqueue(ex.Message); var millis = 5000; while (--millis > 0) { if (disposed) { break; } Thread.Sleep(1); } } } }
public override void Write(RequestHead head) { ThrowIfEnded(); StringBuilder builder = new StringBuilder(); builder.Append(head.Method + WHITESPACE + head.Query + WHITESPACE + head.Version + CRLF); foreach (Header header in head.Headers.AsCollection()) { builder.Append(header.Name + COLON + WHITESPACE + header.Value + CRLF); } builder.Append(CRLF); Readable.Write(Encoding.ASCII.GetBytes(builder.ToString())); }
public override void Write(ResponseHead head) { ThrowIfEnded(); StringBuilder builder = new StringBuilder(); builder.Append(head.Version.ToString() + WHITESPACE + head.StatusCode + WHITESPACE + head.StatusDescription + CRLF); foreach (Header header in head.Headers.AsCollection()) { builder.Append(header.Name + COLON + WHITESPACE + header.Value + CRLF); } builder.Append(CRLF); Readable.Write(Encoding.ASCII.GetBytes(builder.ToString())); }
private static void SafeClientLoop(int pid, IPEndPoint endpoint, TcpClient client, ProcessStartInfo pi) { try { //dynamic service location ClientLoop(pid, endpoint, client, pi); } catch (Exception ex) { WriteError(Readable.Make(pi.FileName)); WriteError(Readable.Make(pi.Arguments)); WriteError(ex.Message); } }
private async Task AnalyzeFolderAsync( ProgressLinkLabel linkLabel, int monthsOld, Func <FileSystemUtil, Task <IEnumerable <FolderInfo> > > getFolders, Action <IEnumerable <FolderInfo> > captureResults) { var fsu = new FileSystemUtil(); var folders = await getFolders.Invoke(fsu); var deletable = folders.Where(folder => folder.IsMonthsOld(monthsOld)); captureResults.Invoke(deletable); long deleteableBytes = deletable.Sum(item => item.TotalSize); linkLabel.Mode = ProgressLinkLabelMode.Text; linkLabel.Text = Readable.FileSize(deleteableBytes); }
public override Readable ReadObject(string fieldName, ConstructorInfo ctorDataReader) { XmlNode node = FindChildNode(fieldName); if (node == null) { return(null); } fCurNodeList.Add(node); Readable readable = (Readable)ctorDataReader.Invoke(new object[] { this }); fCurNodeList.RemoveAt(fCurNodeList.Count - 1); return(readable); }
private void ShowFolderList(LinkLabel control, IEnumerable <FolderInfo> folders) { var dlg = new frmFolderList() { Position = _settings.FolderListPosition }; dlg.Folders = folders; dlg.ShowDialog(); _settings.FolderListPosition = dlg.Position; control.Text = (dlg.SelectedSize != 0) ? $"{Readable.FileSize(folders.Sum(item => item.TotalSize))}, {Readable.FileSize(dlg.SelectedSize)} selected" : Readable.FileSize(folders.Sum(item => item.TotalSize)); UpdateDeleteButtonText(); }
public void ReadFrom(DataReader reader) { string nameSpace = GetType().Namespace; fResponseType = reader.ReadString("ResponseType", 64); //TODO: should/can this be optimized? //fRequest = (Requestable)GetType().Assembly.CreateInstance(nameSpace + "." + fRequestType); string typeName = nameSpace + "." + fResponseType; ConstructorInfo ctor = GetType().Assembly.GetType(nameSpace + "." + fResponseType ).GetConstructor(new Type[] { typeof(DataReader) }); if (ctor == null) { throw new Exception(String.Format("failed getting ctor for type({0})", typeName)); } fResponse = reader.ReadObject(fResponseType.Value, ctor); }
protected void Start() { client = new MongoClient(new MongoUrl("mongodb://*****:*****@ds049624.mlab.com:49624/wordriver")); server = client.GetServer(); server.Connect(); db = server.GetDatabase("wordriver"); allContextPacks = db.GetCollection <BsonDocument>("contextpacks"); allWords = db.GetCollection <BsonDocument>("words"); allWordPacks = db.GetCollection <BsonDocument>("wordpacks"); foreach (BsonDocument item in allWords.FindAll()) { BsonElement name = item.GetElement("name"); string wordValue = name.Value.ToString(); words.Add(wordValue); } Readable.Speak("Let's Build a Sentence!"); }
public override IList ReadStringList(string fieldName, int maxLength, ConstructorInfo listCtor, ConstructorInfo itemCtorString) { IList list = (IList)listCtor.Invoke(new object[] {}); ArrayList nodes = FindChildNodes(fieldName); if (nodes.Count == 0) { return(list); } foreach (XmlNode node in nodes) { Readable readable = (Readable)itemCtorString.Invoke(new object[] { node.InnerText }); list.Add(readable); } return(list); }
// Show a readable object public void ShowReadable(Readable item) { if (!pauseManager.IsPaused) { readableShowing = true; // Make it visible (so we can modify it) readableContainer.SetActive(true); // Add the image readable.sprite = item.sprite; // Specify the dimensions RectTransform rt = readableContainer.GetComponent <RectTransform> (); rt.sizeDelta = item.size; readableTime = Time.time; AddOpenMenuItem("readable"); } }
public override IList ReadList(string fieldName, ConstructorInfo listCtor, ConstructorInfo itemCtorDataReader) { IList list = (IList)listCtor.Invoke(new object[] {}); ArrayList nodes = FindChildNodes(fieldName); if (nodes.Count == 0) { return(list); } foreach (XmlNode node in nodes) { fCurNodeList.Add(node); Readable readable = (Readable)itemCtorDataReader.Invoke(new object[] { this }); list.Add(readable); fCurNodeList.RemoveAt(fCurNodeList.Count - 1); } return(list); }
internal bool Control(SocketException ex, bool silent, bool terminate, bool r, bool w) { if (ex != null || terminate) { #if DEBUG_TCPIO Console.WriteLine("Control: terminate (has exception: {0}, silent: {1}, is server: {2})", ex != null, silent, isServer); #endif // terminate & terminate w/ exception State = TcpSocketState.Closed; if (!silent) { Base.Dispose(); } if (!ReadableEnded) { Readable.End(); } if (!WritableEnded) { Writable.End(); } if (ex != null) { OnError?.Invoke(ex); } OnClose?.Invoke(); return(true); } else if (r && w) { #if DEBUG_TCPIO Console.WriteLine("Control: graceful close (is server: {0})", isServer); #endif // graceful close State = TcpSocketState.Closed; Base.Close(); if (!ReadableEnded) { Readable.End(); } if (!WritableEnded) { Writable.End(); } OnClose?.Invoke(); return(true); } else if (r) { #if DEBUG_TCPIO Console.WriteLine("Control: end readable (is server: {0})", isServer); #endif // end readable State = TcpSocketState.Closing; Readable.End(); if (WritableEnded || OnEnd == null) { #if DEBUG_TCPIO Console.WriteLine("Control: OnEnd == null; progress to close (is server: {0})", isServer); #endif Control(null, false, false, true, true); return(true); } else if (OnEnd != null) { #if DEBUG_TCPIO Console.WriteLine("Control: OnEnd != null (is server: {0})", isServer); #endif OnEnd?.Invoke(); return(false); } } else if (w) { // end writable #if DEBUG_TCPIO Console.WriteLine("Control: end writable (is server: {0})", isServer); #endif State = TcpSocketState.Closing; try { Base.Shutdown(SocketShutdown.Send); } catch (SocketException ex2) { return(Control(ex2, true, false, false, false)); } Writable.End(); if (ReadableEnded) { #if DEBUG_TCPIO Console.WriteLine("Control: progress to close (is server: {0})", isServer); #endif return(Control(null, false, false, true, true)); } return(false); } throw new InvalidOperationException("Cannot do anything"); }
public void BlahBlah() { var @in = new Readable <char>( "{\"Wibble\":123}".AsZeroTerminatedSpan() ); var ops = new Readable <Op>(new[] { Op.ReadObject(), Op.DumpTo(0) }); var tokenData = new Tokenized[16]; var tokens = new Buffer <Tokenized>(tokenData, 15); var charData = new char[16]; var @out = new Buffer <char>(charData, 15); var machine = new Machine(); Write(ref tokens, (0, 0, Token.Object), (2, 6, Token.String), (10, 3, Token.Number), (13, 1, Token.ObjectEnd), (0, 0, Token.End)); while (true) { var(signal, bufferTag) = machine.Next(ref ops, ref @in, ref tokens, ref @out); switch (signal) { case Signal.End: return; case Signal.Underrun: switch (bufferTag) { case Stream.Ops: //load more ops here (should just be simple readable interface) throw new NotImplementedException(); case Stream.In: //read more chars into buffer and carry on //and if we have to wait, then... we can wait at this top level throw new NotImplementedException(); case Stream.Tokens: //token underrun shouldn't be handled here, like throw new NotImplementedException(); case Stream.Out1: //this is the first output buffer //how would this level cope with this? higher level contexts should bind to this throw new NotImplementedException(); case Stream.Out2: //second output buffer throw new NotImplementedException(); default: throw new NotImplementedException(); } } } }
public (Signal, Stream) Next(ref Readable <Op> ops, ref Readable <char> @in, ref Buffer <Tokenized> tokens, ref Buffer <char> @out) { if (!ops.Read(out var op)) { return(Signal.Underrun, Stream.Ops); } switch (op.Type) { case Mode.Dump: //dumping just reads out entirely to the output //but, for this, we need to know the scope of the input to read from //ie, ReadObject will be handled, and then we may want to read everything in it till the end //well, we've been here already: we read ahead till the depth comes back down to our level //question again of how to take tokens from tokenizer; //the problem of where to buffer the bloody things... //instead of having a fixed buffer everywhere, it makes more sense to have one-by-one yielding, each one handled here //but, if we want to skip, then the tokenizer should be able to skip to the proper part //in this case, the tokenizer itself doesn't have to yield depths... //it can just track thm itself //but it does yield them //so, how can we progress with the buffer in place? //we'd have a Readable of tokens, not managed as part of the machine here, but separately //there'd then be an ulterior machine, that fielded signals from the Reader and Binder //the Reader would tokenize into a buffer; the Binder would do whatever it bloody well liked //but at the cost of copying into intermediate memory repeatedly //otherwise, the tokenizer lives here and yields each token upwards to be immediately handled //so, for each token read there'd be a check, and the Tokenizer would move forwards, always updating its state //and the token would be immediately returned to update the state of our thingy here //in the case of skipping, the tokenizer can go into a more efficient mode that just skims till it finds the requisite depth returned //which sounds nice doesn't it //a big stateful structure of machines that proceeds as it reads throw new NotImplementedException(); case Mode.ReadObject: var signal = _tokenizer.Next(ref @in, out var token); switch (signal) { case Signal.Ok: throw new NotImplementedException(); default: return(signal, Stream.In); } //if we're reading an object, //the above better read an object token, or... //or, BADINPUT rises //and BADINPUT will be bubbled out of here //at this point, the program's failed //tho, each layer is a program //ReadLine might be tolerant of errors... //its up to ReadLine to recover //so the machine itself has its buffer of tokens //which are written into here //ReadObject reads tokens into its buffer,forever... //we're in the mood for taking an object //if what we have isn't an object (say, a number or a string) then skip it throw new NotImplementedException(); case Mode.MatchProps: //props should be matched via a trie //each prop encountered should be tested for a match //problem is, how to structure program to fork //easy - we always match multiple props //the prefix trie yields an index, like a jump statement throw new NotImplementedException(); } throw new NotImplementedException(); }
void SearchNearbyPickups() { if (!cutsceneManager.CutsceneActive && !consoleManager.ConsoleOpen) { Collider[] hitColliders = Physics.OverlapSphere(transform.position, 2f, LayerMask.GetMask("Pickup")); if (hitColliders.Length > 0) { // something has gone wrong and our array isn't big enough.. let's fix that if (currentObject > hitColliders.Length - 1) { currentObject = 0; } // Smart Searching will show the item needed most to the user // For example, if the player is on low health then health kits will be the first thing prioritised // Smart searching can be stopped by cycling between other items, and will restart when the player moves if (smartSearch && allowSmartSearch) { bool smartSearchFound = false; if (hitColliders.Length > 1) { // If the player is on 1/2 of their health or less, let's prioritise showing health kits if (entity.CurrentHealth <= (float)(entity.maxHealth / 2)) { for (int i = 0; i < hitColliders.Length; i++) { Pickup pickup = hitColliders [i].GetComponent <Pickup> (); if (pickup != null) { // If this item is rarer, prioritise showing it to the player if (pickup.pickupType == Pickups.Type.Health) { smartSearchFound = true; currentObject = i; break; } } } } // All other searches failed, so let's give the item with the best rarity if (!smartSearchFound) { int bestRarity = 0; for (int i = 0; i < hitColliders.Length; i++) { Pickup pickup = hitColliders [i].GetComponent <Pickup> (); if (pickup != null) { // If this item is rarer, prioritise showing it to the player if (pickup.rarity > bestRarity) { bestRarity = pickup.rarity; currentObject = i; } } } } } } // Show the pickup text near the weapon if (!cutsceneManager.CutsceneActive) { pickupTextObject.SetActive(true); pickupTextObject.transform.position = hitColliders [currentObject].transform.position; pickupText.text = "[" + inputManager.GetKeyValue("INVENTORY_PICK") + "] " + hitColliders [currentObject].gameObject.name; } else { pickupTextObject.SetActive(false); } // User presses pickup key if (inputManager.InputMatchesKeyup("INVENTORY_PICK")) { // Add to inventory, if it's not a readable Readable readable = hitColliders[currentObject].GetComponent <Readable>(); Listenable listenable = hitColliders[currentObject].GetComponent <Listenable>(); Teleportable teleportable = hitColliders[currentObject].GetComponent <Teleportable>(); Interactable interactable = hitColliders[currentObject].GetComponent <Interactable>(); StoryTriggerable triggerable = hitColliders [currentObject].GetComponent <StoryTriggerable> (); if (readable != null) { if (readable.sprite != null && !uiManager.ReadableShowing) { uiManager.ShowReadable(readable); } } else if (listenable != null) { if (listenable.audioSource != null) { if (listenable.useCustomKeys) { soundManager.ToggleSound(listenable.audioSource); } else { soundManager.PlaySound(listenable.audioSource, 0f); } if (listenable.destroyOnActivate) { Destroy(listenable.gameObject); } } } else if (teleportable != null) { if (teleportable.destination != null) { storyManager.TeleportEntity(storyManager.player, teleportable.destination.transform.position); } } else if (interactable != null) { interactable.OnInteraction(); } else if (triggerable != null) { triggerable.OnTrigger(); } else { inventory.AddItemToInventory(hitColliders [currentObject].gameObject); currentObject = 0; } } // User presses cycle key if (inputManager.InputMatchesKeyup("INVENTORY_CYCLE")) { smartSearch = false; currentObject = (currentObject + 1) % hitColliders.Length; } } else { pickupTextObject.SetActive(false); currentObject = 0; } } }
/// <summary>Initialize the channel.</summary> internal UnbufferedChannel() { In = new Readable(this); Out = new Writable(this); }
public IEnumerator <T> GetEnumerator() { return(Readable.GetEnumerator()); }
public override byte[] Read() => Readable.Read();
internal void WriteIncoming(byte[] data) { LastActivityTime = DateTime.UtcNow; CalledTimeout = false; Readable.Write(data); }
public override byte[] Read(int length) => Readable.Read(length);