Fredbriceshelby's Profile

90
Points

Questions
16

Answers
8

  • Asked on August 31, 2020 in Swift.

    If you don’t want to change the code, you can run the Contents.swift file in the playground using the swift command in Terminal.app, and use > to direct the output to a file, e.g.:

    swift YourPlayground.playground/Contents.swift > output.txt 

    This will cause the output to be written to output.txt in the working directory.

    If you can change the print statements, you can pass your own implementation of TextOutputStream (which writes to a file) to the to: parameter of print. For more info, see this link.

    • 19 views
    • 1 answers
    • 0 votes
  • Asked on August 31, 2020 in iOS.

    Updated for Swift 4:

    guard let htmlStringData = htmlString.data(using: .unicode) else { fatalError() }  let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [                 .documentType: NSAttributedString.DocumentType.html                 .characterEncoding: String.Encoding.unicode.rawValue              ]  let attributedHTMLString = try! NSAttributedString(data: htmlStringData, options: options, documentAttributes: nil) let string = attributedHTMLString.string 
    • 13 views
    • 8 answers
    • 0 votes
  • Asked on August 31, 2020 in iOS.

    Put Spacer in between elements you want keep aside, like

    HStack(alignment: .center, spacing: 0) {     VStack(alignment: .leading) {         Image("\(AppTools.allCases[index])").resizable().frame(width: 27, height: 27)         Text(AppTools.allCases[index].rawValue)             .font(.custom("AvenirNextCyr-Demi", size: 24))         Text(AppTools.allCases[index].subtitles)             .font(.custom("AvenirNextCyr-Demi", size: 12))             .foregroundColor(Color(#colorLiteral(red: 0.4823529412, green: 0.4980392157, blue: 0.6196078431, alpha: 1)))     }.foregroundColor(.white)     .padding(.leading)      Spacer()          // << here !!      Button("+", action: {         self.currentSelectedTool = AppTools.allCases[index]         self.showToolView.toggle()     })         .font(.custom("AvenirNextCyr-Demi", size: 20))         .frame(width: 48, height: 48)         .background(Color(#colorLiteral(red: 1, green: 0.6745098039, blue: 0.1882352941, alpha: 1)).cornerRadius(24))         .foregroundColor(Color(#colorLiteral(red: 0.1294117647, green: 0.137254902, blue: 0.1882352941, alpha: 1)))     .padding(.trailing) } 
    • 16 views
    • 1 answers
    • 0 votes

  • Please help me to understand this …

    Parallel processing means multiple threads are doing things at the same time. This leads to all kinds of weird things that you have to be careful of.

    Consider the line:

    count++; 

    This one C# instruction actually represents multiple operations:

    1. load the value from the count variable from memory into the processor.
    2. add 1 to the value of the value loaded into the processor.
    3. store the new value into the memory location for the count variable.

    Now imagine two threads doing these three instructions at the same time. There’s a slight possibility that both of them will complete step 1 before either completes step 3. That means if count started at zero, both threads will now set count to 1, which isn’t what you intended.

    This line has many more steps between the point where log is read and the point where it is written:

    log += "\t" + count + " Endpoint Name " + eachendpoint + "\n"; 

    Therefore, you’ll find that it’s much more frequent for one thread to overwrite (rather than add to) the value already written by another thread. That’s the behavior you’re noticing.

    … and let me know, what can be done to overcome this.

    First, avoid parallel processing whenever possible.

    If things are going fast enough with a simple foreach loop, don’t try to optimize them.

    If things are not going fast enough with a simple foreach loop, figure out why. Most of the time, it’ll be because of I/O operations (disk or network accesses). In those cases, use concurrent execution of asynchronous tasks rather than multithreading. See https://stackoverflow.com/a/14130314/120955 and What is the difference between asynchronous programming and multithreading?.

    If you’re performing operations that require CPU power, and you really need them to run in parallel to squeeze that extra bit of performance out of them, try to avoid changing state in each one (e.g. setting values for shared variables, like count++). One good strategy for this is Command/Query Separation, where you do your parallel processing on immutable data structures to produce "answers", and then use those answers to make the changes that must be made all on the same thread. Here’s how that might look in your code:

    var logs = RunModuleConfigVariables     .AsParallel()     .WithDegreeOfParallelism(3)     .Select(e =>         "Module Name " + e.Key + " thread: " + Thread.CurrentThread.ManagedThreadId + "\n"             + string.Join("\n",                 e.Value                     .AsParallel()                     .WithDegreeOfParallelism(10)                     .Select((eachendpoint, index) => "\t" + index + " Endpoint Name " + eachendpoint)      ));  Console.WriteLine(string.Join("\n", logs));  

    Finally, if you absolutely must change state in parallel, you need to take the time to learn about locks, Mutexes, Concurrent Collections, atomic operations, and other similar tools, and make sure you’re only using thread-safe methods in parallel contexts, in order to make sure you’re doing it "right."

    That might lead to something like this:

    Parallel.ForEach(RunModuleConfigVariables, new ParallelOptions { MaxDegreeOfParallelism = 3 }, pair => {     Console.WriteLine("Module Name " + pair.Key + " thread: " + Thread.CurrentThread.ManagedThreadId);     var count = 0;     Parallel.ForEach(pair.Value, new ParallelOptions { MaxDegreeOfParallelism = 10 }, eachendpoint =>     {         var thisCount = Interlocked.Increment(ref count);         Console.WriteLine("\t" + thisCount + " Endpoint Name " + eachendpoint + "\n");     }); }); 
    • 14 views
    • 2 answers
    • 0 votes
  • Asked on August 31, 2020 in .NET.

    So, yes.. you are correct in assuming that ToArray duplicates the memory in the stream.

    If you want do not want to do this (for efficiency reasons), you could modify the bytes directly in the stream. Take a look at this:

    // create some bytes: 0,1,2,3,4,5,6,7... var originalBytes = Enumerable.Range(0, 256).Select(Convert.ToByte).ToArray();  using(var ms = new MemoryStream(originalBytes)) // ms is referencing bytes array, not duplicating it {     // var duplicatedBytes = ms.ToArray(); // copy of originalBytes array      // If you don't want to duplicate the bytes but want to     // modify the buffer directly, you could do this:      var bufRef = ms.GetBuffer();      for(var i = 0; i < bufRef.Length; ++i)     {         bufRef[i] = Convert.ToByte(bufRef[i] ^ 0x55);     }      // or this:     /*     ms.TryGetBuffer(out var buf);     for (var i = 0; i < buf.Count; ++i)     {         buf[i] = Convert.ToByte(buf[i] ^ 0x55);     }*/      // or this:     /*     for (var i = 0; i < ms.Length; ++i)     {         ms.Position = i;         var b = ms.ReadByte();          ms.Position = i;         ms.WriteByte(Convert.ToByte(b ^ 0x55));     }*/ }  // originalBytes will now be 85,84,87,86... 

    ETA:

    Edited to add in Blindy’s examples. Thanks! — Totally forgot about GetBuffer and had no idea about TryGetBuffer

    • 14 views
    • 2 answers
    • 0 votes
  • You can make use of .includes array method to achieve the same

    var data = ['abc abc abc', 'def', 'ghi','abc','abc e'];  var result = data.filter(obj => obj.includes('abc'));  console.log(result);

    • 19 views
    • 3 answers
    • 0 votes
  • Accessing dynamically multi levels object.

    var obj = {   name: "john doe",   subobj: {     subsubobj: {       names: "I am sub sub obj"     }   } };  var level = "subobj.subsubobj.names"; level = level.split(".");  var currentObjState = obj;  for (var i = 0; i < level.length; i++) {   currentObjState = currentObjState[level[i]]; }  console.log(currentObjState); 

    Working fiddle: https://jsfiddle.net/andreitodorut/3mws3kjL/

    • 31 views
    • 26 answers
    • 0 votes
  • You are missing the require attribute. Vue Loader, does this automatically when it compiles the <template> blocks in single file components. Try with this:

    require(`~cryptocurrency-icons/svg/color/${this.currency}.svg`) 

    You can read more here.

    • 11 views
    • 2 answers
    • 0 votes