texts: Baby Step Giant Step Discrete Log Solver

texts:
I've made a concurrent implementation of the Big Step Giant Step discrete log solver in Go. I'm pretty new to this branch of math, but it seems slow. Any way to speed it up or is this the limit of this particular algorithm?

package main

import (
    "fmt"
    "math/big"
    "runtime"
)

const increment = 1000
var processors int

func main() {
    a := big.NewInt(7)
    b := big.NewInt(24190)
    m := big.NewInt(65537)

    processors = runtime.NumCPU()
    runtime.GOMAXPROCS(processors)
    fmt.Println("RESULT:", babyGiant(a, b, m))
}

func modInverse(a, b *big.Int) *big.Int {
    return new(big.Int).ModInverse(a, b)
}
func mod(a, b *big.Int) *big.Int {
    return new(big.Int).Mod(a, b)
}
func pow(a, b *big.Int) *big.Int {
    return new(big.Int).Exp(a, b, nil)
}
func mul(a, b *big.Int) *big.Int {
    return new(big.Int).Mul(a, b)
}
func sub(a, b *big.Int) *big.Int {
    return new(big.Int).Sub(a,b)
}

func babyGiant(a, b, m *big.Int) int64 {
    fmt.Println("Beginning Store Generation")
    var k int64 = 1000
    store := make(map[string]int64)
    var i int64
    previous := mod(big.NewInt(1), m)
    for i = 1; i < k; i++ {
        if i % 1e7 == 0 {
            fmt.Println("Storage of", i, "items completed.")
        }
        current := mod(mul(previous, a), m)
        currentString := current.String()
        if _, inMap := store[currentString]; inMap {
            k = i
            break
        }
        store[currentString] = i
        previous = current
    }
    fmt.Println("Store Generation Complete")

    var r int64 = 0 - increment
    rk := big.NewInt(r * k)
    receiver := make(chan int64)

    semiphoreStart := processors
    semiphore := semiphoreStart
    for rk.Cmp(m) <= 0 {
        if semiphore > 0 {
            semiphore -= 1
            r += increment
            go func (receiver chan int64, rGiven, k int64) {
                r := rGiven
                rk := big.NewInt(r * k)
                fmt.Println("Currently at", rGiven, "\nRemaining:", sub(m, rk), "\n")
                for ; r < rGiven + increment+1; r++ {
                    rk = big.NewInt(r * k)
                    current := mod(mul(b, modInverse(pow(a, rk), m)), m)
                    currentString := current.String()
                    val, inMap := store[currentString]
                    if inMap {
                        receiver <- (val + r*k)
                    }
                }
                receiver <- -1
            }(receiver, r, k)
        } else {
            result := <- receiver
            if result != -1 {
                return result
            }
            semiphore += 1
        }
    }
    for ; semiphore < semiphoreStart; semiphore++ {
        if result := <- receiver; result != -1 {
            return result
        }
    }
    return -1
}


texts:
i am currently learning to do things with vanilla Javascript. No plugins, libraries or code snippets. I want to do things on my own, so that I understand 100% of what is happening.

I wrote a little script which checks, if a section of the page is in view.

Now, the script works as expected, but I was wondering, if I had accomplished the task in a good way. I am especially unsure about looping over the sections in a scroll event. I would love to get some feedback on this. Example page

Here is the code

(function () {
    // Store all panels in variable
    const panels = document.querySelectorAll(".panel");

    // Window on load event
    window.addEventListener("load", () => {
        let scrollTop = window.scrollY;
        let windowHeight = window.innerHeight;
        let documentHeight = document.body.offsetHeight;

        panels.forEach( panel => {
            if(scrollTop == panel.offsetTop ){
                panel.classList.add("is-visible");
            }
        });
    }); // end of load event

    // Window on scroll event
    window.addEventListener("scroll", () => {
        let scrollTop = window.scrollY;
        let windowHeight = window.innerHeight;
        let documentHeight = document.body.offsetHeight;

        panels.forEach( panel => {
            if(scrollTop >= panel.offsetTop - ( windowHeight / 2)){
                panel.classList.add("is-visible");
            } else {
                panel.classList.remove("is-visible");
            }
            if(scrollTop >= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) {
                panel.classList.remove("is-visible");
            }
        });

    }); // end of scroll event
})();

APPENDIX

So I refactored the code as follows. I am still not sure about things like the IIFs.

(function(){

            const panels = document.querySelectorAll(".panel");
            let scrolling = false;

            (function windowOnLoad () {

                // Window on load event
                window.addEventListener("load", () => {
                    let scrollTop = window.scrollY;
                    let windowHeight = window.innerHeight;
                    let documentHeight = document.body.offsetHeight;

                    panels.forEach( panel => {
                        if(scrollTop == panel.offsetTop ){
                            panel.classList.add("is-visible");
                        }
                    });
                }); // end of load event
            })();

            (function windowOnSCroll(){
                window.addEventListener("scroll", () => {
                    scrolling = true;
                });
            })();

            setInterval( function() {
              if (scrolling) {
                scrolling = false;
                let scrollTop = window.scrollY;
                let windowHeight = window.innerHeight;
                let documentHeight = document.body.offsetHeight;

                panels.forEach( panel => {
                    if(scrollTop >= panel.offsetTop - ( windowHeight / 2)){
                        panel.classList.add("is-visible");
                    } else {
                        panel.classList.remove("is-visible");
                    }
                    if(scrollTop >= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) {
                        panel.classList.remove("is-visible");
                    }
                });

              }
            }, 250 );

        })();


texts:
Inspired by jqueryboilerplate.com, I extended their boilerplate to fit my needs. Coming from PHP development, I wanted to have a good starting point for writing jQuery plugins with a defined API/interface (more at jquib.web-sav.de).

/**
 * JQUIB - JQUERY INTERFACEPLUGIN BOILERPLATE
 *
 * This is a solid starter template for your jQuery plugins. Its designed
 * to keep all logic and data hidden from public access except the set of
 * functions you defined inside its interface function namespace.
 *
 * Inspired by http://jqueryboilerplate.com
 *
 * @see        http://web-sav.de/jquib-boilerplate
 * @copyright  Andr&eacute; Kroll
 * @license    MIT
 */
;
(function ($, window, document, undefined) {
  const PLUGIN_NAME = 'your_plugin';

  const defaults = {
    option_one: 'value_1',
    option_two: 'value_2'
  };

  /* PLUGIN - CONSTRUCTOR AND INSTANCE METHODS ............................... (scope: private) */
  var Plugin = {

    options: {},
    /* ... more plugin properties here ... */

    // Gets called whenever a new plugin instance is created
    __construct: function (options) {
      this.options = this.initOptions(options);
      /* ... you can define more parameters for your constructor                     */
      /*     - the bootstrap process will pass them through                          */

      /* ... start writing your plugin logic ...                                     */
      /*     From here you have access to a plugin                                   */
      /*     .. member with           "this.propertyName;"                           */
      /*     .. method with           "this.methodName();"                           */
      /*     .. interface method with "this.public_interface.interfaceMethodName();" */
      /*     .. helper function with  "helperFunctionName();"                        */
      /*                                                                P e a c e    */
    },

    // Validate options and merge with defaults
    initOptions: function (options) {
      /* ... put your option validation logic here ... */
      return $.extend({}, defaults, options);
    }

  };

  /* PLUGIN - PUBLIC / INTERFACE METHODS ...................................... (scope: public) */
  Plugin.public_fn = {

    // Get the jQuery-wrapped plugin container
    get$: function () {
      return $(this.container);
    }

  };

  /* HELPER FUNCTIONS ------------------------------------------------- (scope: private static) */
  {
    // Simple and safe function to log/debug elements
    function log(elementToLog) {
      if ( window.console && window.console.log ) {
        window.console.log(elementToLog);
      }
    }
  }

  /* BOOTSTRAP AND PLUGIN REGISTRATION ======================================================== */
  {
    // Register the plugin at jQuerys function namespace
    $.fn[PLUGIN_NAME] = function (options) {
      var origArgs = arguments;
      this.each(function () {
        if ( undefined == $.data(this, "plugin_" + PLUGIN_NAME) ) {
          // First call by this element: create new instance of the plugin
          $.data(this, "plugin_" + PLUGIN_NAME, (function (container, options) {
            var plugin = Object.create(Plugin);
            plugin['container'] = container;
            plugin['public_interface'] = {};
            for ( prop in plugin.public_fn ) {
              if ( typeof plugin.public_fn[prop] === 'function' ) {
                // Register all interface functions to call within the plugin object context
                plugin['public_interface'][prop] = $.proxy(plugin.public_fn[prop], plugin);
              }
            }
            plugin.__construct.apply(plugin, origArgs);
            return plugin;
          })(this, options));
        }
      });
      // Return plugin interface of the first element
      return $.data(this.get(0), "plugin_" + PLUGIN_NAME).public_interface;
    };
  }
})(jQuery, window, document);


texts:
I have the following case, I need to delete a specific observer for the firebase database reference, so I made a code that looks something like it looks to the NotificationCenter. In various managers I used NSMapTable in order to keep the weak references on UIViewControllers and that controller served as the key to the reference handle. In most UIViewControllers I removed observers in viewDidDisappear, but in some I need to delete it in deinit, for this I used runtime and added two arrays (DatabaseQueue's array and DatabaseReferences' array) as checked in the UIViewController extension.

Please tell me how can I improve this code? Thanks.

private var queuesKey = 0
private var referencesKey = 1

extension UIViewController {

    var firQueues: [DatabaseQuery]? {
        get {
            return objc_getAssociatedObject(self, &queuesKey) as? [DatabaseQuery]
        }
        set {
            objc_setAssociatedObject(self, &queuesKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

    var firReferences: [DatabaseReference]? {
        get {
            return objc_getAssociatedObject(self, &referencesKey) as? [DatabaseReference]
        }
        set {
            objc_setAssociatedObject(self, &referencesKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

    func removeFIRQueuesReferensesObservers() {
        if var _firQueues = firQueues {
            for firQueqry in _firQueues {
                firQueqry.removeAllObservers()
            }
            _firQueues.removeAll()
            firQueues?.removeAll()
            debugPrint("_firReferences", _firQueues.count, "firReferences", firQueues?.count ?? "nil")
        }

        if var _firReferences = firReferences {
            for firRef in _firReferences {
                firRef.removeAllObservers()
            }
            _firReferences.removeAll()
            firReferences?.removeAll()
            debugPrint("_firReferences", _firReferences.count, "firReferences", firReferences?.count ?? "nil")
        }
    }

}

snippet code from one of the managers

class FirebaseUsersManager {

    private var userDeletingObservers = NSMapTable<AnyObject, AnyObject>(keyOptions: .weakMemory, valueOptions: .strongMemory)

    func observeUserDeleting(observer: Any, isObserve: Bool, userID: String, didDeleted: (() -> Void)?, fail: ((_ error: Error) -> Void)?) {
        let ref = Database.database().reference().child(MainGateways.users.rawValue).child(userID)
        if !isObserve {
            guard let handle = userDeletingObservers.object(forKey: observer as AnyObject) as? UInt else { return }
            ref.removeObserver(withHandle: handle)
            userDeletingObservers.removeObject(forKey: observer as AnyObject)
            return
        }

        if let observableVC = observer as? UIViewController {
            if observableVC.firReferences != nil {
                observableVC.firReferences?.append(ref)
            } else {
                observableVC.firReferences = [ref]
            }
        }

        guard userDeletingObservers.object(forKey: observer as AnyObject) as? UInt == nil else { return }

        DispatchQueue.global(qos: .background).async {
            var handle: UInt = 0
            handle = ref.observe(.value, with: { (snap) in
                if snap.value is NSNull {
                    didDeleted?()
                    RealmUsersManager().deleteUser(userID)
                    ref.removeObserver(withHandle: handle)
                    return
                }
            }, withCancel: { (error) in
                fail?(error)
            })
            self.userDeletingObservers.setObject(handle as AnyObject, forKey: observer as AnyObject)
        }
    }

}


texts:
I want to eliminate code duplication in my Fizz-Buzz like program. Any ideas?

#include <stdio.h>
int myseries(int n) {
  int i, cpt = 0;
  if (n < 0) {
    for (i = 0; i >= n; i--) {
      // if the number is multiple of both three and five
      if (i % 15 == 0) {
        printf("lancelot\n");
      }
      // if the number is multiple of 3
      else if(i % 3 == 0) {
        printf("Fizz\n");
      }
      // if the number is multiple of 5
      else if(i % 5 == 0) {
        printf("Buzz\n");
        cpt++;
      }
      else {
        printf("%d\n", i);
      }
    }
    return cpt;
  }
  else {
    for (i = 0; i <= n; i++) {
      // if the number is multiple of both three and five
      if (i % 15 == 0) {
        printf("lancelot\n");
      }
      // if the number is multiple of 3
      else if(i % 3 == 0) {
        printf("Fizz\n");
      }
      //if the number is multiple of 5
      else if(i % 5 == 0) {
        printf("Buzz\n");
        cpt++;
      }
      else {
        printf("%d\n",i);
      }
    }
    return cpt;
  }
}
//example
main() {
  printf("the number of buzz is : %d", myseries(-16));
}


texts: should DRY apply to unit tests as much as production code

texts:
I have a unit test method that looks like this:

...
113 CPPUNIT_ASSERT( !m_pInputFilter[0]->SendPacket() );
114
115 CppUnitUtil::CUnitTestTimeline::GetInstance().Advance( 1, CppUnitUtil::Seconds );
116 CPPUNIT_ASSERT_NO_THROW( m_pTimer->Fire() );
117
118 CPPUNIT_ASSERT_EQUALS( 1, m_pOutputFilter[0]->RecievedPackets() );
119 CPPUNIT_ASSERT_EQUALS( 2, m_pOutputFilter[1]->RecievedPackets() );
120
121 CPPUNIT_ASSERT( !m_pInputFilter[1]->SendPacket() );
122
123 CppUnitUtil::CUnitTestTimeline::GetInstance().Advance( 1, CppUnitUtil::Seconds );
124 CPPUNIT_ASSERT_NO_THROW( m_pMockTimer->Fire() );
125
126 CPPUNIT_ASSERT_EQUALS( 2, m_pOutputFilter[0]->RecievedPackets() );
127 CPPUNIT_ASSERT_EQUALS( 2, m_pOutputFilter[1]->RecievedPackets() );
...

This same chunk of code (lines 113-119) is repeated several more times in this function.

If this was production code, I would've done extract method refactoring in a heartbeat on lines 113-119. But because this is part of a unit test project, I'm having second thoughts and here's why.  Supposed I create a function:

SendNextPacket( int sendFilterIndex, int expectedOutput0, int expectedOutput1 ) {
    CPPUNIT_ASSERT( !m_pInputFilter[sendFilterIndex]->SendPacket() );

    CppUnitUtil::CUnitTestTimeline::GetInstance().Advance( 1, CppUnitUtil::Seconds );
    CPPUNIT_ASSERT_NO_THROW( m_pTimer->Fire() );

    CPPUNIT_ASSERT_EQUALS( expectedOutput0, m_pOutputFilter[0]->RecievedPackets() );
    CPPUNIT_ASSERT_EQUALS( expectedOutput1, m_pOutputFilter[1]->RecievedPackets() );
}

... and my main test method becomes...

...

SendNextPacket( 0, 1, 2 );

SendNextPacket( 1, 2, 2 );

...

The problem becomes that if this unit test fails on line 119 or 127 (from original code segment), my refactored code would not actually tell me which line failed. Instead, in both cases, it will report the same line number which is now in the helper function.

So in original code, yes I have duplication which is bad, but I also have an exact point of failure, which is good.

I've caught myself several times now kicking myself because I would eliminate all duplication, but then end up having to use debugger just to see exactly which one of the calls to the refactored methods is failing.  That seems to be the opposite of what you want from a unit test.

How would you guys approach this type of scenario?


texts:
So I developed some code as part of a larger project.  I came upon a problem with how to match paragraphs, and wasn't sure how to proceed, so I asked on Stack Overflow here.  You can find an in-depth description of my problem there if you're curious.

Just to be clear, I am not reposting the same question here to get an answer.

I came up with a solution to my own problem, but I'm unsure of limits/pitfalls, and here seems like the perfect place for that.

The short version on the explanation is this:  I have two strings, one is the revised version of the other.  I want to generate markups and preserve the paragraph spacing, thus, I need to correlate the list of paragraphs in each, match them, and then mark the remaining as either new or deleted.

So I have a function (paraMatcher()) which matches paragraphs and returns a list of tuples as follows:

(num1, num2) means that the best match for revised paragraph num1 is original paragraph num2
(num, '+') means that there is no match for revised paragraph num, so it must be new (designated by the '+')
(num, '-') means that no revised paragraph was matched to original paragraph num so it must have been deleted (designated by the '-')

So without further adiue, here is my function:

def paraMatcher(orParas, revParas):
    THRESHOLD = 0.75
    matchSet = []
    shifter = 0

    for revPara in revParas:
        print "Checking revPara ", revParas.index(revPara)
        matchTuples = [(difflib.SequenceMatcher(a=orPara,b=revPara).ratio(), orParas.index(orPara)) for orPara in orParas]
        print "MatchTuples: ", matchTuples
        if matchTuples:
            bestMatch = sorted(matchTuples, key = lambda tup: tup[0])[-1]
            print "Best Match: ", bestMatch
            if bestMatch[0] > THRESHOLD:
                orParas.pop(bestMatch[1])
                print orParas
                matchSet.append((revParas.index(revPara), bestMatch[1] + shifter))
                shifter += 1
            else:
                matchSet.append((revParas.index(revPara), "+"))

        print ""
        print "---------------"
        print ""

    if orParas:
        print "++++++++++++++dealing with extra paragraphs++++++++++++++"
        print orParas
        for orPara in orParas:
            matchSet.insert(orParas.index(orPara) + shifter, (orParas.index(orPara) + shifter, "-"))

    return matchSet

While I definitely want review of general coding style, etc, here are a few issues that I'm really interested in getting feedback on:

The function needs to be called with copies of the lists (paraMatcher(lst1[:], lst2[:]))
How might this fail?
How do I determine an appropriate value for THRESHOLD

Some Extra Notes:

I've left the diagnostic printing in there in case any of you want to test it
Due to other parts of the code, its more convenient that this function take lists of paragraphs as arguments, rather than the strings
I don't think it matters, but this is 32-bit Python 2.7.6 running on 64-bit Windows 7


texts:
I'm an amateur at programming and have created the following method with which I pass a lowercase string with the idea it is then returned either in it's original lowercase format, Capitalised or UPPERCASE. I'm not sure this is the best way or is truly "random" but does work up to a point but would like pointers on any improvements or different ways to achieve this.
        //==============================================================================
        // Randomise string case
        //==============================================================================
        private string randomCase (string word)
        {
            string changed;
            Random r = new Random(Guid.NewGuid().GetHashCode());
            int n = r.Next(1, 29);

            if (n >= 1 && n <= 9)
            {
                // First letter capatalised
                changed = char.ToUpper(word[0]) + word.Substring(1);
                return changed;
            }
            else if (n >= 10 && n <= 19)
            {
                // Word capatalised
                changed = word.ToUpper();
                return changed;
            }
            else if (n >= 20 && n <= 29)
            {
                // Left as lower case
                return word;
            }

            return null;
        }


texts: Dephi: faster way to convert a "dirty" string to a number

texts:
How can I make this code faster? the string can contain characters such as ", .?#" and possibly others.

Const Nums = ['0'..'9'];

function CleanNumber(s: String): Int64;
Var z: Cardinal;
begin
  for z := length(s) downto 1 do
   if not (s[z] in Nums) then Delete(s,z,1);
  if s = '' then
    Result := 0 else
    Result := StrToInt64(s);
end;


texts: Showing and hiding element, making my code more useful

texts:
I have just started learning about JavaScript and events. I am interested in learning the JavaScript and not jQuery until I am better at JavaScript.

I wrote this code that will show and hide my div because I basically want to be able to use this code in future web development projects but at the moment it will only apply to one element on page but what if I want to have a few pop up boxes. I understand I will have to have the element positioned absolute.

Can I also ask anyone that is good at JavaScript events to check my code to see if it is well written or if it could be improved? I am just a learning.

To make my questions clearer:

How would I make this code more usable for more than one element?
Is my code well written or does it look like a noob wrote it?

Click Me

SUPRISE


texts:
This is my attempt at a C++ version of Java's LinkedHashMap. Any criticism is welcome.

I implemented important methods. Big thing still to do would be an iterator. First I wanted to get feedback on this thus far:

#include <unordered_map>
#include <list>
#include <utility>
#include <algorithm>
#include <set>

using namespace std;

template <class K, class V>
class linked_hash_map {
private:
    typedef typename list<K>::iterator list_iterator;
    unordered_map< K, pair<V, list_iterator > > hash;
    list<K> ls;
public:
    int size() { return hash.size(); }
    bool empty() { return hash.empty(); }
    void insert(pair<K,V> kv) {
        if (hash.count(kv.first) == 1) {
            auto p = hash[kv.first];
            hash[kv.first] = make_pair(kv.second, p.second);
        } else {
            ls.push_back(kv.first);
            auto it = ls.end(); --it;
            hash.insert( make_pair(kv.first, make_pair(kv.second, it)));
        }
    }
    void erase(K key) {
        if (hash.count(key) == 1) {
            auto p = hash[key];
            hash.erase(key);
            ls.erase(p.second);
        }
    }
    void eraseEldest() {
        if(!hash.empty()) {
            K key = ls.front();
            ls.pop_front();
            hash.erase(key);
        }
    }
    void eraseNewest() {
        if(!hash.empty()) {
            K key = ls.back();
            ls.pop_back();
            hash.erase(key);
        }
    }
    V at(K key) {
        auto p = hash.at(key);
        return p.first;
    }
    V operator[](K key) {
        auto p = hash[key];
        return p.first;
    }
    list<K>& keyList() {
        return ls;
    }
};


texts:
I am writing a simpel program that can basicly do the same as piping two linux commands can do. For example, ls -l | grep vars.sh, this can be done on the Linux console. I need to write a programm in C that can do the same. I think I got it working but I want to know if I am doing it rite and if there are some modifications I can do on my code.

Here is my code:

#include <stdio.h> // Voor verschillende I/O's, macro's, declaraties.
#include <stdlib.h> // Om de system call te activeren.
#include <unistd.h> // Laden van constanten en types.

int main()
{
    pid_t pid;
    int pipefd[2];
    pipe(pipefd);
    pid = fork();

    if(pid==-1){
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    if(pid>0){
        close(pipefd[0]);
        dup2(pipefd[1],1);
        execlp("ls","ls","-l",NULL);
    }
    else{
        close(pipefd[1]);
        dup2(pipefd[0],0);
        execlp("grep","grep",".bashrc",NULL);
        exit(EXIT_FAILURE);
    }
}

Any feedback,rewrites or modifications are welcome.


texts:
I'd like to share my implementation to you to confirm if it's a correct way to solve my problem. I have a list of products which have an attributes table and a description table (both in html_encoded strings). Every product starts at a new print-page using page break. When the attributes and description tables don't fit in one page I want to print the description in the next page.

My solution is to print the attributes table and then print the description div twice: once in the same page with the attributes and once at the next page using a page break; After the page has loaded using JavaScript, I measure the height of both attributes+description and if that is higher than 800 pixels (which means that two pages will be needed) I hide the first description. If their height is lower than 800 pixels (which means they can fit in the same page) I hide the second one.

(I know for certain that neither of the two tables will exceed one page by itself)

Is this a solid solution or are there possible cases in which it will lead to a big mess?

.
.
.
<input id="total_product_count" type="hidden" value="<?php echo $total_product_count; ?>" />

<?php foreach ($products as $product) { ?>

...small image + title....

    <div  class="attribute" id="attributes[<?php echo $product['product_count']; ?>]" ><?php echo $product['attributes']; ?>

    <div id="description[<?php echo $product['product_count']; ?>]" class="tab-content"> <?php echo $product['description']; ?>

    <div id="second_description[<?php echo $product['product_count']; ?>]" class="tab-content">

          <?php echo $product['description']; ?>

<?php }?>


texts:
I've recently had to print some national symbols in windows console using Mingw and found, that I got nothing in the output, if I use wide strings.

So, I studied the problem and found out that it is locale problem. I was unable to find somewhere complete solution, so I had to write something, that seems to work.

So, I decided to publish it here for review, or may be I should publish it somewhere it it worth.

I've tested in Mingw 4.7.0 using Russian locale.
It should probably correctly convert wide strings to national OEM encoded strings.

Code:

#ifndef CUSTOM_LOCALE_H
#define CUSTOM_LOCALE_H

#if (__cplusplus >= 201103L)
#define CUSTOM_LOCALE_OVERRIDE override
#else
#define CUSTOM_LOCALE_OVERRIDE
#endif

#include <locale>
#include <iostream>
#include <windows.h>

namespace custom_locale
{

class CustomLocale : public std::codecvt <wchar_t, char, std::mbstate_t> {
  public:
    explicit CustomLocale ( size_t r = 0 ) : std::codecvt <wchar_t, char, std::mbstate_t> (r) {}

  protected:
    result do_in (state_type&, const char* from, const char* from_end,
                  const char*& from_next, wchar_t* to, wchar_t* to_end, wchar_t*& to_next ) const CUSTOM_LOCALE_OVERRIDE
    {
        std::size_t size = from_end - from;
        std::size_t buffer_size = to_end - to;
        std::size_t written = MultiByteToWideChar(CP_OEMCP, 0, from, size, to, buffer_size);
        to_next = to + written;
        if (written == 0) {
            return error;
        }
        else if (written != buffer_size) {
            return partial;
        }
        else {
            return  ok;
        }
    }

    result do_out (state_type&, const wchar_t* from, const wchar_t* from_end,
                   const wchar_t*& from_next, char* to, char* to_end, char*& to_next ) const CUSTOM_LOCALE_OVERRIDE
    {
        std::size_t size = from_end - from;
        std::size_t buffer_size = to_end - to;
        std::size_t written = WideCharToMultiByte(CP_OEMCP, 0, from, size, to, buffer_size, 0, 0);
        to_next = to + written;
        if (written == 0) {
            return error;
        }
        else if (written != buffer_size) {
            return partial;
        }
        else {
            return  ok;
        }
    }

    result do_unshift ( state_type&, char*, char*, char*& ) const CUSTOM_LOCALE_OVERRIDE { return ok; }
    int do_encoding () const throw () CUSTOM_LOCALE_OVERRIDE { return 1; }
    bool do_always_noconv () const throw () CUSTOM_LOCALE_OVERRIDE { return false; }

    int do_length ( state_type& state, const char* from, const char* from_end, size_t max ) const CUSTOM_LOCALE_OVERRIDE
    {
      return std::codecvt <wchar_t, char, std::mbstate_t>::do_length ( state, from, from_end, max );
    }

    int do_max_length () const throw () CUSTOM_LOCALE_OVERRIDE
    {
      return std::codecvt <wchar_t, char, std::mbstate_t>::do_max_length ();
    }
};

inline void init()
{
    std::locale loc ( std::locale(), new CustomLocale() );
    std::ios_base::sync_with_stdio (false);
    std::wcout.imbue(loc);
    std::wcin.imbue(loc);
}

}

#endif

Example:

#include "custom_locale.h"

int main ()
{
    custom_locale::init();
    std::wstring s(L"привет");
    std::wcout << s << '\n';
    std::wstring u;
    std::wcin >> u;
    s += L' ' + u;
    std::wcout << s << '\n';
    return 0;
}


texts: Groupby count, then sum and get the percentage

texts:
I wrote this code.

It works, but I think there is a more elegant and Pythonic way to this task.

Groupby and count the different occurences
Get the sum of all the occurences
Divide each occurrence by the total of the occurrences and get the percentage

#Creating the dataframe
##The cluster column represent centroid labels of a clustering alghoritm
df=pd.DataFrame({'char':['a','b','c','d','e'], 'cluster':[1,1,2,2,2]})

#Counting the frequency of each labels
cluster_count=df.groupby('cluster').count()

#Calculating the sum of the frequency
cluster_sum=cluster_count.sum()

#Normalizing the frequency
cluster_prct=cluster_count.char.apply(lambda x: 100*x/cluster_sum)

print(cluster_prct)

Output:

cluster
1        40.0
2        60.0


texts: Simon, Mat's Mug, what's the (rating) difference?

texts:
This is a part of the code for the almighty bot @Duga (That's me!).

Every evening, 15 minutes before "RELOAD" (00:00 UTC), I post the reputation differences for some Code Review users.

Example output is:

  Mat's Mug vs. Simon Forsberg: 2728 diff. Year: +3618. Quarter: +885. Month: +648. Week: -40. Day: +185.

The code below makes use of the following classes/interfaces:

StackExchangeAPI: Contains methods for doing a request to Stack Exchange API. The result is then parsed and "slurped" as JSON and stored into a Groovy object.
DugaBot: Contains methods for sending a message to chat
WebhookParameters: Information about where to send the chat message (which chat room)

This class is created on startup (or when tasks are reloaded) and then run() is called on this class through a cron trigger in Grails.

Any comments about the code appreciated.

This code is also available on Github: Zomis/Duga.

class UserRepDiffTask implements Runnable {

    private final StackExchangeAPI stackApi;
    private final DugaBot chatBot;
    private final String usersString;
    private final String site;
    private final WebhookParameters room;

    public UserRepDiffTask(StackExchangeAPI stackApi, String room, DugaBot chatBot, String users, String site) {
        this.stackApi = stackApi;
        this.chatBot = chatBot;
        this.usersString = users.replace(',', ';');
        this.room = WebhookParameters.toRoom(room);
        this.site = site;
    }

    @Override
    public void run() {
        try {
            def result = stackApi.apiCall("users/" + usersString, site, "!23IYXA.sS8.otifg5Aq.2");
            List users = result.items
            if (users.size() != 2) {
                throw new UnsupportedOperationException("Cannot check diff for anything other than two users");
            }

            def max = users.stream().max(Comparator.comparingInt({it.reputation})).get();
            def min = users.stream().min(Comparator.comparingInt({it.reputation})).get();
            StringBuilder str = new StringBuilder();
            str.append(clearName(max.display_name) + " vs. " + clearName(min.display_name) + ": ");
            str.append((int)max.reputation - (int)min.reputation);
            str.append(" diff. ");
            diffStr(str, max, min, "Year", {it.reputation_change_year});
            diffStr(str, max, min, "Quarter", {it.reputation_change_quarter});
            diffStr(str, max, min, "Month", {it.reputation_change_month});
            diffStr(str, max, min, "Week", {it.reputation_change_week});
            diffStr(str, max, min, "Day", {it.reputation_change_day});
            chatBot.postSingle(room, str.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String chatName(String displayName) {
        return clearName(displayName).replace(" ", "");
    }

    public static String clearName(String displayName) {
        while (displayName.contains("&#")) {
            String replacement = displayName.substring(displayName.indexOf("&#") + 2);
            try {
                replacement = replacement.substring(0, replacement.indexOf(';'));
                int ch = Integer.parseInt(replacement);
                displayName = displayName.replaceFirst("&#\\d+;", String.valueOf((char) ch));
            } catch (RuntimeException ex) {
                displayName = displayName.replaceFirst("&#", "");
            }
        }
        return displayName;
    }

    private void diffStr(StringBuilder str, max, min, String string, ToIntFunction<?> function) {
        str.append(string);
        str.append(": ");
        int maxValue = function.applyAsInt(max);
        int minValue = function.applyAsInt(min);
        int diff = maxValue - minValue;
        str.append(diff > 0 ? "+" : "");
        str.append(diff);
        str.append(". ");
    }

}


texts: Turning 1D array to 2D array in TicTacToe

texts:
To check a win in my TicTacToe game, I have created a 2D array that contains all the combination that a game can be won in, like so:

 private int[][] winningCombinations = new int[][] {
            {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
            {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
            {0, 4, 8}, {2, 4, 6}             //diagonal wins
        };
JButton buttons[] = new JButton[9]; // This is what I had when working with 1D array
JButton buttons[][] = new JButton[3][3]; // This is what I have now

then I have used for loop to loop through this array like this:

/*Determine who won*/
        for(int i=0; i<=7; i++){
            if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
                buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
                !buttons[winCombinations[i][0]].getText().equals("")) {
                win = true;
            }
        }

        for(int i = 0; i < 3; i++){
            if (buttons[i*3].getText().equals("X") && buttons[i*3+1].getText().equals("X") && buttons[i*3+2].getText().equals(""))
                buttons[i*3+2].setText("O");
                win = true;
            }

Everything works, but now I am planning to convert my code from 1D to 2D array, but when I convert this to 2D, it does not work. I might be wrong, but this is how I attempted to convert to 2D:

for(int i=0; i<=7; i++){
    if( buttons[winCombinations[i][0]][winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]][winCombinations[i][1]].getText()) &&
        buttons[winCombinations[i][1]][winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]][winCombinations[i][2]].getText()) &&
        !buttons[winCombinations[i][0]][winCombinations[i][0]].getText().equals("")) {
        win = true;
    }
}


texts: Current ISS latitude / longitude position

texts:
I'm looking into basic API examples and I've got the following to work as I want it to. Is there a better way to determine the direction of latitude and longitude? It feels like I could do it better.

import requests
from time import strftime, localtime

response = requests.get('http://api.open-notify.org/iss-now.json')

data = response.json()
status = response.status_code

if status == 200:
    timestamp = data['timestamp']
    time = strftime('%T', localtime(timestamp))

    latitude = data['iss_position']['latitude']
    if float(latitude) > 0:
        lat_dir = 'N'
    else:
        lat_dir = 'S'

    longitude = data['iss_position']['longitude']
    if float(longitude) > 0:
        lon_dir = 'E'
    else:
        lon_dir = 'W'

    print('International Space Station position @ {}'.format(time))
    print('Latitude: {}° {}'.format(latitude, lat_dir))
    print('Longitude: {}° {}'.format(longitude, lon_dir))
else:
    print('Request unsuccessful: {}'.format(status))


texts: C hack: replace printf to collect output and return complete string by using a line buffer

texts:
I have this great C program I'd like to embed into an iOS app. One passes command line arguments to it and the results are printed to stdout via printf and fputs - like with all the good old Unix programs.

Now I'd like to just edit main and the print functions to use my own printf function which collects all the output that normally goes to stdout and return it at the end.

I implemented a solution by using a line buffer to collect all the printfs until the newline. And a dynamic char array whereto I copy when an output line is finished.

The charm of this solution is - it's kind of tcl'ish: just throw everything into a text line, and if it's complete, store it. Now do that as long as necessary and return the whole bunch at the end.

C code:

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

// outLineBuffer collects one output line by several calls to tprntf
#define initialSizeOfReturnBuffer 10 // reduced for testing (would be 16*1024)
#define incrSizeOfReturnBuffer 5     // reduced for testing (would be 1024*1024)
#define outLineBufferMaxSize 4095
char outLineBuffer[sizeof(char)*outLineBufferMaxSize] = "";
char *tReturnString;
size_t sizeOfReturnBuffer, curPosOutBuffer = 0, lenOutLine = 0;

With the replacement tprntf for all the original printf and fputs:

// replace printf with this to collect the parts of one output line.
static int tprntf(const char *format, ...)
{
    const size_t maxLen = sizeof(char)*outLineBufferMaxSize;
    va_list arg;
    int done;

    va_start (arg, format);
    done = vsnprintf (&outLineBuffer[lenOutLine], maxLen-lenOutLine, format, arg);
    va_end (arg);
    lenOutLine = strlen(outLineBuffer);

    return done;
}

And the function when we complete one output line (everywhere \n is printed):

// Output line is now complete: copy to return buffer and reset line buffer.
static void tprntNewLine()
{
    size_t newSize;
    long remainingLenOutBuffer;
    char *newOutBuffer;

    remainingLenOutBuffer = sizeOfReturnBuffer-curPosOutBuffer-1;
    lenOutLine = strlen(outLineBuffer)+1; // + newline character (\n)
    remainingLenOutBuffer -= lenOutLine;

    if (remainingLenOutBuffer < 0) {
        newSize = sizeOfReturnBuffer + sizeof(char)*incrSizeOfReturnBuffer;
        if ((newOutBuffer = realloc(tReturnString, newSize)) != 0) {
            tReturnString = newOutBuffer;
            sizeOfReturnBuffer = newSize;
        } else {
            lenOutLine += remainingLenOutBuffer; //just write part that is still available
            remainingLenOutBuffer = 0;
        }
    }

    snprintf(&tReturnString[curPosOutBuffer], lenOutLine+1, "%s\n", outLineBuffer);

    curPosOutBuffer += lenOutLine;
    outLineBuffer[0] = 0;
    lenOutLine = 0;
}

And a little main to test it (without Swift - e.g. plain gcc):

int main(int argc, char *argv[])
{
    int i;
    sizeOfReturnBuffer = initialSizeOfReturnBuffer*sizeof(char);
    if ((tReturnString = malloc(sizeOfReturnBuffer)) == 0) {
        return 1; // "Sorry we are out of memory. Please close other apps and try again!";
    }
    tReturnString[0] = 0;

    for (i = 1; i < argc; i++) {
        tprntf("%s ", argv[i]);
    }
    tprntNewLine();

    tprntf("%s", "ABC\t");
    tprntf("%d", 12);
    tprntNewLine(); // enough space for that ;-)
    tprntf("%s", "DEF\t");
    tprntf("%d", 34);
    tprntNewLine(); // realloc necessary ...
    tprntf("%s", "GHI\t");
    tprntf("%d", 56);
    tprntNewLine(); // again realloc for testing purposes ...
    printf("tReturnString at the end:\n>%s<\n", tReturnString); // contains trailing newline
    return 0;
}

The call from swift will then be as follows (using CStringArray.swift):

let myArgs = CStringArray(["computeIt", "par1", "par2"])
let returnString = mymain(myArgs.numberOfElements, &myArgs.pointers[0])

if let itReturns = String.fromCString(returnString) {
    print(itReturns)
}

freeMemory()


texts:
Inspired by Nested for-loop ASCII art, I looked at building a more complicated ASCII art than just the normal 'diamond' and 'triangle' variations that crop up occasionally here.

The challenge: Produce the following rocket

     /**\
    //**\\
   ///**\\\
  ////**\\\\
 /////**\\\\\
+=*=*=*=*=*=*+
|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|
|\/\/\/\/\/\/|
|.\/\/..\/\/.|
|..\/....\/..|
+=*=*=*=*=*=*+
|\/\/\/\/\/\/|
|.\/\/..\/\/.|
|..\/....\/..|
|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|
+=*=*=*=*=*=*+
     /**\
    //**\\
   ///**\\\
  ////**\\\\
 /////**\\\\\

The question on Stack Overflow has issues, and those issues got answered before I could put a response together, but, the problem intrigued me, and I built the following code to solve it in a more compact way, using loops as much as possible, and parameterizing almost all aspects of the problem.

public class Rocket {

    private enum Direction {
        FORWARD, BACKWARD
    }

    private static final char NONE = (char) 0;

    private static final String buildSymmetrical(
            char[] chars, char mid, int from, int len) {

        StringBuilder sb = new StringBuilder(len * 2 + 2);
        for (int i = 0; i < len; i++) {
            sb.append(chars[from + i]);
        }
        if (mid != NONE) {
            sb.append(mid).append(mid);
        }
        for (int i = 0; i < len; i++) {
            sb.append(chars[chars.length - from - len + i]);
        }
        return sb.toString();
    }

    private static final String buildLines(
            char bracket, char[] source, int len, char midchar, int charfrom,
            Direction chardir, int linecount, int duplicates) {

        StringBuilder sb = new StringBuilder();
        for (int line = 0; line < linecount; line++) {
            sb.append(bracket);
            int pos = charfrom + line * (chardir == Direction.FORWARD ? 1 : -1);
            String block = buildSymmetrical(source, midchar, pos, len);
            for (int d = 0; d < duplicates; d++) {
                sb.append(block);
            }
            sb.append(bracket).append('\n');
        }
        return sb.toString();
    }

    public static final String buildRocket() {
        char[] wider = "../\\/\\/\\/\\..".toCharArray();
        char[] narrower = "..\\/\\/\\/\\/..".toCharArray();
        char[] cone = "    //////\\\\\\\\\\\\    ".toCharArray();
        char[] boundary = "+=*=*=*=*=*=*+\n".toCharArray();

        StringBuilder sb = new StringBuilder();
        sb.append(buildLines(' ', cone, 5, '*', 0, Direction.FORWARD, 5, 1));
        sb.append(boundary);
        sb.append(buildLines('|', wider, 3, NONE, 0, Direction.FORWARD, 3, 2));
        sb.append(buildLines('|', narrower, 3, NONE, 2, Direction.BACKWARD, 3, 2));
        sb.append(boundary);
        sb.append(buildLines('|', narrower, 3, NONE, 2, Direction.BACKWARD, 3, 2));
        sb.append(buildLines('|', wider, 3, NONE, 0, Direction.FORWARD, 3, 2));
        sb.append(boundary);
        sb.append(buildLines(' ', cone, 5, '*', 0, Direction.FORWARD, 5, 1));
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(buildRocket());
    }

}

My particular concerns are the number of parameters I have going to the inner methods. How can those be rationalized? Should they be? What mechanisms can be used to simplify the interfaces?


texts: Dynamic module import in Python with exception handling

texts:
import nltk

req_modules = {'from nltk import punkt': 'punkt',
               'from nltk.corpus import stopwords': 'stopwords',
               'from nltk import pos_tag': 'averaged_perceptron_tagger',
               'from nltk import ne_chunk': 'maxent_ne_chunker'}

for m in req_modules:
    try:
        print("Trying: '%s'" % m)
        exec(m)    # try to import the package
        print("Success.")
    except (LookupError, ImportError):
        # if data not found (not already installed), download it
        print("Tried: %s. Resource '%s' was not available \
              and is being downloaded.\n" % (m, req_modules[m]))
        nltk.download(req_modules[m])
        exec(m)

I have some code I'm distributing to folks at work, and the lines above are at the top of the file. In order to run the code underneath (which harnesses several subpackages in nltk), the user needs to have downloaded these subpackages. Is this is safe/reliable way of doing dynamic module import? It has worked for me thus far.


texts:
Problem Statement

  Suppose you have a string \$S\$ which has length \$N\$ and is indexed from \$0\$ to \$N−1\$. String \$R\$ is the reverse of the string \$S\$. The string \$S\$ is funny if the condition \$|S_i−S_{i−1}|=|R_i−R_{i−1}|\$ is true for every \$i\$ from \$1\$ to \$N−1\$.

  (Note: Given a string \$str\$, \$str_i\$ denotes the ascii value of the \$i\$th character (0-indexed) of \$str\$. \$|x|\$ denotes the absolute value of an integer \$x\$)

Example

is_funny("acxz") returns True

is_funny("bcxz") returns False

Solution

def is_palindrome(ary):
    return ary == ary[::-1]

def create_difference_list(s):
    res = []
    for i in range(1, len(s)):
        res.append(abs(ord(s[i]) - ord(s[i-1])))
    return res

def is_happystr(s):
    return is_palindrome(create_difference_list(s))

Notes

Have used slow version of palindrome check assuming string is not going to be too long. Hope it doesn't affect performance that much.
Approached problem via functional style, could have done all the computation in the same loop but is it a good practice?


texts: Project Euler 18/67: Maximum Sum from Top to Bottom of the Triangle

texts:
This is my attempt at Project 18/67 of Project Euler. You can see the problem information, and obtain the needed txt file from here.

I had some help with the split function, and help on how to use an vector to do this. I would love any other feedback on this code.

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>

//function by jesyspa
std::vector<int> split(std::string line){
    std::stringstream ss (line);
    std::vector<int> result;
    std::string num;
    while(std::getline(ss, num, ','))
        result.push_back(std::stoi(num));
    return result;
}
int main(){

    std::vector<std::vector<int>> grid;

    //inputing triangle fule
    std::ifstream nums;
    nums.open("triangle.txt");
    std::string row;
    //Calling function, and pushing back into the vector
    while(std::getline(nums, row, '\n')){
        grid.push_back(split(row));
    }
    //term is one shorter then grid
    int term = grid.back().size() - 1;

    //This loop add's the larger of two bottom numbers, with the number above the first of the two.
    for(int a = term; a >= 1; a--){
        for(int b = 0; b <= a; b++){
            if(grid[a][b] > grid[a][b+1]){
                grid[a-1][b] += grid[a][b];
            }
            else{
                grid[a-1][b] += grid[a][b+1];
            }
        }
    }
    //Our answer
    std::cout << grid[0][0];
}


texts: its doing multiple nested for loop. How to reduce to 1?

texts:
I am writing one logic to iterate numbers first and then additional logic to putting them into particular subset of array.

What does this code do:

Code accept first $n
It creates an array of $n number from 1 to $n
Then started converting to subset of $main_array to possible one like
['1'] [1,2] [1,2,3] [2] [2,3] [3] etc. same like this
After creating subset i am counting those some subset which satisfy condition
Condition is xyz[0] should not come in subset with abc[0] and xyz[i] should not come in subset abc[i]. Example 2 and 3 is coming subset then don't count that subset, same 1 and 4 is coming then don't count.

Here is my nested for loop:

$n = 1299;
$main_array = range(1,$n);
$counter = 0;
$count = sizeof($abc);  // $abc and $xyz size will same always.
$abc = [2,1];
$xyz = [3,4];

for ($i=0; $i <$n; $i++) {
         for($j = $i;$j < $n; $j++){
            $interval_array = array();
          for ($k = $i; $k <= $j; $k++){
                array_push($interval_array,$main_array[$k]);
          }
           $counter++;
           for ($l=0; $l < $count ; $l++) {
                //if block here to additional condition using in_array() php function. which do $counter--
                if(in_array($abc[$l], $interval_array) &&
                 in_array($xyz[$l], $interval_array)){
                     $counter--;
                     break;
                 }
             }
         }
    }

$main_array I have to create on the spot after receiving $n values.

Following is cases:

when running $n = 4 its run in 4s
when running $n = 1200 or 1299 or more than 1000 its run in 60s-123s

Expected execution timing is 9s. I reduce from 124s to 65s by removing function calling inside for loop but it's not coming to point.

Expectation of code is if I have an array like:

$array = [1,2,3];

Then subset need to generate:

[1],[1,2],[1,2,3],[2],[2,3],[3]

Any help in this?


texts: Don't include root directory in HTML tree

texts:
I've written a function to create an HTML tree from JSON.

async function traverseTree (list, node) {
  const li = document.createElement('li')
  if (node.kids) {
    const
      ul = document.createElement('ul'),
      span = document.createElement('span')
    span.innerText = node.name
    li.appendChild(span)
    li.appendChild(ul)
    list.appendChild(li)
    for (const kid of node.kids) {
      traverse(ul, kid)
    }
    return list
  }
  li.innerText = node.name
  list.appendChild(li)
  return list
}

;(async function(){
  const
    tree = await readJson('./tree.json'),
    list = document.createElement('ul'),
    output = await traverseTree(list, tree)
  console.log(output)
})()

The issue is that I don't want to display the root node in the HTML tree since it is already displayed elsewhere, therefore I modified the code to exclude it.

async function traverseTree (list, node, isNotRoot) { // additional parameter
  const li = document.createElement('li')
  if (node.kids) {
    let ul = list                                     // now let
    if (isNotRoot) {                                  // additional conditional
      const span = document.createElement('span')
      ul = document.createElement('ul')               // additional assignment of value
      span.innerText = node.name
      li.appendChild(span)
      li.appendChild(ul)
      list.appendChild(li)
    }
    for (const kid of node.kids) {
      traverseTree(ul, kid, true)                     // additional argument
    }
    return list
  }
  li.innerText = node.name
  list.appendChild(li)
  return list
}

I'm wondering if there is a better, cleaner way to go about this?


texts: Set same color as prev row if data matches otherwise different color

texts:
I have a requirement in which I need to set color of two or more rows of a table same if they have same value in cell one and I have to maintain this alternatively i.e. no 3 or 4 rows should have the same color unless there cell value is same.

I have written following code but I don't like it that much as it seems dirty.

function SetGroupingDetails(row, item, color, namedColor) {
  $(row)
    .css("background-color", color) //set different color for different groups
    .addClass(namedColor);
}

$("#tblExport tbody tr").each(function() {
  var item = $("td:first", this).text();

  var prev = $(this).prev();

  if (prev.length > 0) {
    var prevItem = prev.find('td:first').text();

    if (prevItem == item) {
      if (prev.hasClass('Green'))
        SetGroupingDetails(this, item, "#009933", "Green");
      else
        SetGroupingDetails(this, item, "#cc9900", "Orange");
    } else {
      if (prev.hasClass('Orange'))
        SetGroupingDetails(this, item, "#009933", "Green");
      else
        SetGroupingDetails(this, item, "#cc9900", "Orange");
    }
  } else
    SetGroupingDetails(this, item, "#009933", "Green");
});
#tblExport body {
  font: normal medium/1.4 sans-serif;
}
#tblExport {
  border-collapse: collapse;
  width: 100%;
}
#tblExport th,
td {
  padding: 0.25rem;
  text-align: left;
  border: 1px solid #ccc;
}
#tblExport th {
  background: #bfbfbf;
}

        Item No.

        Item Name

        10178601

        X

        10178601

        X

          40062595

          Y

          40062595

          Y

          80214549

          Z

          80214549

          Z

Any suggestions?


texts: Priority scheduling algorithm using std::vector

texts:
I'm learning priority scheduling algorithm and trying to implement it using std::vector. But the current performance of my code that's partially implemented is not that good since I'm performing sort operation every time I add a new process to std::vector list. Can somebody suggest ways I can improve my current partially implemented algorithm. This is my code:
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>

void print_list(const std::vector<std::pair<int, int>>& pair_list) {
    for (const auto& pa : pair_list)
        std::cout << "process_ID: " << pa.first << ", " << "priority: " << pa.second << "\n";
    std::cout << std::endl;
}

void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list) {
    pair_list.emplace_back(pro_ID, pro_pri);

    std::sort(pair_list.begin(), pair_list.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) {
        return a.second < b.second;
    });
}

bool check_pro_is_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list) {
    for (const auto& pa : pair_list) {
        if (pa.first == pro_ID)
            return true;
    }

    return false;
}

bool is_higher_pri_pro_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list) {
    if (pair_list.front().first == pro_ID)
        return false;

    return true;
}

int main() {
    std::vector<int> process_ID_list { 1345, 45, 5646, 52525, 55757, 23424, 68696, 55878, 667, 252 };
    std::vector<int> process_pri_list { 41, 334, 747, 41, 47, 7, 75, 544, 42, 6 };

    std::vector<std::pair<int, int>> pair_list;
    for (int i = 0; i < process_ID_list.size(); ++i) {
        int new_pro_ID = process_ID_list.at(i);
        int new_pro_pri = process_pri_list.at(i);

        if (!check_pro_is_present(new_pro_ID, pair_list))
            add_pro(new_pro_ID, new_pro_pri, pair_list);
        else
            std::cout << "process is already in list" << std::endl;

        print_list(pair_list);
    }

    int query_pro_ID = 1345;
    std::cout << std::boolalpha << is_higher_pri_pro_present(query_pro_ID, pair_list) << std::endl;

    return (EXIT_SUCCESS);
}


texts: Minimum Sum Path of Pyramid with Data Structures

texts:
I have a program that uses ArrayLists to store a pyramid that has been read by a txt file and calculates the minimum sum value of travelling from the top of the pyramid to the bottom.

My code's main method is like this:

File file1 = new File(args[0]);
Scanner reader = new Scanner(file1); // The Scanner that is going to read file1.
try {
    int pyramidSize = reader.nextInt();
    System.out.println("Pyramid Size = " + pyramidSize);
    ArrayList<ArrayList <Integer>> solution1List = new ArrayList<ArrayList <Integer>>(pyramidSize);

    // Reads all integers to an array list.
    for(int i = 0; i < pyramidSize; i++) {
        solution1List.add(new ArrayList<Integer>());
    }
    int row = 0;
    int ctr = 0;
    int rowCounter = 1;

    while(reader.hasNext()) {

        if(reader.hasNextInt()) {

            while(row < rowCounter) {
                int temporaryForSolution1Integer = reader.nextInt();
                solution1List.get(ctr).add(temporaryForSolution1Integer);
                row++;
            }
            row = 0;
            ctr++;
            rowCounter++;
        }
        else {
            reader.next();
            row++;
        }
    }

    System.out.println("Triangle size is = " + solution1List.size());
    System.out.println("The minimum sum path is = " + minimumSumPath(solution1List));

And my method for calculating the sum is like this:

public static int minimumSumPath(ArrayList<ArrayList<Integer>> triangle) {

    if (triangle.size() == 0)
        return 0;

    int size = triangle.size();
    int min = Integer.MAX_VALUE;

    int[] sum = new int[size];
    sum[0] = triangle.get(0).get(0);

    for(int current = 1; current <= size - 1; current++) {
        int next_size = triangle.get(current).size();

        for(int next = next_size - 1; next >= 0; next--) {
            if (next == 0) { // Sum[0] gets done by walking the leftmost direct way.
                sum[0] = sum[0] + triangle.get(current).get(next);
            }
            else if (next == (next_size - 1)) { // Reaches to the rightmost element of that iteration
                sum[next] = sum[next-1] + triangle.get(current).get(next);
            }
            else { // Provides sum[next] to be the minimal sum that can come there
                sum[next] = Math.min(sum[next-1], sum[next]) + triangle.get(current).get(next);
            }
        }
    }

    for(int i = 0; i < size; i++) {
        if(sum[i] < min) {
           min = sum[i];
        }
    }
    return min;
}

My code is working properly. But I wonder if I can do this by implementing with a kind of Tree Data Structure (or other data structure but I thought maybe it could be done with a Tree but I couldn't figure which kind of Tree?). Any advice? I would appreciate any help and recommendation.


texts: Compute distance matrix using DTW acceptable for scipy.cluster.hierarchy

texts:
I am new to both data science and python. I have a dataset of the time-dependent samples, which I want to run agglomerative hierarchical clustering on them. I have found that Dynamic Time Warping (DTW) is a useful method to find alignments between two time series which may vary in time or speed.

I have found mlpy.dtw_std and scipy.cluster.hierarchy library in order to cluster my data using defined metrics.

My dataset is stored in pandas dataframe. The samples are waring in size, so there are nan value in the dataframe which should be ignored when computing mlpy.dtw_std.

To provide data for scipy.cluster.hierarchy.linkage(distanceMatrix, method='average') I need a distance matrix in the form of the 1d compressed distance matrix, where it must be a (n 2) sized vector where n is the number of original observations paired in the distance matrix.

Is there faster solution than following in order to compute distance matrix acceptable for scipy.cluster.hierarchy.linkage using Dynamic Time Warping distance?

dm = pdist ( ctl,lambda u,v: mlpy.dtw_std ( pd.Series(u).dropna(),pd.Series(v).dropna(),dist_only=True ))


texts:
I have this method inside a class that is responsible for setting up and executing a model:

public FlowJob PrepareAndScheduleFlowModelJob(string coordinates)
{
    GeometryCoordinateString coordinateString =
        new GeometryCoordinateString(coordinates);
    DataSet intersectedWatershedsDataSet =
        FindIntersectingWatersheds(coordinateString);
    List<string> xCoords = new List<string>();
    List<string> yCoords = new List<string>();
    List<string> ascFiles = new List<string>();
    string submitJobID = "fromServa" + new Random().Next().ToString();
    ProcessWatershedResults(intersectedWatershedsDataSet, xCoords, yCoords, ascFiles);
    ScheduleFlowJob(xCoords, yCoords, ascFiles, submitJobID);
    return new FlowJob(submitJobID);
}

It is a long running process so the client caller uses the FlowJob to poll status and get results.  The client itself doesn't care about any of the intermediate data and only wants to specify the input location for the model to run.

Every method that is called inside this method have their own unit tests already to ensure those work properly.

I know I can write an integration test ensuring that the entire thing in fact works.

I don't see anything here to unit test except that various methods are called.  Any suggestions?


texts:
I am currently in the process of completely rewriting an older Chess project and have written the main recurring function in the AI:

//Finds and applies the best move for the ai.
function aiTurn() {
//Recursive function. recurBoard is the board array passed to the function.
//Colour is either -1 or 1, -1 means it's calculating for black and 1, white.
//depth is simply how deep the recursion has gone.
var recur = function(recurBoard, colour, depth) {
    //Stops recurring when max depth is reached. Max is defined in index.html.
    if (depth === max) return getEvaluation(recurBoard);
    //Setting a baseline for the biggest value of all deeper moves.
    var mVal = -10000*colour;
    //Cycling through the entire board array.
    for (var i = 0; i < 64; i++) {
        //Defines unit as the numeric representation of the current board position
        //(EG. -5 is a black queen, 1 is a white pawn and 6 is a white king).
        var unit = recurBoard[i];
        //Checks to see if the unit is a pawn
        //(currently only have programmed pawn movement for the ai).
        if (unit*colour != 1) continue;
        //Makes an array of all the moves the specific unit can make
        //(formated like this: [[9,17],[9,25]]
        //This would be the moves of a pawn on square 9).
        var moves = getMoves(unit, i, recurBoard);
        //Loops through all the moves.
        for (var j = 0; j < moves.length; j++) {
            //Defines movToUnt as the unit the current move will move on top of.
            var movToUnt = recurBoard[moves[j][1]];
            //If moving on to a king simply return a massive advantage.
            if (movToUnt === -6*colour) return 9000*colour;
            //Recurs. move(from,to,board) returns a board after a given move.
            var val = recur(move(moves[j][0], moves[j][1], recurBoard), -colour, depth+1);
            //Checks to see if the value of the move is bigger than that of the current best move
            if (val*colour > mVal*colour) mVal = val;
        }
    }
    //Returns the value of the best move.
    return mVal;
}

//This next part does pretty much the same thing as the for loop above, but stores the values.
var aiMoves = []
for (var i = 0; i < 64; i++) {
    var u = board[i];
    if (-u*playerSide != 1) continue;
    var uMoves = getMoves(u, i, board);
    for(var j = 0; j < uMoves.length; j++) {
        if (board[uMoves[j][1]] === 6*playerSide) {         //Shouldn't be necessary.
            uMoves[j][2] = -9000*playerSide;                //
            aiMoves[aiMoves.length] = uMoves[j];            //
            continue;                                       //
        }                                                   //
        uMoves[j][2] = recur(move(uMoves[j][0], uMoves[j][1], board), playerSide, 0);
        aiMoves[aiMoves.length] = uMoves[j];
    }
}
return aiMoves;
}

This properly recurs up to a given depth, but this gives the Chess AI the infamous "horizon effect" where it will make stupid decisions because it doesn't calculate far enough. This can be fixed simply by telling it to not stop recurring if it just killed a piece in its simulation.


texts:
I had a requirement where I need to create object using same interface but one derived class expects simple data and other array of type. Here is solution I came up with:

I had two questions:

As you can see I am converting IEquatable<T> into T. In my testing so far I did not see any disasters. Can you think of any from top off your head?
Is there a way I can change constraint in ArrayExpectant::CloneFromMe to ArrayWrapper instead of IEquatable?

public class ArrayWrapper<T> : IEquatable<T>
{
    public T[] Array { get; set; }

    public bool Equals(T other) { return false;  }
    public bool Equals(T[] other) { return Array == other; }
    public bool Equals(ArrayWrapper<T> other) { return Array == other.Array; }
}

public interface ICreationByCloning
{
    ICreated CloneFromMe<TClone>(IEquatable<TClone> t) where TClone : IEquatable<TClone>;
}

public interface ICreated { }

public class Simpleton<T> : ICreated, ICreationByCloning
{
    public Simpleton(T t) { }
    public ICreated CloneFromMe<TClone>(IEquatable<TClone> t) where TClone : IEquatable<TClone>
    {
        return new Simpleton<TClone>((TClone)t);
    }
}

public class ArrayExpectant<T> : ICreated, ICreationByCloning where T : IEquatable<T>
{

    T[] Data { get; set; }
    public ArrayExpectant(T[] t) { Data = t; }
    public ICreated CloneFromMe<TClone>(IEquatable<TClone> t) where TClone : IEquatable<TClone>
    {
        TClone[] array = (t as ArrayWrapper<TClone>).Array;

        return new ArrayExpectant<TClone>(array);
    }
}


texts:
This is a simple rock-paper-scissors program implemented using C++. Any feedback or suggestions for improvement are welcome.

Code:

main.cpp:

#include <iostream>
#include <string>
#include "rock-paper-scissorss.h"
using namespace std;

void whoWon(string player_move, string computer_move){
    if(player_move == "rock"){
        if(computer_move == "paper")
            cout<<"You chose rock and the computer chose paper, the computer wins!"<<endl;

        else if(computer_move == "scissors")
            cout<<"You chose rock and the computer chose scissors, you win!"<<endl;

        else
            cout<<"You chose rock and the computer chose rock, it's a tie!"<<endl;
    }

    else if(player_move == "paper"){
        if(computer_move == "scissors")
            cout<<"You chose paper and the computer chose scissors, the computer wins!"<<endl;

        else if(computer_move == "rock")
            cout<<"You chose paper and the computer chose rock, you win!"<<endl;

        else
            cout<< "You chose paper and the computer chose paper, it's a tie!"<<endl;
    }

    else{
        if(computer_move == "rock")
            cout<<"You chose scissors and the computer chose rock, the computer wins!"<<endl;

        else if(computer_move == "paper")
            cout<<"You chose scissors and the computer chose paper, you win!"<<endl;

        else
            cout<<"You chose scissors and the computer chose scissors, it's a tie!"<<endl;
    }
}

int main(int argc, char** argv) {
  \
  char play_again = 'y';
  cout<<"Please enter your name: "<<endl;
  string name;
  getline(cin,name);
  cout<<"Hello "<<name<<", welcome to Rock-Paper-Scissors!"<<endl;

    Player player_1(name);
  while(play_again == 'y'){

    cout<<"Please enter the move you wish to make: "<<endl;
    string move;
    getline(cin,move);
    while(1){
        if((move == "rock") || (move == "paper") || (move == "scissors")){

            player_1.setMoveChoice(move);
            break;
        }

        else{
            cout<<"Invalid move choice! Please enter rock, paper, or scissors"<<endl;
            getline(cin,move);
        }
    }

    Computer com_1;
    com_1.setMoveChoice();

   string p_move = player_1.getMoveChoice();
   string c_move = com_1.getMoveChoice();

   whoWon(p_move,c_move);

   cout<<"Would you like to play again?(y/n)"<<endl;

   cin>>play_again;
   cin.ignore();

    }

 return 0;
}

rock-paper-scissors.cpp:

#include "rock-paper-scissorss.h"
#include <cstdlib>

Computer :: Computer(){
    num_generated = rand() % 3 + 1;
}

void Computer ::  setMoveChoice(){
   if(num_generated == 1)
       move_selected = "rock";

   else if(num_generated == 2)
       move_selected = "paper";

   else
       move_selected = "scissors";

}

string Computer :: getMoveChoice(){
    return move_selected;
}

Player :: Player(string name){
    player_name = name;

}

void Player :: setMoveChoice(string choice){
    move_selected = choice;
}

string Player :: getMoveChoice(){
    return move_selected;
}

rock-paper-scissorss.h:

#ifndef ROCK_PAPER_SCISSORSS_H
#define ROCK_PAPER_SCISSORSS_H

#include <iostream>
#include <string>
using namespace std;

class Computer{

private:
    int num_generated;
    string move_selected;

public:
    Computer();
    void setMoveChoice();
    string getMoveChoice();

};

class Player{

private:
    string move_selected;
    string player_name;

public:
    Player(string);
    void setMoveChoice(string move);
    string getMoveChoice();

};

#endif /* ROCK_PAPER_SCISSORSS_H */


texts:
I'm currently using Backbone to generate a carousel slider.  In my View, I have an initialize function that looks like this:

var SlideModel = Backbone.Model.extend({
    defaults: {
        id: null,
        source_url: null,
        date: null,
        slug: null,
        link: null
    },
    idAttribute: '_id'
});

var SlideCollection = Backbone.Collection.extend({
    model: SlideModel,
    url: 'https://www.usarugby.org/wp-json/posts?filter[category_name]=Club',
    parse: function(response){
        return response;
    }
});

var SlideView = Backbone.View.extend({
    el: '#hero-wrapper',
    className: 'carousel-cell',
    template: _.template( $('#tmpl-hero-slides').html() ),
    initialize: function(){
        this.listenTo(this.collection, 'update', this.render);
        this.listenTo(this.collection, 'update', this.afterRender);
        this.listenTo(this.collection, 'update', this.scaleSlider);
        this.listenTo(this.collection, 'update', this.correctDate);
    },
    render: function(){
        this.$el.html(this.template({
            slides: this.collection.toJSON()
        }));
        return this;
    },
    afterRender: function() {
        var $carousel = $('#hero'),
            $win = $(window);

        $carousel.royalSlider({
            autoScaleSlider: !0,
            autoScaleSliderWidth: 1125,
            autoScaleSliderHeight: 593,
            controlNavigation: 'bullets',
            arrowsNav: !0,
            imageScaleMode: 'fill',
            imageAlignCenter: !0,
            numImagesToPreload: 5,
            sliderTouch: !0,
            autoplay: {
                enabled: !0,
                pauseOnHover: !0,
                delay: 4000
            },
            loop: !0,
            transitionType: rs.fadeOrMove(),
            navigateByClick: !0,
            allowCSS3: rs.cssOnDesk(),
            addActiveClass: !0
        });

        $carousel.removeClass('hide');

    },
    scaleSlider: function(){
        $('.royalSlider').royalSlider('updateSliderSize', true);
    },
    correctDate: function(){
        $('.royalSlider .rsSlide').each(function(){
            var str = $(this).find('.date').html(),
                slideDate = new Date( str );
            $(this).find('.date').html( slideDate.toDateString() );
        });
    }
});

var slidecollection = new SlideCollection(),
    slideshow = new SlideView({ collection: slidecollection });
slidecollection.fetch();
slideshow.render();

Is this the most efficient way to write the initialize function with each listener listening for the same event one after the other, or is there a better way to write the function?

I've added the entire Backbone script for my carousel. RoyalSlider is a third-party plugin that powers the carousel.


texts:
Here is the code I have written for a HackerRank challenge which takes multiple arrays, and attempts to determine if there exists an element in an array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero.

Detailed problem statement:

Input Format

The first line contains \$T\$, the number of test cases. For each test case, the first line contains N , the number of elements in the array \$A\$ . The second line for each test case contains N space-separated integers, denoting the array \$A\$.

Output Format

For each test case print YES if there exists an element in the array, such that the sum of the elements on its left is equal to the sum of the elements on its right; otherwise print NO.

It works fine, but it's definitely not an optimal solution, as it fails two test cases (time outs occur). Could anybody provide any insights on optimising it further?

T = int(input())
N = []
A = []

for i in range(T):
    #N.append(int(input()))
    N = int(input())
    arr = input().strip().split(' ')
    arr = list(map(int, arr))
    A.append(arr)
#print(A)
for i in A:
    count=0
    for j in range(len(i)):
        preSum = sum(i[0:j])
        postSum = sum(i[j+1:len(i)])
        if(preSum == postSum):
            count+=1
    if(count>0):
        print("YES")
    else:
        print("NO")


texts:
I wrote a C# program to remove non-ASCII characters in a text file, and then output the result to a .NonAsciiChars file.

The input file is in XML format. In fact, the data may all be on two lines, which is why I am not doing the replacement line by line. Instead, I'm using StreamReader.ReadToEnd().

The problem is, the input file can be as big as 4 GB. When this happens, I'm getting the following OutOfMemoryException:

DateTime:2014-08-04 12:55:26,035 Thread ID:[1] Log Level:ERROR Logger Property:OS_fileParser.Program property:[(null)] - Message:System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at System.Text.StringBuilder.ExpandByABlock(Int32 minBlockCharCount)
   at System.Text.StringBuilder.Append(Char* value, Int32 valueCount)
   at System.Text.StringBuilder.Append(Char[] value, Int32 startIndex, Int32 charCount)
   at System.IO.StreamReader.ReadToEnd()
   at OS_fileParser.MyProgram.FormatXmlFile(String inFile) in D:\Test\myProgram.cs:line 530
   at OS_fileParser.MyProgram.Run() in D:\Test\myProgram.cs:line 336

Line 530 contains content = Regex.Replace(content, pattern, "");, while line 336 calls a method with the following body:

const string pattern = @"[^\x20-\x7E]";

string content;
using (var reader = new StreamReader(inFile))
{
    content = reader.ReadToEnd();
    reader.Close();
}

content = Regex.Replace(content, pattern, "");

using (var writer = new StreamWriter(inFile + ".NonAsciiChars"))
{
    writer.Write(content);
    writer.Close();
}

using (var myXmlReader = XmlReader.Create(inFile + ".NonAsciiChars", myXmlReaderSettings))
{
    try
    {
        while (myXmlReader.Read())
        {
        }
    }
    catch (XmlException ex)
    {
        Logger.Error("Validation error: " + ex);
    }
}

How can I improve the memory footprint of my code?


texts: HTML  elements word spacing using jQuery

texts:
I'm doing a hobby project for fun recently, it's a GitHub webpage using Jekyll.
One of the main component of my site is displaying Chinese characters with their Sino-Vietnamese pronunciation. I use <ruby> elements to render these texts, for those who don't know, you can read its MDN docs
The problem with that is word spacing is broken when a <rt> element is longer than its associated <rb> element. So I created a jQuery function to dynamically adjust spacing.
A minimal example here:

const stdSpace = "1em"; // for ruby annotation spacing
$(function () {
    $("rb").each(rubyAdjust);
});
function rubyAdjust(i, el) { // for each ruby base
    const rbW = $(el).width(), // take its width
          rtW = $(el).next("rt").width(), // its associated ruby text width
          diff = (rtW - rbW).toFixed(0), // excess amount
          addSpace = diff > 0
                     ? `calc(${stdSpace} + ${diff.toString()}px)`
                     : stdSpace;
    $(el).css("margin-right", addSpace);
}
rb {
    display: inline-block /* fluid word spacing with margin using JS */
}

rt {
    text-align: left /* to work together with rb margin */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ruby>
    <rb>是</rb><rt>Thị</rt>
    <rb>故</rb><rt>cố</rt>
    <rb>空</rb><rt>không</rt>
    <rb>中</rb><rt>trung</rt>
</ruby>

My function rubyAdjust works as expected, but becomes a UI blocking point when I have a very long text. For a full fledged example, you can visit a page of my project which shows the Diamond Sutra.
So what I want is to improve the rendering speed:

Is there a better way to adjust word spacing of <ruby>? The official docs of <ruby> doesn't have much, maybe because the feature is still uncomplete and fews people are using it?
I've also searched for a multi thread execution of jQuery, but it seems like DOM manipulation isn't possible. Do you guys have any idea?

Many thanks,


texts: Max depth of tree when all parent pointers are provided

texts:
Request for optimization, good practices, recommendations.

class NodeMaxDepth {

    private final NodeMaxDepth parent;

    public NodeMaxDepth (NodeMaxDepth parent) {
        this.parent = parent;
    }

    public NodeMaxDepth getParent() {
        return parent;
    }
}

    /**
     * Given a list of nodes with parent pointers,
     * calculate the max depth of tree from the root.
     */
    public final class MaxDepth {

        private MaxDepth ( ) { }

        public static int maxDepth (List<NodeMaxDepth> nodes) {
            if (nodes.size() == 0) { throw new IllegalArgumentException("List of nodes is empty."); }

            final Map<NodeMaxDepth, List<NodeMaxDepth>> parentChild = new HashMap<NodeMaxDepth, List<NodeMaxDepth>>();
            NodeMaxDepth parent = null;

            for (NodeMaxDepth node : nodes) {
                if (node.getParent() == null) parent = node;

                if (!parentChild.containsKey(node.getParent())) {
                    List<NodeMaxDepth> count = new ArrayList<NodeMaxDepth>();
                    parentChild.put(node.getParent(), count);
                }
                parentChild.get(node.getParent()).add(node);
            }

            if (parent == null) {
                throw new IllegalArgumentException("The graph should be acyclic.");
            }

            return height (parentChild, parent);
        }

        private static int height (Map<NodeMaxDepth, List<NodeMaxDepth>> parentChild, NodeMaxDepth parent) {
            assert parentChild != null;
            assert parent != null;

            final List<NodeMaxDepth> childList = parentChild.get(parent);

            if (childList == null) return 0;

            int maxCount = 0;
            for (NodeMaxDepth child : childList) {
                int height = height(parentChild, child);
                if (height > maxCount) {
                    maxCount = height;
                }
            }
            return maxCount + 1;
        }

        public static void main(String[] args) {
            NodeMaxDepth root = new NodeMaxDepth(null);
            NodeMaxDepth nodeLeft = new NodeMaxDepth(root);

            NodeMaxDepth nodeRight = new NodeMaxDepth(root);
            NodeMaxDepth nodeRightRight = new NodeMaxDepth(nodeRight);
            NodeMaxDepth nodeRightRightRight = new NodeMaxDepth(nodeRightRight);

            List<NodeMaxDepth> nodes = new ArrayList<NodeMaxDepth>();
            nodes.add(root);
            nodes.add(nodeLeft);
            nodes.add(nodeRight);
            nodes.add(nodeRightRight);
            nodes.add(nodeRightRightRight);

            System.out.println("Expected 3, Actual: " + maxDepth (nodes));
        }
    }


texts: SSH autokiller for connections from other systems

texts:
I was messing around with ssh and decided to write a python program that scans for any connections that aren't from the system, then terminates them. It works well for many connections from my iMac to my MacBook. A more in-depth explanation of the program is written at the top of the code. I'd appreciate feedback on any nitpicks you can find, since I threw this together in about thirty minutes. Any and all feedback is appreciated and considered.

scanner.py

""" Import Statements """
import os
import subprocess
import time

"""

Objective: Scan all connections to this computer, every two seconds, and if any are not
system, as in not `console` or `s000`, find the PID associated with the connection,
then terminate the connection with `kill -9 ...`

"""

def format_pid(text):
    """
    Formats the output to only include PIDS that are not from the system
    """
    ids = text.split("\n")
    all_ids = []
    del ids[0] #removes uptime stuff
    for line in ids:
        pid = line[:13]
        if pid[12:] != '0':
            all_ids.append(pid[:5])
    return all_ids

def get_pids():
    """ Returns all users logged into the computer """
    return format_pid(subprocess.Popen(['ps'], stdout=subprocess.PIPE).communicate()[0])

def kill():
    """ Terminates all processes that are not system """
    processes = get_pids()
    for process in processes:
        if process: # Makes sure process isn't null/empty
            os.system('kill -9 ' + process)
            print("KILLED CONNECTION PROCESS: " + process)

    time.sleep(2)
    kill()

if __name__ == '__main__':
    kill()


texts: Is there a more efficient way of implementing this clock in Raphael JS?

texts:
Can someone let me know if this is a proper (and efficient) way of doing it? It works, but I wanted to understand if there's a way it be made better (I can use a for loop for the clones, but my browser gets stuck if I do it).

Here's the fiddle

window.onload = function() {
  rot();
}
var rot = function(){
var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
var c1 = paper.circle(250,250,150).attr({"stroke-width":2});
var c2 = paper.circle(250, 250, 5).attr({"fill":"black"});
var lMark = paper.path("M 250 250 m 0 -130 l 0 -20").attr({"stroke-wid th":2});
lMark.clone().attr({transform:"r90 250 250"});
lMark.clone().attr({transform:"r180 250 250"});
lMark.clone().attr({transform:"r270 250 250"});
lMark.clone().attr({transform:"r360 250 250"});
var d = new Date();
var hourAngle = (d.getHours() * 60 + d.getMinutes())/2, minAngle = (d.getMinutes() * 6), secAngle = (d.getSeconds() * 6);
var secHand = paper.path("M 250 250, l 0 -110, M 250 250, l 0 15").attr({"stroke":"red", "stroke-width":2});
var minHand = paper.path("M 250 250, l 0 -120").attr({'stroke-width':2}).transform("r" + minAngle + " 250 250");
var hourHand = paper.path("M 250 250, l 0 -80").attr({'stroke-width':3, 'stroke-linecap':'round'}).transform("r" + hourAngle + " 250 250");
var secAnim = Raphael.animation({transform: "r360 250 250"}, 60000).repeat(Infinity);
var minAnim = Raphael.animation({transform: "r360 250 250"}, 3600000).repeat(Infinity);
var hourAnim = Raphael.animation({transform: "r360 250 250"}, 43200000).repeat(Infinity);
secHand.animate(secAnim);
minHand.animate(minAnim);
hourHand.animate(hourAnim);
}


texts:
I created this based on this website which calculates IP address information such as hosts, netmasks etc.

I'm quite new to C and I'm still grasping the idea of the whole array and pointers and bit manipulations. Code works the way I want it to work but I'd like to improve this. I would like to know how I did as well as what are some things I can look out for when programming in C.

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

#define B1 0
#define B2 1
#define B3 2
#define B4 3
#define CIDR 4

void ConvertIpToInt(char address[], int address_block[]);

int main(int argc, char** argv) {

    int address_block[4], netmask_block[4];

    char address[] = "128.42.0.0/25";

    ConvertIpToInt(address, address_block);

    char literal_netmask_bin[32];
    int bit_counter, net_bit_counter = 0;
    while (bit_counter != 33) {
        while (net_bit_counter != address_block[CIDR]) {
            literal_netmask_bin[bit_counter] = '1';
            net_bit_counter += 1;
            bit_counter += 1;
        }
        literal_netmask_bin[bit_counter] = '0';
        bit_counter += 1;
    }

    int i, block_counter, sqN_value, sqN = 0;
    bit_counter = 0;
    for (i = 0; i < 33; i++) {
        bit_counter += 1;
        if (literal_netmask_bin[i] == '1') {
            sqN_value += pow(2, 7 - sqN);
        }
        sqN += 1;
        if (bit_counter == 8) {
            netmask_block[block_counter] = sqN_value;
            bit_counter = 0;
            sqN = 0;
            sqN_value = 0;
            block_counter += 1;
        }
    }

    int wildcard_netmask_block[4];
    i = 0;
    for (i = 0; i < 4; i++) {
        wildcard_netmask_block[i] = ~netmask_block[i] & 0xFF;
    }

    printf("> [GENERAL]\n\n");
    printf("Address:---------------------> %d.%d.%d.%d\n", address_block[B1], address_block[B2], address_block[B3], address_block[B4]);
    printf("Network Mask:----------------> %d.%d.%d.%d => %d\n", netmask_block[B1], netmask_block[B2], netmask_block[B3], netmask_block[B4], address_block[CIDR]);
    printf("Wildcard Mask:---------------> %d.%d.%d.%d\n", wildcard_netmask_block[B1], wildcard_netmask_block[B2], wildcard_netmask_block[B3], wildcard_netmask_block[B4]);
    printf("Network Address:-------------> %d.%d.%d.%d\n", address_block[B1] & netmask_block[B1], address_block[B2] & netmask_block[B2], address_block[B3] & netmask_block[B3], address_block[B4] & netmask_block[B4]);
    printf("Broadcast Address:-----------> %d.%d.%d.%d\n", wildcard_netmask_block[B1] | address_block[B1], wildcard_netmask_block[B2] | address_block[B2], wildcard_netmask_block[B3] | address_block[B3], wildcard_netmask_block[B4] | address_block[B4]);
    printf("Minimum Usable Address:------> %d.%d.%d.%d\n", address_block[B1] & netmask_block[B1], address_block[B2] & netmask_block[B2], address_block[B3] & netmask_block[B3], (address_block[B4] & netmask_block[B4]) + 1);
    printf("Maximum Usable Address:------> %d.%d.%d.%d\n", wildcard_netmask_block[B1] | address_block[B1], wildcard_netmask_block[B2] | address_block[B2], wildcard_netmask_block[B3] | address_block[B3], (wildcard_netmask_block[B4] | address_block[B4]) - 1);
    printf("Number of Hosts:-------------> %d\n", (int) pow(2, 32 - address_block[CIDR]) - 2);
    printf("Total Hosts:-----------------> %d\n\n", (int) pow(2, 32 - address_block[CIDR]));
}

void ConvertIpToInt(char address[], int address_block[]) {
    char * pch;
    char delimeters[] = "./";
    pch = strtok(address, delimeters);
    int i = 0;
    while (pch != NULL) {
        address_block[i] = strtol(pch, NULL, 10);
        i += 1;
        pch = strtok(NULL, delimeters);
    }
}


texts: Generate binary image using coordinate vectors

texts:
I have a matrix M of size [n_rows, n_cols] and a list of x and y pixel coordinates. I use these coordinates to draw a binary image. Here is my code:
std::vector<std::vector<double>> x;
std::vector<std::vector<double>> y;

// fill x and y

std::vector<std::vector<unsigned int>> M(n_rows, std::vector<unsigned int>(n_cols));

std::vector<std::vector<double>>::const_iterator iter_row_x = x.begin();
std::vector<std::vector<double>>::const_iterator iter_row_y = y.begin();

for (; iter_row_x != x.end(); ++iter_row_x, ++iter_row_y) {
    std::vector<double>::const_iterator iter_col_x = iter_row_x[0].begin();
    std::vector<double>::const_iterator iter_col_y = iter_row_y[0].begin();
    for (; iter_col_x != iter_row_x[0].end(); ++iter_col_x, ++iter_col_y) {
        unsigned int i = unsigned int(*iter_col_x);
        unsigned int j = unsigned int(*iter_col_y);
        M[i][j] = 1;
    }
}

I would like to know if there is a more elegant way to achieve this? My code above looks a bit bulky and error-prone for such a simple task.


texts: Work command handler for an economy system

texts:
I have been working on this code, which is the part of an economy system that handles the work command. This lets the user pick a role and if they have enough level then they will get it by updating a db.

I know it's inefficient and I am unsure how to reduce the if count and keeping a cyclomatic complexity below 15. I need to add 8 more jobs but I can't add anymore.

How can I reduce the if count?
What else have I done wrong?

The code I have been working on

  @job.command()
  async def apply(self,ctx,*,selection:str):
    a = banned(ctx.author.id,self.bot.blacklisted)
    if a is True:
      return await ctx.send("You are blacklisted from using this command.")
    db = client.bot
    posts = db.user
    for x in posts.find({"guildid":f"{ctx.guild.id}","id":f"{ctx.author.id}"},{ "_id": 0,"job":1,"level":1}):
      level = int(x["level"])
    if selection.lower() == "garbage collector" and level >= 0:
      posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Garbage Collector","income":50}})#save
    elif selection.lower() == "cleaner" and level >= 7:
      posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Cleaner","income":70}})#save
    elif selection.lower() == "car washer" and level >= 16:
      posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Car Washer","income":105}})#save
    elif selection.lower() == "maid" and level >= 27:
      posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Maid","income":145}})#save
    elif selection.lower() == "receptionist" and level >= 36:
      posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Receptionist","income":185}})#save
    else:
      return await ctx.send(f"You are currently {level}, please go to school using ?learn")
    await ctx.send(f"You are now working as a {selection.lower()}")

The pymongo document format

"id":f"{message.author.id}"
"name":f"{message.author.name}"
"guildid":f"{message.guild.id}"
"cash":0
"job":"Homeless"
"balance":0
"shares":0
"level":0
"income":0


texts:
I'm new to programming. I tried to find a way to convert numbers into letters with Python. I would like to receive some advice to improve myself. This program works for numbers between 1 and 106  and I would like to know how the logic of the program can be improved.

def changeNumberIntoLetter(value):
    number=numToLetter(value)
    return number

def numToLetter(value): #The function converts the numbers into letters.
    if value==1: return 'one'
    elif value==2: return 'two'
    elif value==3: return 'three'
    elif value==4: return 'four'
    elif value==5: return 'five'
    elif value==6: return 'six'
    elif value==7: return 'seven'
    elif value==8: return 'eight'
    elif value==9: return 'nine'
    elif value==10: return 'ten'
    elif value==11: return 'eleven'
    elif value==12: return 'twelve'
    elif value==13: return 'thirteen'
    elif 13<value<=19: return composeTeen(value)
    elif value>19:
        if value==20: return 'twenty'
        elif value==30: return 'thirty'
        elif value==50: return 'fifty'
        elif value==10**2: return 'one hundred'
        elif value==10**3: return 'one thousand'
        elif value==10**5: return 'one hundred thousand'
        elif value==10**6: return 'one milion'
        elif value>=20: return composeNumbers(value)
        else: exit('Out of range')
    else: return ''

def composeNumbers(value):   #The function build every number biger than 40
    if 40<=value<10**2:
        value1=int(str(value)[0])
        value2= int(str(value)[1])
        if value1==2:
           value1= 'twen'
           return value1 + 'ty' + '-' + numToLetter(value2)
        if value1==3:
           value1='thir'
           return value1 + 'ty' + '-' + numToLetter(value2)
        if value1==8:
            value1='eigh'
            return value1 + 'ty' + '-' + numToLetter(value2)
        elif value1==5:
            value1='fif'
            return value1 + 'ty' + '-' + numToLetter(value2)
        return numToLetter(value1) + 'ty' + '-' + numToLetter(value2)
    elif 10**2<=value<10**3:
        value1=int(str(value)[0])
        value2= int(str(value)[1:])
        return numToLetter(value1) + ' ' + 'hundred' + ' ' + numToLetter(value2)
    elif 10**3<=value<10**4:
        value1=int(str(value)[0])
        value2=int(str(value)[1:])
    elif 10**4<=value<10**5:
        value1=int(str(value)[0:2])
        value2=int(str(value)[2:])
    elif 10**5<=value<10**6:
        value1=int(str(value)[0:3])
        value2=int(str(value)[3:])
    return numToLetter(value1) + ' ' + 'thousand' + ' ' + numToLetter(value2)

def composeTeen(value): #The function takes the unit and then converts it into letter to build the word.
    value= int(str(value)[-1])  #It turns elem in string to take the last position and it converts it again in integer to change it in letters. Then it composes the word adding 'teen' at the end.
    value= numToLetter(value)
    if value=='five': value= 'fif'
    value= value + 'teen'
    return value


texts: How to write elegant conditional bits of markup in Razor views?

texts:
Suppose the following model:

public class ViewBookModel
{
    public string Title { get; set; }
    public string Subtitle { get; set; }
}

I'm currently rendering it like this in my Razor view:

@Model.Title

@if (Model.Subtitle != null)
{

@Model.Subtitle

}

My question is about the Subtitle bit. The above approach feels a little clunky, and can get repetitive (which is probably a bad sign) at times.

Are there any better, less verbose, more elegant ways to handle this situation?

I had considered (a) the option now mentioned in Mat's Mug's answer, as well as (b) moving the condition to the model:

public class ViewBookModel
{
    // ...
    public string ShowSubtitle {
        get { return string.IsNullOrEmpty(Subtitle); }
    }
}

With this change to the view:

@if (Model.ShowSubtitle)

However, that doesn't address my main issue: the verbosity (i.e. 4 lines of view code just to display Subtitle).


texts: LeetCode 862: Shortest Subarray with Sum at Least K

texts:
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem

Return the length of the shortest, non-empty, contiguous subarray of nums with sum at least k.
If there is no non-empty subarray with sum at least k, return -1.

Example 1:
Input: nums = [1], k = 1 Output: 1
Example 2:
Input: nums = [1,2], k = 4 Output: -1
Example 3:
Input: nums = [2,-1,2], k = 3 Output: 3
Note:

\$1 <= \text{nums.length} <= 50000\$
\$-10 ^ 5 <= \text{nums}[i] <= 10 ^ 5\$
\$1 <= k <= 10 ^ 9\$

Code
#include <vector>
#include <algorithm>
#include <deque>

class Solution {
public:
    static int shortestSubarray(std::vector<int> nums, const int k) {
        const int length = nums.size();
        int shortest = length + 1;

        std::deque<int> deque_indicies;

        for (int index = 0; index < length; index++) {
            if (index) {
                nums[index] += nums[index - 1];
            }

            if (nums[index] >= k) {
                shortest = std::min(shortest, index + 1);
            }

            while (!deque_indicies.empty() && nums[index] - nums[deque_indicies.front()] >= k) {
                shortest = std::min(shortest, index - deque_indicies.front());
                deque_indicies.pop_front();
            }

            while (!deque_indicies.empty() && nums[index] <= nums[deque_indicies.back()]) {
                deque_indicies.pop_back();
            }

            deque_indicies.emplace_back(index);
        }

        return shortest <= length ? shortest : -1;
    }
};

Problem

Solution

Discuss