texts:
I have a conf.inc.php file which has the following few lines.

// enable css using convention below:
// $css["pageName"] = ["cssName1", "cssName2", ...]
$css["all"]         = ["style"];
$css["myPage"]      = ["someStyle"];
$css["myOtherPage"] = ["otherStyle", "anotherStyle"];

// disable css
$exCss["myOtherPage"] = ["style"];

What this will do is give all of my pages the style.css. Then all the other keys of the index will give their respective page (e.g. "myPage.php" etc.) the styles listed in the array after the equals (e.g. "someStyle.css").

All of the styles are stored in a folder called "css" and there is no other place to store them as I have hard coded it in - this meant I didn't have to write relative paths in the multidimensional array.

The second array will exclude some styles from their respective page. In this instance the style called style.css is being excluded from the page named myOtherPage.php.

Note: The page names are from a function here. So they only read the file name and ignore extensions etc. This means that "myOtherPage" could also be "myOtherPage.php" or "myOtherPage.html". Although if you look at the following code they will have to be PHP see I use an include in my header of the PHP files.

// print css that are present in all pages
$a = (isset($css["all"])) ? count($css["all"]) : 0;
for ($i = 0; $i < $a; $i++)
    if ((isset($exCss["all"]) && !in_array($css["all"][$i], $exCss["all"])) || (isset($exCss["$page"]) && !in_array($css["all"][$i], $exCss["$page"])) || (!isset($exCss["all"]) || !isset($exCss["$page"])))
        echo (file_exists("{$css["all"][$i]}.css")) ? "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$css["all"][$i]}.css\" />" : "";

This code is part of header.inc.php and this gets placed inside the <head> tags. This will add all the styles from the array providing that style is not listed in the $exCss array.

It is common for me to make things more difficult than they need to be...
This could be another case of that. I also tend to make functions or processes that already exist.

Anyway, I thought I would share this little snippet. If anyone has anyway of improving it then I would love to hear it. Thanks as usual!


texts:
I feel that I am repeating myself a lot with this HTML/PHP code. Am I right, and is there a maintainable way of reducing the amount of repetition in the code?

mydomain/index.php:

<!DOCTYPE HTML>
<?php $root="/mywebdir"; ?>

<?php include("$root/inc/meta.php"); ?>
<meta name="description" content="Some description" />
<meta name="keywords" content="some,home,page,keywords" />
<title>Home - This Website</title>

<?php include("$root/inc/header.php"); ?>
<?php include("$root/inc/nav.php"); ?>

Home

Introduction.

Some content.

More content.

<?php include("$root/inc/footer.php"); ?>

mydomain/somedir/index.php:

<!DOCTYPE HTML>
<?php $root="/mywebdir"; ?>

<?php include("$root/inc/meta.php"); ?>
<meta name="description" content="Some description" />
<meta name="keywords" content="some,keywords,about,this,page" />
<title>Some Page - This Website</title>

<?php include("$root/inc/header.php"); ?>
<?php include("$root/inc/nav.php"); ?>

Some Page

Some content about this page.

<?php include("$root/inc/footer.php"); ?>


texts: Reformatting a structured string like "a-b-c|A-B-C" into "a-A|b-B|c-C"

texts:
The code below was inspired by this post in Code Review.
Here is how it was first intended by its author:

I have the following code that converts a string that looks like :

aaa-bbb|ccc-ddd|eee-fff

to two strings that look like

aaa|ccc|eeeandbbb|ddd|fff

Somebody already proposed an answer, and I found it could be more improved using reduce() and map() methods.
But after a few time I realized it could be made of more general use, so I hooked in the intent to have a code which both:

accept any main- and sub-separator (| and -) in the above example.
accept any number of main parts and sub-parts, the only (not checked) requirement being the number of sub-parts is the same through all parts.
is strictly written functional-programming style

Then I ended up with pretty different requirements than in the original post I cited, so rather than an answer I prefer to post it as a question, waiting for comments about:

is there a simpler strategy for doing that in functional style?
and even is it a good idea to use functional style, since it might be actually slower than with procedural code?

function reformat(string, mainSep, subSep) {
  return string.split(mainSep).map(item => item.split(subSep)).reduce(
    (result, part) =>
      part.map((str, index) =>
        `${result[index]}${mainSep}${str}`
      )
  ).join(subSep || ' ');
}

console.log(reformat('HEL-CAS|MAD-STO|XXX-YYY', '|', '-'));
console.log(reformat('1:2:3_one:two:free_ONE:TWO:THREE_I:II:III', '_', ':'));
console.log(reformat('abcdefgh.ABCDEFGH', '.', ''));


texts: Binning and calculating a huge range of data

texts:
I have a code that I'm fairly certain does what I want. Bear with me as I explain what I'm doing:

Imagine that there is 10 houses, where there can be one to an infinite number of persons. Each of those persons sends a number of messages, containing their userid and the house number. This can be from 1 to infinite number of messages. I want to know the average number of messages that is sent by each person, for each house, to later plot which house got the largest number of average messages.

Now, that I've explained conceptually, the houses aren't houses, but latitudes, from f.ex -90 to -89 etc. And that a person can send messages from different houses.

This is some sample input:

lat = [-83.76, -44.88, -38.36, -35.50, -33.99, -31.91, -27.56, -22.95,
       -19.00, -12.32,  -6.14,  -1.11,   4.40,  10.23,  19.40,  31.18,
        40.72,  47.59,  54.42,  63.84,  76.77]

userid= [525, 701, 701, 520, 701, 309, 373, 255,
         372,  636, 529, 529, 529, 775,   345,  636,
          367, 366,  372,  251,  273]

The real input is some houndred million values in the range of -90 to 90 for latitudes, and different numbers in no set range for the userid. There are about 100 000 unique userids. These are stored in an SQLite database.

"My code" takes about 13s with 1/300th of my data, so I guess there is a lot of possibilities for optimization. I got the code with great help from J-Richard-Snape in this question. Note that it is my code down until min_lat so he is not held accountable for the code over that.  Any suggestions?

import sqlite3 as lite
import numpy as np
import matplotlib.pyplot as plt
from itertools import groupby

def getQuantity(databasepath):
    latitudes = []
    userids = []
    info = []
    con = lite.connect(databasepath)
    with con:
        cur = con.cursor()
        cur.execute('SELECT latitude, userid FROM message')
        con.commit()
        while True:
            tmp = cur.fetchone()
            if tmp != None:
                info.append([float(tmp[0]),int(tmp[1])])
            else:
                break
        info = sorted(info, key=itemgetter(0))
        for x in info:
            latitudes.append(x[0])
            userids.append(x[1])
        info = []
        tmp = 0
        min_lat = -90
        max_lat = 90
        binwidth = 1

        bin_range = np.arange(min_lat,max_lat,binwidth)

        all_rows = zip(latitudes,userids)
        binned_latitudes = np.digitize(latitudes,bin_range)
        all_in_bins = zip(binned_latitudes,userids)
        unique_in_bins = list(set(all_in_bins))
        all_in_bins.sort()
        unique_in_bins.sort()

        bin_count_all = []
        for bin, group in groupby(all_in_bins, lambda x: x[0]):
            bin_count_all += [(bin, len([k for k in group]))]

        bin_count_unique = []
        for bin, group in groupby(unique_in_bins, lambda x: x[0]):
            bin_count_unique += [(bin, len([ k for k in group]))]

        bin_density = [(bin_range[b-1],a*1.0/u) for ((b,a),(_,u)) in         zip(bin_count_all, bin_count_unique)]

        bin_density =  np.array(bin_density).transpose()

        # all_in_bins and unique_in_bins now contain the data
        # corresponding to the SQL / pseudocode in your question

        # plot as standard bar - note you can put uneven widths in as an         array-like here if necessary
        plt.bar(*bin_density, width=binwidth)

Especially info.append([float(tmp[0]),int(tmp[1])]) causes a memory error.


texts: 'Genetic algorithm' implementation for constructing a battle mech

texts:
This is a simple but complete console application where I experiment with genetic algorithm to try to figure out the best way to construct a battle mech that would win in a simple turn-based combat.

I welcome your criticism and pointers about what I could improve in the code above: architecture-wise, technique-wise, presentation-wise, and whatever else catches your interest. To provide at least a sample code as per the local rules, this is the method to make two mechs meet in combat:

// Match::match()
// ==============
// A static method that can be used to execute a match between the two provided mechs.
// Return value: 0 = draw, 1 = mech #1 wins, 2 = mech #2 wins.

int Match::match (Mech& m1, Mech& m2) {

    m1.resetCombatValues();
    m2.resetCombatValues();

    int turn = 0;
    static const int turnLimit = 25;

    // Each turn:
    while (turn < turnLimit) {

        m1.actCombatTurn (m2);
        m2.actCombatTurn (m1);

        bool mech1Alive = m1.isAlive();
        bool mech2Alive = m2.isAlive();

        if (!mech1Alive && !mech2Alive) return 0;

        if (!mech1Alive) return 2;
        if (!mech2Alive) return 1;

        turn++;

    }

    // Turn limit reached.
    return 0;

}


texts: Smart Pointers with Reference Counting - C++

texts:
I am trying to improve my general skills in C++ so I plan to write versions of shared_ptr and unique_ptr from scratch. I wrote a version of shared_ptr with reference counting and I was wondering for reviews.

#ifndef __SHIVA_XSMARTPTRS__
#define __SHIVA_XSMARTPTRS__

/*
This tries to define a reference counted smart pointer class instead of
regular pointers
*/

namespace Shiva
{
template <class T>
class SmartPtr
{
  public:
    //Default Constructor
    explicit SmartPtr(T* p = 0)
    {
      if(p)
        ptrWrapper_ = new PointerWrapper(p,1);
      else
        ptrWrapper_ = new PointerWrapper();
    }

    //The copy constructor
    SmartPtr(const SmartPtr& copyObj)
    {
      ptrWrapper_ = copyObj->ptrWrapper_;
      ptrWrapper_->incrementRefCount();
    }

    //Assignment operator
    SmartPtr& operator=(const SmartPtr& copyObj)
    {
      if(this != copyObj)
      {
        //Decrement and decimate as needed
        unsigned int preReleaseRefCount = ptrWrapper_->getRefCount();
        ptrWrapper_->decrementRefCount();
        if(preReleaseRefCount==1)
        {
          delete ptrWrapper_;
          ptrWrapper_ = 0;
        }
        ptrWrapper_ = copyObj->ptrWrapper_;
        ptrWrapper_->incrementRefCount();
      }
      return *this;
    }

    //The main object destructor
    //Essentially decrement the refcount by 1. If the refcount is equal to 0, then you should delete the pointer
    ~SmartPtr()
    {
      unsigned int preReleaseRefCount = ptrWrapper_->getRefCount();
      ptrWrapper_->decrementRefCount();
      if(preReleaseRefCount==1)
      {
        delete ptrWrapper_;
        ptrWrapper_ = 0;
      }
    }

    //Referncing operator
    T& operator*()
    {
      return ptrWrapper_->getReference();
    }

    //Address operator
    T* operator->()
    {
      return ptrWrapper_->getPointer();
    }

    //Get reference counter
    int getRefCount() const
    {
      return ptrWrapper_->getRefCount();
    }

    //Is this the only copy of the object present
    bool unique() const
    {
      return ptrWrapper_->isUnique();
    }

private:
    class PointerWrapper
    {
    public:
      PointerWrapper(T* ptr=0, int refCount = 0)
      :ptr_(ptr),refCount_(refCount)
      {}

      T* getPointer()
      {
        return ptr_;
      }

      T& getReference()
      {
        return *ptr_;
      }

      unsigned int getRefCount()
      {
        return refCount_;
      }

      void decrementRefCount()
      {
        refCount_--;
        if(!refCount_)
        {
          delete ptr_;
          ptr_ = 0;
        }
      }

      void incrementRefCount()
      {
        refCount_++;
      }

      bool isUnique()
      {
        return (refCount_==1);
      }

    private:
      T* ptr_;
      int refCount_;
    };

    PointerWrapper* ptrWrapper_;
};
}

#endif


texts:
I am trying to improving my Java skills and I've been doing various different projects/challenges which I usually am able to complete. I unfortunately never have my code reviewed so while my code may work, I would love to hear ways to do things better. I went on Codechef and solved one of the problems and added some basic error handling in addition to what the problem asked. I tried to write the code as clearly as possible to avoid unnecessary comments.

Main.java

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

static List<Integer> maxEatingCaps_Limark = new ArrayList<>();
static List<Integer> maxEatingCaps_Bob = new ArrayList<>();

public static void main(String[] args) {

    setUp();
    Bear Limak = new Bear(maxEatingCaps_Limark,"Limak");
    Bear Bob = new Bear(maxEatingCaps_Bob,"Bob");
    Bear.startEating(Limak,Bob);

    }

public static void setUp() {
    int  numOfTestCases = 0;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter number of test cases");

    try {
        numOfTestCases = Integer.parseInt(input.nextLine().trim());
    }
    catch (NumberFormatException e) {
        System.err.println("You must enter an number" );
        System.exit(1);
    }

    boolean validInput = false;
    for (int i = 0; i < numOfTestCases ; i++) {
        validInput = false;

        while (!validInput)
            try {

                String maxEatingInput = input.nextLine();
                String[] individualEatingCaps = maxEatingInput.trim().split("\\s+");
                maxEatingCaps_Limark.add(Integer.parseInt(individualEatingCaps[0]));
                maxEatingCaps_Bob.add(Integer.parseInt(individualEatingCaps[1]));
                validInput = true;

            } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                System.err.println("Enter in the form: INTEGER:(Limark's Max Eating Capacity) INTEGER:(Bob's Max Eating Capacity)");
                validInput = false;

            }

    }

}

Bear.java

import java.util.List;

public class Bear {

    private static int amountOfCandyToEat;
    private static boolean haveWinner;
    private static String currentLeader;
    private int candyConsumed;
    private List<Integer> maxEatingCapacity;
    private String name;
    private static int numOfTest;

    Bear(List<Integer> maxEatingCapacity, String name) {

        this.maxEatingCapacity = maxEatingCapacity;
        this.name = name;
        candyConsumed = 0;
        numOfTest = maxEatingCapacity.size();
    }

  public static void  startEating(Bear bear1, Bear bear2) {

        for (int i = 0; i < numOfTest ; i++) {

            amountOfCandyToEat = 1;
            haveWinner = false;
            currentLeader = null;
            bear1.reset();
            bear2.reset();

            while(!haveWinner) {

                tryEating(bear1,i);
                tryEating(bear2,i);
            }
            System.out.println(currentLeader);

        }
        }
    private void reset() {
        candyConsumed = 0;
    }

    private static void tryEating(Bear bear, int index) {

        if (bear.getCandyConsumed() + Bear.getAmountOfCandyToEat() <= bear.getMaxEatingCapacity(index)) {
            bear.setCandyConsumed(bear.getCandyConsumed() + Bear.getAmountOfCandyToEat());
            Bear.setCurrentLeader(bear.getName());
            amountOfCandyToEat++;
        }
        else{
            haveWinner = true;
        }
    }

  private String getName() {
      return name;
  }

  private static int getAmountOfCandyToEat() {
      return amountOfCandyToEat;
  }

  private int getMaxEatingCapacity(int index) {
      return maxEatingCapacity.get(index);
  }

  private int getCandyConsumed() {
      return candyConsumed;
  }

  private void setCandyConsumed(int candyConsumed) {
      this.candyConsumed = candyConsumed;
  }

  private static void setCurrentLeader(String currentLeader) {
      Bear.currentLeader = currentLeader;
  }
}


texts: Group key-value pairs in chunks no longer than specified limit

texts:
Sometime ago I saw a code which packed key,value pairs into several GET messages. That code had a bug (that is why it was shown to me: as the example of beautiful code which doesn't do what it should).

Today I decided to write this code out of curiosity and for training.

This is what I have written:

def group(url,D,limit):
    if len(D) == 0:
        if len(url) <= limit:
            yield url
            return
        else:
            raise ValueError("url is longer than limit")

    if len(url) > limit - 2:
        raise ValueError("url is too long to be able to hold any key-value pairs")

    for i,(key,value) in enumerate(D.iteritems()):
        if i == 0:
            old = url
            new = '{url}?{key}={value}'.format(**locals())
            continue
        new, old = '{new}&{key}={value}'.format(**locals()), new

        if len(new) > limit:
            if len(old) > limit:
                raise ValueError("String '{old}' is longer than GET query limit.".format(**locals()))
            yield old
            old = url
            new = '{url}?{key}={value}'.format(**locals())
    if len(new) != len(url):
        if len(new) > limit:
            raise ValueError("String '{new}' is longer than GET query limit.".format(**locals()))
        yield new

I have written some tests and the code seems to work correctly.

Still, I don't like it.

If we leave alone corner case checking at the beginning, we will only have one working cycle.
Inside that cycle I had to keep two strings: old and new. If new is longer than the limit, I yield the old one, and start a new string with blank url plus key,value pair added which caused the previous new string to grow beyond the limit.

To make it work I had to write the same statements in different places of that loop.

For example,

old = url
new = '{url}?{key}={value}'.format(**locals())

is written it two places.

raise ValueError("String '{new}' is longer than GET query limit.".format(**locals()))

is also in two places.

Can it be refactored to have statements to be written only once without duplication?

Are there any other things that I should pay attention to?


texts: A closable footer bar with a floating info box

texts:
I wrote this page with the goal in mind of having a footer that runs along the bottom of the page that can be closed, and has a floating info box that appears when the footer is hovered over. I'm just learning JS, HTML and CSS now, so I'd appreciate any critiques on style.

Am I doing anything the long way? Is any of the JavaScript un-idiomatic? Please let me know!

What I'm not looking for advice on:

I know that external CSS and JS would likely be preferable. I'm using internal JS and CSS to ease learning.

This is a very broad review request. I'd like opinions on any aspect of any of the languages used.

FooterTest.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Footer Test</title>
    <style>
        body {
            background-color: lightseagreen;
        }

        #floatingBox {
            display: none;
            position: fixed;

            background-color: black;
            color: white;

            left: 0px;
            top: 0px;

            width: 50px;
            height: 50px;

            z-index: 1;
        }

        #fixedFooter {
            display: block;
            position: fixed;
            background-color: bisque;
            color: black;

            left: 0px;

            border-top: 10px double black;
            bottom: 0px;

            height: 20%;
            width: 100%;

            text-align: center;

            z-index: 0;
        }

        #closeButton {
            display: inline-block;
            position: absolute;

            right: 0px;
            top: 0px;

            color: white;
            background-color: red;

            width: 5%;
            height: auto;

            z-index: 1;
        }
    </style>
</head>
<body>
    <div id="floatingBox">
        Test Block
    </div>

    <footer id="fixedFooter">
        <button id="closeButton">X</button>
    </footer>
    <script>
        var fixedFooter = document.getElementById("fixedFooter");
        var positionText = document.createElement('p');
        var closeButton = document.getElementById("closeButton");

        fixedFooter.appendChild(positionText);

        var floatingBox = document.getElementById("floatingBox");

        var defaultDisplay = "inline-block";

        //To prevent the mouse from entering the floating box
        var posBuffer = 10;

        fixedFooter.onmousemove = function(e) {
            var x = e.pageX;
            var y = e.pageY;

            positionText.innerHTML = formatPosition(x, y) + " - "
                    + formatPosition(floatingBox.style.left, floatingBox.style.top);

            setElementPosition(floatingBox, x + posBuffer, y + posBuffer);
        };

        fixedFooter.onmouseover = function(e) {
            floatingBox.style.display = defaultDisplay;
            console.log("\tMouse In");
        };

        fixedFooter.onmouseout = function() {
            floatingBox.style.display = "none";
            //setElementPosition(floatingBox)
            console.log("\tMouse Out");
        };

        closeButton.onclick = function() {
            fixedFooter.style.display = "none";
        }

        var setElementPosition = function(element, xPos, yPos) {
            element.style.left = xPos + "px";
            element.style.top = yPos + "px";

            //console.log("Setting " + element + "'s position to " + formatPosition(xPos, yPos));
        };

        var formatPosition = function(x, y) {
            return "(" + x + ", " + y + ")";
        };

    </script>
</body>
</html>


texts: Responsive Foundation Orbit Image Gallery

texts:
I decided to refactor the code for a responsive image gallery, that I setup not too long ago. Following the suggestions @joseph-the-dreamer made, and some other best practices, I cut down on the number of if statements.

Is there anything else I could do to make the activateSlider function more concise?

Is there another method one could use (in general) to avoid having to keep calling the same function on resize?

/* jQuery throttle / debounce - v1.1 - 3/7/2010 */
function debounce(a,b,c){var d;return function(){var e=this,f=arguments;clearTimeout(d),d=setTimeout(function(){d=null,c||a.apply(e,f)},b),c&&!d&&a.apply(e,f)}}

function activateSlider() {

   var slider = $('#slider'),
    sliderContainer = $('.orbit-container'),
    sliderContainerLinks = $(sliderContainer).children('a'),
    sliderKids = $('#slider li'),
    sliderContent = $('.slider-content'),
    sliderKidsContent = $(sliderKids).children(sliderContent),
    inactiveKidsContent = $('#slider li:not(.active) .slider-content'),
    accordionContainer = $('.accordion-container'),
    sliderBulletsContainer = $('.orbit-bullets-container');

  function transformSlider() {
    $(slider).foundation({
       orbit: {
         slide_number: false,
         timer: true,
         timer_speed: 8000,
         next_on_click: false
       }
   });

  if(window.matchMedia("(max-width: 767px)").matches) {
       /* Disable orbit gallery styles */
        $(sliderContainer).after($('.orbit-timer'));
        $(slider, sliderKids).attr('style', '');
        $(slider).removeClass('orbit-slides-container').removeAttr('data-orbit').addClass('accordion-container');
        $(sliderKids).removeAttr('data-orbit-slide').removeClass('active');
        $(sliderContainerLinks, sliderKidsContent).hide();
        $(inactiveKidsContent).css('display', 'none');

      /* Init accordion click functions */
        $(sliderKids).unbind().bind('click', function(){
            $(this).toggleClass('active').siblings().removeAttr('class');
            $(this).siblings().find(sliderContent).slideUp();
          $(this).find(sliderContent).slideToggle();
        });
  } else {
    /* If accordion styles are present, remove them */
    var OrbitStyles = ($(accordionContainer).length === 0);
    if (!OrbitStyles) {
        $(sliderContainerLinks).show();
        $(slider).removeClass('accordion-container').addClass('orbit-slides-container').attr('data-orbit', '');
        $(sliderBulletsContainer).before($('.orbit-timer'));
        $('.orbit-timer').removeClass('paused');
    }
      $(sliderContent).show();
      $(sliderKids).first().addClass('active').siblings().removeAttr('class');
  }
}
 transformSlider();
}

$(function(){
  if (window.Foundation) {
    activateSlider();
  }
});
/* Call the script on resize (must support ie8) */
if (window.addEventListener) {
   window.addEventListener('resize', debounce(function () {
    activateSlider();
  }, 250));
} else {
   window.attachEvent('resize', debounce(function () {
     activateSlider();
   }, 250));
 }

EDIT: It looks a little crude (stylewise) but the working version is here: http://jsbin.com/gicin/14/


texts:
Because I don't want to download an entire library for a single function (which I do understand, was made better than I made mine), I decided to implement my own string formatting function.

I am not very proud of it, as I find it pretty ugly and unreadable.
This is only a string formatter with string-only arguments.
Efficiency is not a concern for me.

#include<iostream>
#include<unordered_map>
#include<string>

using std::string;
string formatString(string format, const std::unordered_map<string, string>& args) {
    string ret;

    string::size_type bracketLoc;
    while((bracketLoc = format.find_first_of('{')) != string::npos) {
        // Handling the escape character.
        if(bracketLoc > 0 && format[bracketLoc - 1] == '\\') {
            ret += format.substr(0, bracketLoc + 1);
            format = format.substr(bracketLoc + 1);
            continue;
        }

        ret += format.substr(0, bracketLoc);
        format = format.substr(bracketLoc + 1);

        bracketLoc = format.find_first_of('}');
        string arg = format.substr(0, bracketLoc);
        format = format.substr(bracketLoc + 1);

        auto it = args.find(arg);
        if(it == args.end()) {
            ret += "(nil)";
        } else {
            ret += it->second;
        }
    }

    ret += format;

    return ret;
}

int main() {
    std::cout << formatString("Hello, {Name}! {WeatherType} weather, right?", {
        {"Name", "Midnightas"},
        {"Fruit", "Apple"}
    });

    return 0;
}

Compile with -std=c++11.
The above program will output Hello, Midnightas! (nil) weather, right?.


texts: Parsing pairs of a number or number range

texts:
I need to process an array of number pairs. Here are the constraints on the pairs:

The second item may be missing, in this case 0 will be used as second item - - 38 is the same as 38,0
The pair items may be a number, or a range - 149,0, 149,[3,7], [5,9],11, [3,6],[2,9], [4,8]
The range may be inclusive or exclusive - [8,11], [3,9), (4,10]
There may be any number of spaces between items - [ 3 , 6 ]
The second item may be >=0, this is the same as bullet #1 - 36, >=0

Why do I need the ranges? If I have, say, 149,[3,5], then I need to have 3 pairs - 149,3, 149,4, 149,5. If I have [8,10], then the pairs are 8,0, 9,0, 10,0. You get the idea.

I wrote a regex to get the items from the input. I think regex is not the best choice here, maybe I'll change it. Here's my program:

#include <string>
#include <regex>
#include <vector>

using intRange = std::pair<int, int>;
std::vector<std::pair<int, int>> pairs;

intRange getRange(const std::string &value1, const std::string &value2, const std::string &value3)
{
    if (value1.length())
        return intRange(std::stoi(value1), std::stoi(value1));

    if (value2.length() && value3.length())
    {
        const short startIncrement = value2.front() == '(' ? 1 : 0;
        const short endDecrement = value3.back() == ')' ? 1 : 0;

        // remove the parentheses
        std::string val2 = value2, val3 = value3;
        val2.replace(0, 1, std::string{});
        val3.pop_back();

        return intRange(std::stoi(val2) + startIncrement, std::stoi(val3) - endDecrement);
    }

    return {};
}

bool parseRange(const std::string &input)
{
    pairs.clear();

    static const std::regex rx{ R"numrange(\s*(?:(\s*\d+\s*)|([\[\(]\s*\d+)\s*,\s*(\d+\s*[\]\)]))(?:,\s*(?:(\d+\s*)|\s*([\[\(]\d+)\s*,\s*(\d+\s*[\]\)])|(\s*>\s*=\s*0\s*)))?\s*)numrange" };

    std::smatch matches;
    if (std::regex_match(input, matches, rx))
    {
        // if 1st (4th) match group exists, first (second) item is a single number
        // if 2nd and 3rd (5th and 6th) match groups exist, first (second) item is a range
        // if neither 4th nor 5th and 6th groups exist, then second item isn't specified, and default value (0) is used
        auto firstRange = getRange(matches[1], matches[2], matches[3]);
        auto secondRange = getRange(matches[4], matches[5], matches[6]);

        // save all pairs
        for (auto first = firstRange.first; first <= firstRange.second; ++first)
            for (auto second = secondRange.first; second <= secondRange.second; ++second)
                pairs.emplace_back(first, second);
    }
    else
        return false;

    return true;
}

int main()
{
    std::vector<std::string> inputs = {
        "38",
        "149,0",
        "149,[3,7]",
        "[5,9],11",
        "[3,6],[2,9]",
        "[4,8]",
        "[3,9)",
        "(4,10]",
        "[ 3 , 6 ]",
        "36, >= 0"
    };

    for (const auto &input : inputs)
    {
        if (parseRange(input))
        {
            std::cout << "input: " << input << '\n';
            for (const auto &pair : pairs)
                std::cout << pair.first << ", " << pair.second << '\n';
            std::cout << "-------------------\n";
        }
        else
        {
            std::cout << "Error occurred.";
            return -1;
        }
    }

    std::cin.get();
}

I think there is room for improvement for this code. Please let me know where I can improve. Thanks.


texts: Pseudo-random number generator & password generator

texts:
I've started learning Rust and decided to implement something on my own from scratch. I've implemented a PRNG and I use it to generate random passwords.
Project tree:
|   .gitignore
|   Cargo.lock
|   Cargo.toml
|
+---src
|       main.rs
|       password.rs
|       xorshift.rs
|

main.rs :
use std::io;

mod xorshift;
mod password;

fn main() {

    let length : u32;

    loop{
        let mut pass_leng_str = String::new();

        println!("Enter the length of wannable password: ");

        io::stdin()
            .read_line(&mut pass_leng_str)
            .expect("Faild to read the line");

        let pass_leng_str = pass_leng_str.trim();

        match pass_leng_str.parse::<u32>(){
            Ok(i) => {
                length = i;
                break;
            },
            Err(..) => {
                println!("Not a valid integer!");
            },
        }
    }
    println!("Enter the characters you want to exclude: ");

    let mut exclude = String::new();

    io::stdin()
        .read_line(&mut exclude)
        .expect("Faild to read the line");

    let excluded : Vec<char> = exclude.chars().collect();

    println!("{}", password::rand_pass(length, excluded));

}

password.rs :
use super::xorshift;

pub static ASCII : [char; 69] = [
    'a', 'b', 'c', 'd', 'e',
    'f', 'g', 'h', 'i', 'j',
    'k', 'l', 'm', 'n', 'o',
    'p', 'q', 'r', 's', 't',
    'u', 'v', 'w', 'x', 'y',
    'z',
    'A', 'B', 'C', 'D', 'E',
    'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y',
    'Z',
    '1','2','3','4',
    '5','6','7','8',
    '9','0',
    '+','-','_','?','!','$','/',
];

pub fn rand_pass(pass_len : u32, excluded : Vec<char>)-> String{
    let mut  password = String::new();
    for _i in 0..pass_len{
        let c : char = loop{
            let c = ASCII[xorshift::get_rand(69) as usize];
            if !excluded.contains(&c){
                break c
            }
        };
        password.push(c);
    }

    password
}

xorshift.rs :
use std::time::UNIX_EPOCH;
use std::time::SystemTime;

pub fn get_rand(len : u128) -> u128{
    let now = SystemTime::now();
    let from_unix = now.duration_since(UNIX_EPOCH).expect("Congrats on time travel!");
    let seed = from_unix.as_nanos();
    let x = seed;
    let x = x ^ seed << 13;
    let x = x ^ x >>17;
    let x = x ^ x <<5;
    let x = x % len;
    x as u128
}


texts: Highlighting and copying spreadsheet rows that match a criterion

texts:
I use the code (provided below) to check for certain criteria in a row. In this case, if cell F in worksheet "Swivel" contains "After Dispute For SBU" then that row needs to be highlighted in yellow and the text changed to red, then the row needs to be copied to another sheet named "Disputed" that is within the same workbook. I have added some code to remove the highlight and the font color change if the row is removed from the workbook manually and then the code is triggered again. This particular code is run from a menu system that I created (code not included). The additional code is also used to protect the color of the header row.

This updated code is causing erratic behavior of the cursor and is also running a little longer than it was before the changes, even though the amount of data did not change. Is there a way to improve the code? or is this normal behavior that I need to live with?

The code is completing the tasks as expected.

Sub Highlight_Copy_Disputed()

Application.ScreenUpdating = False

    ' This part highlights all rows that are Disputed
    Dim row As Range
    For Each row In ActiveSheet.UsedRange.Rows
        If row.Cells(1, "F").Value = "After Dispute For SBU" Then
            row.Interior.ColorIndex = 6
            row.Font.Color = RGB(255, 0, 0)
    ElseIf row.Cells(1, "F").Value = "Impact Status" Then
            row.Interior.Color = RGB(197, 190, 151)
            row.Font.Color = RGB(0, 0, 0)
    Else
        row.Interior.ColorIndex = xlNone
        row.Font.Color = RGB(0, 0, 0)
        End If
    Next row

' This part clears the Disputed worksheet and copies all disputed rows to the sheet

With ThisWorkbook.Worksheets("Disputed")
Range(.Range("A2"), .UsedRange.Offset(1, 0)).EntireRow.Delete
End With

Dim LR As Long, lr2 As Long, r As Long
LR = Sheets("Swivel").Cells(Rows.Count, "A").End(xlUp).row
lr2 = Sheets("Disputed").Cells(Rows.Count, "A").End(xlUp).row
    For r = LR To 2 Step -1
        If Range("F" & r).Value = "After Dispute For SBU" Then
            Rows(r).Copy Destination:=Sheets("Disputed").Range("A" & lr2 + 1)
            lr2 = Sheets("Disputed").Cells(Rows.Count, "A").End(xlUp).row
        End If

        Range("A2").Select
    Next r
Application.ScreenUpdating = True
    Range("C" & Rows.Count).End(xlUp).Offset(1).Select
End Sub


texts: Make 10 from the numbers 1,1,5 and 8 using the 4 operations, by brute force

texts:
I tried to calculate the following problem by brute force using R (under the assumption that a single pair of parenthesis would suffice).

  Make 10 from the numbers 1, 1, 5, 8. You can use the operations + – *
  / ().  You have to use all the numbers, and use each number exactly
  once. The operations can be repeated (like 1 + 1 + 5 + 8) and you
  don’t have to use each operation.

I did the following and got the correct answer, but I would like your ideas for better ways of addressing that problem.

## Helper functions for inserting characters into strings
# http://stackoverflow.com/questions/13863599/insert-a-character-at-a-specific-location-in-a-string/25416334#25416334

  split_str_by_index <- function(target, index) {
    index <- sort(index)
    substr(rep(target, length(index) + 1),
           start = c(1, index),
           stop = c(index -1, nchar(target)))
  }

  #Taken from https://stat.ethz.ch/pipermail/r-help/2006-March/101023.html
  interleave <- function(v1,v2)
  {
    ord1 <- 2*(1:length(v1))-1
    ord2 <- 2*(1:length(v2))
    c(v1,v2)[order(c(ord1,ord2))]
  }

  insert_str <- function(target, insert, index) {
    insert <- insert[order(index)]
    index <- sort(index)
    paste(interleave(split_str_by_index(target, index), insert), collapse="")
  }

  # insert_str("1+1+5+8", c("(", ")"), c(2, 3))

  #################

  library(gtools)
  library(dplyr)

  symbols <- expand.grid(data.frame(matrix(rep(c("+","-","*","/"),3),ncol=3)))

  numbers <- unique(permutations(4,4,c(1,1,5,8),set=FALSE))

  # Insert symbols between the numbers
  lst <- lapply(1:nrow(numbers) , function(i) mapply(paste0,numbers[i,],symbols))
  res1 <- data.frame(do.call(rbind, lst))

  # paste strings omitting the trailing symbol
  res2 <- res1 %>%
    transmute(expr=do.call(paste0,.)) %>%
    transmute(expr=substr(expr,1,7))

  # positions of opening and closing bracket
  x<-expand.grid(c(1,3,5),c(4,6,8))
  x<-x[x[1]<x[2]-1,]

  # Generate x rows for each row of res2
  res3 <- as.data.frame(matrix(rep(NA,nrow(res2)*nrow(x)),ncol=1))
  for (i in seq(nrow(res2))){
    temp <- res2[i,]
    res3[((i-1)*nrow(x)+1):(i*nrow(x)),] <- sapply(1:6, function(j) insert_str(temp,c("(", ")"),x[j,]))
  }

  res3  %>%
    rowwise() %>%
    mutate(result=eval(parse(text=V1))) %>%
    filter(result==10)


texts: Convert hex encoded string to byte array

texts:
The following should read a hex string such as "ece998a2fb" into vector 236 233 152 162 251. I was unable to find any built in method for doing this.

as.byte.vector <- function(hex.string) {
  vapply(seq(to=nchar(hex.string), by=2), function(idx) {
    as.numeric(paste("0x", substr(hex.string, idx, idx+1), sep=''))
  }, FUN.VALUE = double(1))
}


texts: Project Euler problem 86 taking a long time

texts:
I'm trying to solve problem 86 in Project Euler. After some tinkering, I managed to unroll the DP solution into a loop. But still the solution takes >150s to complete. What can I do to improve the performance of this algorithm?

(defn- square [n]
  (* n n))

(defn- is-perfect-square? [n]
  (let [sq (int (Math/sqrt n))]
    (= n (* sq sq))))

;; See: https://math.stackexchange.com/a/1189884/7078 (Second case)
;; So lengths = [sqrt(l^2 + b^2 + h^2 + 2bh), sqrt(l^2 + b^2 + h^2 + 2lb), sqrt(l^2 + b^2 + h^2 + 2lh)]
;; Shortest length is the smallest of the above. == sqrt(l^2 + b^2 + h^2 + min(2bh, 2lb, 2lh))
(defn- shortest-cuboid-dist-has-int-length?
  ([a b c]
   (->> (min (* a b) (* b c) (* c a))
        (* 2)
        (+ (square a) (square b) (square c))
        (is-perfect-square?)))
  ([[a b c]]
   (shortest-cuboid-dist-has-int-length? a b c)))

;; if F(n) denotes number of integer shortest lengths for cuboids with dimensions equal to or less than (n,n,n),
;; F(i+1) = F(i) + int_lengths(cuboids with at least one side dimension of i+1)

(defn- get-int-dist-above [lim]
  (loop [dim 0 c 0 i 1 j 1]
    (cond (> c lim) dim
          (= i (inc dim)) (recur (inc dim) c 1 1)
          (= j (inc i)) (recur dim c (inc i) 1)
          :else (recur dim (if (shortest-cuboid-dist-has-int-length? dim i j) (inc c) c) i (inc j)))))

(defn problem-86 []
  (get-int-dist-above 1000000))

(time (problem-86))  ;; Takes 150s


texts: Storing and Retrieving data with User Forms in Excel 2010

texts:
I'm currently designing a check list for my office using Excel that requires the user to save anywhere from 4-10 documents that need to be saved in the same folder as this check list. I thought it might be easier to consolidate everything into one Excel file by using User Forms. I noticed that it's not safe to use a User Form to store data, but instead using it as a means to display or manipulate data or cells from within the spreadsheet.

Unfortunately, I cannot store all the raw data from these files into a single cell as they can be quite large files. I thought maybe it'd be best to have an ActiveX Textbox to store this data into instead, but I'm wondering if I this might cause issues later down the road or if some one else's computer isn't compatible.

Visually what I've done...

This is the secondary spreadsheet (will be hidden) that stores the data in ActiveX Text Boxes

User form below that is displaying that data, stored from the secondary spreadsheet in the ActiveX Text Boxes

TL;DR

Everything is working as intended, but my primary question here is... Is this the best and safest (safest as in, lowest chance of losing data... I am not worried about security as everything is stored on a server) way to have all this data being stored in a single document by using embedded TextBoxes? If not, what would be a good alternative?

Code run when the User Form is closed

Private Sub btnSaveAndClose_Click()

    Sheets("Data").TextBox1.Value = PO850Data.Value
    Sheets("Data").TextBox2.Value = Invoice810Data.Value
    frmEDIData.Hide

End Sub

Code run when the User Form is opened

Private Sub UserForm_Initialize()

    btnSaveAndClose.SetFocus
    PO850Data.Value = Sheets("Data").TextBox1.Value
    Invoice810Data.Value = Sheets("Data").TextBox2.Value

End Sub

EDIT 1:

EXAMPLE EDI 850 DOCUMENT - (X12 Format)

ISA*01*0000000000*01*0000000000*ZZ*ABCDEFGHIJKLMNO*ZZ*123456789012345*101127*1719*U*00400*000003438*0*P*>
GS*PO*4405197800*999999999*20101127*1719*1421*X*004010VICS
ST*850*000000010
BEG*00*SA*08292233294**20101127*610385385
REF*DP*038
REF*PS*R
ITD*14*3*2**45**46
DTM*002*20101214
PKG*F*68***PALLETIZE SHIPMENT
PKG*F*66***REGULAR
TD5*A*92*P3**SEE XYZ RETAIL ROUTING GUIDE
N1*ST*XYZ RETAIL*9*0003947268292
N3*31875 SOLON RD
N4*SOLON*OH*44139
PO1*1*120*EA*9.25*TE*CB*065322-117*PR*RO*VN*AB3542
PID*F****SMALL WIDGET
PO4*4*4*EA*PLT94**3*LR*15*CT
PO1*2*220*EA*13.79*TE*CB*066850-116*PR*RO*VN*RD5322
PID*F****MEDIUM WIDGET
PO4*2*2*EA
PO1*3*126*EA*10.99*TE*CB*060733-110*PR*RO*VN*XY5266
PID*F****LARGE WIDGET
PO4*6*1*EA*PLT94**3*LR*12*CT
PO1*4*76*EA*4.35*TE*CB*065308-116*PR*RO*VN*VX2332
PID*F****NANO WIDGET
PO4*4*4*EA*PLT94**6*LR*19*CT
PO1*5*72*EA*7.5*TE*CB*065374-118*PR*RO*VN*RV0524
PID*F****BLUE WIDGET
PO4*4*4*EA
PO1*6*696*EA*9.55*TE*CB*067504-118*PR*RO*VN*DX1875
PID*F****ORANGE WIDGET
PO4*6*6*EA*PLT94**3*LR*10*CT
CTT*6
AMT*1*13045.94
SE*33*000000010
GE*1*1421
IEA*1*000003438

These can be much larger documents, I'd say we deal with 10x this size on a regular basis. Each TextBox will store one of these document's data.


texts: "Tara's Beautiful Permutations" challenge

texts:
I'm practising my coding skills using Python to answer medium to difficult problems on sites like HackerRank.
Here is the challenge. Given an array of integers, where each number can appear at most twice, count the number of permutations in which no identical numbers appear consecutively.
My solution solves the base test but not the others because it is too slow. That's okay for now (I find the actual solution difficult to understand, but I first would like feedback to my own solution).
My questions today are:

What is the time complexity of my algorithm? I have commented on what I am doing, best to start from the bottom up.
I think, given n elements in the array, I have two for loops and it seems like a n*n! solution for one array, but I would really appreciate a clear explanation here on Big O for this particular piece of code.

I am new to Python's yield and I actually got this part of the solution from another SO post. I just want to know, have I used yield efficiently? What time/efficiency difference would it have made if I didn't use yield in this case and just made a list perm_lst then and there, to hold all unique permutations?

# Enter your code here. Read input from STDIN. Print output to STDOUT

def getBeautifulPerms(arr, arrlen):

    if (arrlen==1): yield arr
    else:
        for perm in getBeautifulPerms(arr[1:], arrlen-1):
            for i in range(arrlen):
                arr_before = perm[:i]
                arr_after = perm[i:]

                if ( (not(arr_before) or arr_before[-1] != arr[0])) and (not(arr_after) or arr_after[0] != arr[0]):
                    yield perm[:i] + [arr[0]] + perm[i:]

def printBeautifulPerms(arr, n):
    '''
    @param arr array of integers (not null)
    @param n length of array arr
    post: prints the number of good permutations mod (10**9 + 7)
    '''

    perm_lst = []
    for perm in getBeautifulPerms(arr, n):
        if perm not in perm_lst:
            perm_lst.append(perm) # remove duplicates

    print(len(perm_lst) % (10**9 + 7))

# main code - the problem states we'll receive this input:
q = int(input()) # no of queries (arrays)

for i in range(q):
    n = int(input()) # no of elements in array
    arr = input () # space separated array of n integers
    arr = arr.split()
    printBeautifulPerms(arr, n)


texts: Two setIntervals activating in a sequence to change CSS

texts:
I'm making a Simon game and I made this function to show flashing lights:

 //a random array representing html divs to change colors
 game.computerMoves = [green, red, blue, red, green, green , yellow];

function showMoves() {

let i = -1;
let c = -1;

const start = setInterval(function() {
    if (i >= game.computerMoves.length - 1) {
        clearInterval(start);
    }

    console.log(i + 'start ' + game.computerMoves.length);

    const showColors = new Map([
        [green, 'lime'],
        [yellow, 'rgb(255,255,102)'],
        [blue, 'dodgerblue'],
        [red, 'salmon'],
    ]);

    i++;

    let move = game.computerMoves[i];

    move.style.backgroundColor = showColors.get(move);
    //revert the colors that were changed in showMoves
    //put at 2 seconds to change after showMoves is done
    const stop = setTimeout(function() {

        console.log(c + 'stop ' + game.computerMoves.length);

        if (c >= game.computerMoves.length - 1) {
            clearInterval(stop);

        }
        const colorKey = new Map([
            [green, 'green'],
            [yellow, 'rgb(204,204,0)'],
            [red, 'red'],
            [blue, 'blue']
        ]);

        c++;

        let move = game.computerMoves[c];

        move.style.backgroundColor = colorKey.get(move);
    }, 1000);
  }, 2000);
}

I'm not sure if this is good code or not but it works how I want it to and I would appreciate any feedback.

edit- here is my html and css, its not done though https://codepen.io/icewizard/pen/JLBpNQ


texts: SQL Query to display minimum prices per country

texts:
I have developed a Tender management System sort of code for one of my client. This is the piece of code :

try {
            Connection con = Mycon.getConnection();
                PreparedStatement ps = con.prepareStatement("TRUNCATE tempcalcplan");
                ps.executeUpdate();
                ps.clearBatch();
                ps = con.prepareStatement("INSERT INTO tempcalcplan SELECT v.conid,c.conname, v.rate, v.venid FROM venprices v LEFT JOIN  country c ON c.conid = v.conid WHERE (v.conid, v.rate) IN ( SELECT v.conid, MIN(v.rate) FROM venprices v GROUP BY v.conid) GROUP BY v.conid");
                ps.executeUpdate();
                ps.clearBatch();
                ps = con.prepareStatement("select * from tempcalcplan");

         ResultSet rs = ps.executeQuery();
         jTable1.setModel(DbUtils.resultSetToTableModel(rs));
        }catch(Exception e){
                e.printStackTrace();
        }

This piece of code is designed to function as :

Empty the table tempcalcplan(Assuming that previous results are stored.)
Generating desired data with the help of 2 different tables(Tables are shown below) and storing it in the tempcalcplan table
Displaying the results of tempcalcplan table on a jTable.

Here Are the country and tempcalcplan table.

country (Contains 30,000 records)

+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| conid   | int(10)     | NO   | PRI | NULL    |       |
| conname | varchar(50) | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+

tempcalcplan (Contains 1,80,000+ Records)

+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| conid   | int(10)     | NO   | PRI | NULL    |       |
| conname | varchar(50) | YES  |     | NULL    |       |
| rate    | double      | YES  |     | NULL    |       |
| venid   | varchar(50) | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+

venprices

+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| conid | int(10)      | NO   | PRI | NULL    |       |
| rate  | double       | YES  |     | NULL    |       |
| venid | varchar(50)  | NO   | PRI |         |       |
+-------+--------------+------+-----+---------+-------+`

The results take up to 12-15 minutes to show in the jTable.
I want reduce it to 1-2 minutes.


texts: Concatenate three 16-bit integers in one 64-bit integer with C++

texts:
I am looking for an elegant alternative of the following code where wordXX contains always 16 bits:

uint64_t wordHi = 0xaa; // I would like u_int16_t over u_int64_t here
uint64_t wordMi = 0xbb; // because it represents the real data better
uint64_t wordLo = 0xcc;

uint64_t largeword = (wordHi << 32) + (wordMi << 16) + (wordLo << 0);

To me this (very simplified) code looks a bit dirty, because reader gets confused about the real size of the wordXX data.

I could store wordHi to largeword and then shift largeword and add wordMi and so on, but this would make the code worse and probably needs more CPU cycles.

Edit: changed u_int64_t to uint64_t in the example as suggested in the comments.


texts:
The following is a small class I extended MySQLi with.  I'm going to use this in my upcoming projects, but my main reason to do this class is learning, so I would like to submit this for your review, tell me if there are any bugs or improvements to be made.

NOTES:

I know about prepared statements, but I am not going to only run the same queries with different parameters, I'm expecting very different queries in each page, So I don't want to use prepared statements. Don't suggest prepared statements.
I am aware of PDO, but I will use MySQL only, so I'm better with MySQLi. So please don't suggest PDO.

class Dbquery extends MySQLi
{
    public $host,$user,$password,$database,$connection;
    public function __construct($host,$user,$password,$database)
    {
        $this -> host = $host;
        $this -> user = $user;
        $this -> password = $password;
        $this -> database = $database;
        $this -> connect_me();
    }
    private function connect_me()
    {
        $this -> connection = $this-> connect($this->host,$this->user,$this->password,$this->database);
        if( $this -> connect_error )
            die($this->connect_error);
    }
    private function extracts($data) // function used to append data and column names for insert query
    {
        $column = array("","");
        foreach ($data as $index => $details)
        {
            $column[0].= $index.",";
            $column[1].= "'".$this ->real_escape_string($details)."',";
        }
        $column[0] = rtrim($column[0],",");
        $column[1] = rtrim($column[1],",");
        return $column;
    }
    private function append($data) // function used to append data and column names for update query
    {
        $string = "";
        foreach($data as $index => $details)
        {
            $string.= $index."='".$this -> real_escape_string($details)."',";
        }
        $string = rtrim($string,",");
        return $string;
    }
    public function insert($table,$data)
    {
        $extracted = $this -> extracts($data);
        $this -> query("INSERT INTO ".$table." (".$extracted[0].") VALUES(".$extracted[1].")");
        if($this -> error)
            return $this -> error;
        else
            return $this -> insert_id;
    }
    public function update($table,$data,$where)
    {
        $extracted = $this -> append($data);
        $this -> query("UPDATE ".$table." SET ".$extracted." WHERE ".$where);
        if($this -> error)
            return $this -> error;
    }
    public function select($table,$column = "",$where = 1,$orderby = "",$limit = "")
    {
        if($column == "")
            $column='*';
        if($orderby == "")
            $orderby = 'NULL';
        if($limit != "")
        {
            $limit = "LIMIT ".$limit;
        }
        $result = $this -> query("SELECT ".$column." FROM ".$table." WHERE ".$where." ORDER BY ".$orderby."".$limit."");
        if($this -> error)
        {
            return $this -> error;
        }
        else
        {
            $index = 0;
            while($row = $result -> fetch_assoc())
            {
                $data[$index] = $row;
            }
            return $data;
        }
    }
    public function delete($table,$where)
    {
        $this -> query("DELETE FROM ".$table." WHERE ".$where."");
        if($this -> error)
        {
            return $this -> error;
        }
        else
        {
            return true;
        }
    }
}


texts: Finding a passcode by comparing MD5 result

texts:
This function finds the 8 char passcode from a given "doorId".

Is there a way to find the passcode in an undetermined number of steps without using a while? Maybe involving streams? val passcode = stream(logic).take(8).

def findPassCode(doorId: String): String = {
  var passcode = ""
  var count = 0

  while (passcode.length < 8) {
    val hash = md5(doorId + count)
    if (hash.startsWith("00000")) passcode = passcode + hash.drop(5).take(1)
    count = count + 1
  }

  passcode
}


texts:
I just wrote a program which performed some elementary set operations as you can see below. It's the first time I have used input and output of text files so I am mainly looking for critique on that, and also how I use cells.

clear all;
clc;

fileID = fopen('inputseto.txt','r');
data = textscan(fileID,'%s',3,'Delimiter','\n');
data = data{1,1};

n = data{1}
n = str2num(n);

A = data{2};
B = data{3};

A = str2num(A(2:end-1));
B = str2num(B(2:end-1));

output = cell(1,6);

output{1} = union(A,B);
output{2} = intersect(A,B);
output{3} = setdiff(A,B);
output{4} = setdiff(B,A);
output{5} = setdiff(1:n,A);
output{6} = setdiff(1:n,B);

fileID = fopen('outputseto.txt','w');

for i = 1:6
    fprintf(fileID,'{');
    fprintf(fileID,'%d, ',output{i}(1:end-1));
    if i ~= 6
        fprintf(fileID,'%d}\n',output{i}(end));
    else
        fprintf(fileID,'%d}',output{i}(end));
    end
end

I got this problem from here. The input is 3 lines, the first lines describes the global set. The first line is an integer n and the global set is the set containing 1,2,...,n. Then the next two lines are two sets A and B. The output consists of various set operations involving A and B.  The solution is correct, but I feel like some of this code doesn't "feel right". I am interested in knowing what you think.


texts: Extract, filter and match three letters from the given arguments and predict the name

texts:
Case 1: rank1_naming

This function takes two arguments

list_proteins_pattern_available
best_match_protein_name

  Objective: Extract the three letter pattern from the both arguments.
  Match the pattern and keep only the matched items. Extract the numbers
  from list_proteins_pattern_available and also sort it. Find the
  maximum number from the collected numbers and add 1 to get the next
  number.

Please let me know if you have any questions.

Can you point ways to improve this script?

import re

def case_rank1_naming(list_proteins_pattern_available, best_match_protein_name):
    #This will store the list of numbers
    available_list_numbers = []

    #extract the three letter pattern
    protein_pattern = re.search(r"[A-Z]{1}[a-z]{2}", best_match_protein_name)
    protein_pattern = protein_pattern.group()

    #extract the numbers
    for name in list_proteins_pattern_available:
        pattern = re.search(r"[A-Z]{1}[a-z]{2}\d{1,3}", name)
        number = re.search(r"\d{1,3}", pattern.group())
        available_list_numbers.append(number.group())

    #Convert all the string numbers to integers
    available_list_numbers = [int(x) for x in available_list_numbers]

    #Sort the available number. Just realized I use two times sort function.
    available_list_numbers.sort()

    # Sort the available number, get the maximum number and add one to get next number
    # Example: result will be 50
    primary_number_prediction = int(max(sorted(available_list_numbers))) + 1

    #Add the protein pattern, the next predicted number and 'Aa1' at the suffix
    predicted_name = protein_pattern + str(primary_number_prediction) + 'Aa1'

    return predicted_name

list_proteins_pattern_available = ['Xpp1Aa1', 'Xpp2Aa1', 'Xpp35Aa1', 'Xpp35Ab1', 'Xpp35Ac1', 'Xpp35Ba1', 'Xpp36Aa1', 'Xpp49Aa1', 'Xpp49Ab1']

best_match_protein_name = 'Xpp35Ba1'

predicted_name = case_rank1_naming(list_proteins_pattern_available, best_match_protein_name)

print(predicted_name)
#Xpp50Aa1


texts:
This is a finished login system where 2 players have to enter their username and password to proceed onto the game. The usernames and passwords are stored in a text file in this formatusername: (username) password: (password). If one of the players enter their details in wrong it will loop it 3 times and if it is sill not correct they have to restart the code to try again.

import sys

counter = 0
check_failed = True
while check_failed:
    print("Could player 1 enter their username and password")
    username1=input("Please enter your username ")
    password=input("Please enter your password ")
    with open("accountfile.txt","r") as username_finder:
        for line in username_finder:
            if ("username: " + username1 + " password: " + password) == line.strip():
                print("you are logged in")
                check_failed = False
                check_failed = True
                while check_failed:
                    print("Could player 2 enter their username and password")
                    username2=input("Please enter your username ")
                    password=input("Please enter your password ")
                    with open("accountfile.txt","r") as username_finder:
                        for line in username_finder:
                            if ("username: " + username2 + " password: " + password) == line.strip():
                                print("you are logged in")
                                check_failed = False

                        else:
                            print("Sorry, this username or password does not exist please try again")
                            counter = counter + 1
                            if counter == 3:
                                print("----------------------------------------------------")
                                print("You have been locked out please restart to try again")
                                sys.exit()
        else:
            print("Sorry, this username or password does not exist please try again")
            counter = counter + 1
            if counter == 3:
                print("----------------------------------------------------")
                print("You have been locked out please restart to try again")
                sys.exit()

As I said this is a finished Login system and I just want suggestions on how I can improve this Login system.


texts: Escalation approval tool, copy to clipboard via Python

texts:
I created a simple little script for the people I work with, what it does is copy information to the users clipboard for escalation approvals. It's pretty simple and not very exciting but I want to know if there are ways to do this better:

from Tkinter import Tk
import getpass
import os
import time

class ClipBoard(object):

    full_string = ''  # Full string that will contain the entire escalation approval

    def __init__(self, string, addition):
        self.string = string
        self.addition = addition

    def add_addition_to_string(self):  # Add the string together
        return self.string + self.addition

    def copy_string_to_clipboard(self):  # Copy to the windows clipboard
        cb = Tk()
        cb.withdraw()
        cb.clipboard_clear()
        cb.clipboard_append(self.full_string)

    def create_full_string(self):  # Create the string and return it
        self.full_string = self.add_addition_to_string()
        return self.full_string

class ConfigureProgram(object):

    def __init__(self, directory, escalator):
        self.directory = directory
        self.escalator = escalator

    def check_directory(self):  # Check if the directory exists
        if os.path.exists(self.directory) is False:
            os.makedirs(self.directory)  # If it doesn't create it
        else:
            return True

    def check_esc_name(self):  # Check if there's already a file made
        if self.check_directory() is True:
            with open(self.escalator, 'a+') as esc:  # If not create it
                esc.write(raw_input('Enter what you want appear on escalations(be specific): '))

def get_user():  # Get the username that's running at the moment
    return getpass.getuser()

def create_addition_for_string():  # Where's it going to?
    return raw_input('Escalate to where? ')

def check_if_run_yet(path_to_file):  # Check if you need to configure the program
    return os.path.exists(path_to_file)

def read_username():  # Read the escalators name from the file created
    with open("C:\Users\{}\AppData\Roaming\esc\esc_name.txt".format(get_user())) as f:
        return f.readline()

if __name__ == '__main__':
    path = "C:\Users\{}\AppData\Roaming\esc\esc_name.txt".format(get_user())

    if check_if_run_yet(path) is not False:
        opening = "Ticket has been reviewed and approved by {}. Ticket assigned to ".format(read_username())
        cliptext = ClipBoard(opening, create_addition_for_string())
        cliptext.create_full_string()
        cliptext.copy_string_to_clipboard()
        print 'Press CNTRL-V to paste the approval.'
        time.sleep(1)
    else:
        config = ConfigureProgram(
            "C:\Users\{}\AppData\Roaming\esc".format(get_user()), path
        )
        config.check_directory()
        config.check_esc_name()
        print "Program configured, please run again."
        time.sleep(2)


texts: Calling API (with rate of 5 calls/second) using Jersey client

texts:
I am using the Jersey client to make API calls to validate a session. This call is being made at a rate of around 5 calls/second. I want to ensure that the client call doesn't have performance issues.

String sessionUrlPrefix = Config.getInstance().getString(Helper.SESSION_SERVICE_URL);
String urlParameters = getParameters(sessionId);
String sessionURL = sessionUrlPrefix + "?" + urlParameters;
WebResource webResource = client.resource(sessionURL);
logger.debug("Session URL is " + sessionURL);
ClientResponse response = webResource
    .accept(MediaType.TEXT_PLAIN_TYPE)
    .type(MediaType.TEXT_PLAIN_TYPE)
    .get(ClientResponse.class);

String responseStr = response.getEntity(String.class);
logger.debug("Response received is " + responseStr);
if (response.getStatus() != HttpStatus.OK.value())
{
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    // Could throw more appropriate HttpException.
}
return responseStr;


texts: Setting the value of properties via reflection

texts:
I am working on an application in which I have to parse an XML file. Nodes of the XML file corresponds to an object. I have to populate the properties of the objects at run time. The code below queries the metadata of property and sets its value. Is there a better way to do it or is there a better way to map the elements of an XML to an object?

public static void SetPropertyValue(object obj, string propertyName, object propertyValue)
    {
        if (obj == null || string.IsNullOrWhiteSpace(propertyName))
        {
            return;
        }

        Type objectType = obj.GetType();

        PropertyInfo propertyDetail = GetPropertyInfo(objectType, propertyName);

        if (propertyDetail != null && propertyDetail.CanWrite)
        {
            Type propertyType = propertyDetail.PropertyType;

            Type dataType = propertyType;

            // Check for nullable types
            if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                // Check for null or empty string value.
                if (propertyValue == null || string.IsNullOrWhiteSpace(propertyValue.ToString()))
                {
                    propertyDetail.SetValue(obj, null);
                    return;
                }
                else
                {
                    dataType = propertyType.GetGenericArguments()[0];
                }
            }

            if (dataType.Equals(typeof(int)))
            {
                propertyValue = Convert.ToInt32(propertyValue);
            }

            if (dataType.Equals(typeof(long)))
            {
                propertyValue = Convert.ToInt64(propertyValue);
            }

            if (dataType.Equals(typeof(short)))
            {
                propertyValue = Convert.ToInt16(propertyValue);
            }

            if (dataType.Equals(typeof(bool)))
            {
                string stringPropertyValue = propertyValue.ToString();
                if (stringPropertyValue.Equals(Boolean.FalseString, StringComparison.OrdinalIgnoreCase) || stringPropertyValue.Equals("0"))
                {
                    propertyValue = false;
                }
                else
                {
                    if (stringPropertyValue.Equals(Boolean.TrueString, StringComparison.OrdinalIgnoreCase) || stringPropertyValue.Equals("1"))
                    {
                        propertyValue = true;
                    }
                }
            }

            if (dataType.Equals(typeof(float)))
            {
                propertyValue = Convert.ToSingle(propertyValue);
            }

            if (dataType.Equals(typeof(double)))
            {
                propertyValue = Convert.ToDouble(propertyValue);
            }

            if (dataType.Equals(typeof(decimal)))
            {
                propertyValue = Convert.ToDecimal(propertyValue);
            }

            if (dataType.Equals(typeof(byte)))
            {
                propertyValue = Convert.ToByte(propertyValue);
            }

            if (dataType.Equals(typeof(string)))
            {
                propertyValue = Convert.ToString(propertyValue);
            }

            if (dataType.Equals(typeof(char)))
            {
                propertyValue = Convert.ToChar(propertyValue);
            }

            if (dataType.Equals(typeof(DateTime)))
            {
                propertyValue = DateTime.ParseExact(propertyValue.ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
            }

            propertyDetail.SetValue(obj, propertyValue);

        }
    }


texts: Values Not Interested In From Hook Causes Re-Render

texts:
This is the code (here):

import React, {
  useContext,
  useReducer,
  createContext
} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const stateReducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return {
        count: state.count + 1
      };
    default:
      return state;
  }
};

const StateContext = createContext();

const StateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(stateReducer, {
    count: 0
  });

  return (
    <StateContext.Provider value={{ state, dispatch }}>
      {children}
    </StateContext.Provider>
  );
};

const useCount = () => {
  const { state, dispatch } = useContext(StateContext);

  const changeCount = () => {
    dispatch({ type: "increment" });
  };

  return {
    ...state,
    changeCount
  };
};

const Caller = () => {
  const { changeCount } = useCount();

  const handleOnClick = () => {
    changeCount();
  };

  return (

      <button type="button" onClick={handleOnClick}>
        Test me!
      </button>

  );
};

const Main = () => {
  const { changeCount } = useCount();

  const handleOnClick = () => {
    changeCount();
  };

  console.log("main render");

  return (

      <button type="button" onClick={handleOnClick}>
        Click Me Boi!
      </button>
      <Caller />

  );
};

const App = () => (
  <StateProvider>

  </StateProvider>
);

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

The issue is this:

My Main component uses a hook. that hook returns some state and a function (functions) to modify that state.

My main component, although uses the hook, only wants/cares about the modifying function of that hook, and as such deconstructs only the function.

When I call the hook's function, it causes a rerender of my main component.

I understand that, for example, if I have useState and call its function, that function will change, but if it's a useReducer and I am calling a displatch does it change?

Really my question comes down to this. Is there a way to stop my main component rendering here (because I only rely on the hook's functions and not the state) or would I have to change my implementation to allow the re-render of main and just use memo to save re-renders of the child components?


texts: Could my object use static methods? Anything I need to do to make the code better?

texts:
With the Zend coding convention in the back of my mind, I have set this up.

It lets you communicate with the API of the vendor TargetSMS. They allow you to bill customers trough SMS. For now I've only spent time on the NonSubscription option.

I would just like to know if it's ok, or what could be better.  I am mostly interested in knowing if the TargetSms object could use static methods.  For example, I think the isAllowedIp method could be static, since I would like to use it even if the object is not initiated (I was told that's the idea behind static methods).

TargetSMS object

<?php
/**
* TargetSMS object with TargetSMS related methods.
*/

namespace TargetPay\Sms;

class TargetSms
{
    /**
* The allowed IP of TargetSms.
* @var array
*/
    protected $_targetSmsIp = array('89.184.168.65');

    /**
* The ok response code for TargetSMS.
* @var number
*/
    protected $_responseCode = 45000;

    /**
* Check if the request is comming from TargetSMS.
* @param string $ip
* @return boolean
*/
    public function isAllowedIp($ip = '')
    {
        if (in_array($ip, $this->_targetSmsIp)) {
            return true;
        }
        return false;
    }

    /**
* Get the TargetSMS required responsecode.
* @return number
*/
    public function getResponseCode()
    {
        return $this->_responseCode;
    }

    /**
* Add a new allowed ip address to the array with allowed ip addresses.
* @param string $ip
*/
    public function addAllowedIp($ip = '')
    {
        $this->_targetSmsIp[] = $ip;
    }
}


texts:
In the _form partial I have a rather complicated logic which builds necessary options for input fields:

- input_html_params = dynamic_settings_select_options('#service-settings', settings_aps_instance_services_path(parent))

= simple_form_for [:aps, parent, resource] do |f|
  = f.input :service_status, :as => :readonly_label
  = f.input :meta_service_meta_id, :collection => parent.meta_services, :value_method => :meta_id, :label_method => :name, :input_html => input_html_params
  = f.button :submit

The first problem which I see here is getting input_html_params to pass them into input of meta_service_meta_id because it already has a lot of parameters. Even this didn't help us to avoid long string to pass all parameters. What is best practice to avoid this complicity?

As you can see, extracting them to helper methods doesn't solve this problem, so I would like to hear something new.


texts: javascript - consolidate multiple null/undefined checks

texts:
My brain is fried from looking from looking at this for so long.  Is there a more efficient way to do this code block.  We have the ability to use es6 code too if that helps.

First it tries to set quantity to itemTemplateIDQty.value if itemTemplateQty is not valid and itemTemplateIDQty is valid.  Then it basically checks the opposite and sets quantity to itemTemplateQty.value.  I'm thinking since in that else block, I am simply checking the exact opposite, I shouldn't need to retype all that code again.  Also I'm wondering if I can remove a lot of code by using something like quantity = itemTemplateIDQty.value || 1;.

Update
I'll try to sum up the code more clearly.  The default value for quantity should be 1 if all the checks fail.  First if there are no classes of itemTemplateQty found and 1+ classes of 'itemTemplateQty' + itemId found then set quantity to the value of the first class found of 'itemTemplateQty' + itemId.  If that check fails, then check if no classes of 'itemTemplateQty' + itemId are found and 1+ classes of itemTemplateQty are found, set quantity to the value of the first class of itemTemplateQty.

let itemId = 5;
let isDynamicRecommendation = false;
let itemTemplateQty =
        document.getElementsByClassName('itemTemplateQty').length > 0 ? document.getElementsByClassName('itemTemplateQty') : null;
    let itemTemplateIDQty =
        document.getElementsByClassName('itemTemplateQty' + itemId).length > 0 ? document.getElementsByClassName('itemTemplateQty' + itemId) : null;
    let quantity = 1;
    if (!isDynamicRecommendation) {
      if ((itemTemplateQty === null || itemTemplateQty.value == null || Number.parseInt(itemTemplateQty.value) <= 0) &&
         (itemTemplateIDQty !== null && itemTemplateIDQty.value !== undefined && itemTemplateIDQty.value !== null && Number.parseInt(itemTemplateIDQty.value) > 0)) {
           quantity = itemTemplateIDQty.value;
      } else if ((itemTemplateIDQty === null || itemTemplateIDQty.value == null || Number.parseInt(itemTemplateIDQty.value) <= 0) &&
        (itemTemplateQty !== null && itemTemplateQty.value !== undefined && itemTemplateQty.value !== null && Number.parseInt(itemTemplateQty.value) > 0)) {
          quantity = itemTemplateQty.value;
      }
    }
console.log("quantity: ", quantity);


texts:
The code works as it is written, however; I was wondering if there are any easier or more effective ways to merge two lists.

import java.util.*;
public class MergeTwoSortedLists {
    public static void main(String[] args)
    {
     java.util.Scanner input = new java.util.Scanner(System.in);

     // Enter values for list1
     System.out.println("Enter the amount of numbers in the first list:");
     // Assign user defined length to the array
     int lengthOfArray = input.nextInt();
     int[] list1 = new int[lengthOfArray];

     // i increments and the user values are assigned to the array until the length is exceeded
     System.out.println("Enter " + list1.length + " values: ");
     for (int i = 0; i < list1.length; i++)
      list1[i] = input.nextInt();

     // Enter values for list2
     System.out.println("Enter the amount of numbers in the second list:");
     // Assign user defined length to the array
     int lengthOfArray2 = input.nextInt();
     int[] list2 = new int[lengthOfArray2];

     // i increments and the user values are assigned to the array until the length is exceeded
     System.out.println("Enter " + list2.length + " values: ");
     for (int i = 0; i < list2.length; i++)
      list2[i] = input.nextInt();

     // Lists one and two are merged into one list
     int[] list3 = merge(list1, list2);
     // Sorts the lists in numerical order
     Arrays.sort(list3);
     // This accesses the actual user defined integers and not their locations, printing them in an assorted array
     System.out.println("The merged list is: " +Arrays.toString(list3));

    }
    public static int[] merge(int[] list1, int[] list2)
    {
        int[] list3 = new int[list1.length + list2.length];
        // Both p and i increment, and list 3 is assigned the user defined integers from both list 1 and 2
        for (int i = 0, p=0 ; i < list1.length || i < list2.length ; i++) {
            if (i < list1.length) {
                list3[p++] = list1[i];
            }
            if (i < list2.length) {
                list3[p++] = list2[i];
            }
        }
        return list3;

    }

}


texts:
I've made a simple caching function for my jQuery ajax calls.

I know about the $.ajax() cache setting, but I don't use it for various reasons. One of the most important one is it being limited to GET (and perhaps HEAD?) requests.

If a cached value is found, and is a reference type, I'm returning a deep copy rather than a reference to the actual object.

var cache = {};
function getData(cacheKey, getPromise) {

    var dfd = $.Deferred(),
        cachedValue = cache[cacheKey];

    if (!cachedValue) {

        getPromise().done(function (response) {

            console.log('got data from XHR', response);

            cache[cacheKey] = response;
            dfd.resolve(response);

        }).fail(dfd.reject);

    } else {

        console.log('got data from cache', cachedValue);

        if ($.type(cachedValue) === 'object')
            dfd.resolve($.extend(true, {}, cachedValue));
        else if ($.type(cachedValue) === 'array')
            dfd.resolve($.extend(true, [], cachedValue));
        else
            dfd.resolve(cachedValue);
    }

    return dfd.promise();
}

Sample use case:

var getter = $.ajax.bind(this, {
    url:'/echo/json/',
    data: data,
    type: 'POST'
});

getData('foo', getter).done(function(){
    getData('foo', getter);
    getData('foo', getter);
});

http://jsfiddle.net/rg5ntyt5/

Please share your thoughts regarding possible improvements


texts:
What would be the most efficient way to write the following code in Perl:

       my $index = 0;
       foreach ( @spec ) {
          if ( $module =~ m/$_/ ) {
         splice(@spec, $index, 0, $module);
             last;
          }
          $index++;
       }

This works fine but just seems a little wordy. The idea is that where I find a match for $module in the array I add an entry. I want to keep the array in a certain order and sorted.


texts: Is there a better pattern to match those words with regex?

texts:
Hello StackExchange community, I am curious if there is a better solution than mine for this exercise below:
Enter a regex that matches all the items in the first column (positive examples) but none of those in the second (negative examples).
Positive Examples:
pit
spot
spate
slap two
respite

Negative Examples:
pt
Pot
peat
part

My solution:
^[a-z](?!ar|ea)[a-z]+\s?[a-z]+
You can find the exercise here:
https://regex.sketchengine.co.uk/cgi/ex1.cgi


texts:
I've been playing around with Clojure for a while now, and one of the tasks I occasionally find awkward is parsing input.  For example, I took part in the facebook hacker cup recently, where part of the challenge was to read input like this:

5
4
..##
..##
....
....
4
..##
..##
#...
....
4
####
#..#
#..#
####
5
#####
#####
#####
#####
.....
5
#####
#####
#####
#####
#####

Where the first line is the number of "cases" to follow and the first line of each case is the number of lines in that case.  It seems fairly obvious to me that the output of parsing this should be a list of "cases", but there's no obvious way to know when to split the data without reading part of the data first.  (In this particular case I know I could look for lines with numbers vs. lines with #s, but I'm more interested in a general solution)

I ended up implementing this like:

(defn read-stdin
  []
  (line-seq (java.io.BufferedReader. *in*)))

(defn my-iterate
  [f n input]
  "Calls iterate on input and returns the final result"
  (nth (iterate f input) n))

(defn parse-grid
  "Parses a text grid of .s and #s and returns a set of coord
   pairs for each # element"
  [lines]
  (set (filter identity
      (for [[row line] (map-indexed vector lines)
            [col c] (map-indexed vector line)]
        (if (= c \#) [row col] nil)))))

(defn parse-case
  "Takes a case-array and some lines, parses out a single case,
   adds it to the case-array and returns along with the remainder of the lines.
   Meant to be used with iterate"
  [[cases [first-line & lines]]]
  (let [problem-size (read-string first-line)]
    [(conj cases {:size problem-size
                   :blacks (parse-grid (take problem-size lines))}),
     (drop problem-size lines)]))

(defn parse-cases
  [[first-line & rest-lines]]
  (let [num-cases (read-string first-line)]
    (first (my-iterate parse-case num-cases [[] rest-lines]))))

(def read-cases-stdin (comp parse-cases read-stdin))

The parse-case function is my main worry here - it feels really awkward to have to return a vector of the current case list and the rest of the input, and have to deal with unpacking it again on the next iteration of the function.  Is there a more idiomatic way of going about doing this?

Any other general feedback on my code would also be welcome.


texts: Conways Game of Life using unordered set of coordinates

texts:
Previously I had been using an array of bool(dead/live) to represent cells.  I looked on code review to see how other people have implemented Conway's Game of Life.  Someone in the comments of a post suggested using an unordered set to only store live cells.  This sounds like it would be more efficient, because only storing live cells means that the program only has to check live cells and their neighbours.  I tried it, but I am not sure if the program is more efficient the way I have implemented it.  Any suggestions are appreciated.

Grid Class

#ifndef UTILITIES_H_INCLUDED
#define UTILITIES_H_INCLUDED

#include<iostream>
#include<unordered_set>

#define dead cells_at_t.end()

namespace ConwaysGameOfLife
{
    struct Grid
    {
        private:
            std::size_t cols{25};
            std::size_t rows{25};

            int top{-cols};
            int bottom{cols};
            const int left{-1};
            const int right{1};
            const int middle{0};

            using set_of = std::unordered_set<std::size_t>;

            set_of cells_at_t{55+76,81+76,104+76,105+76,106+76,205+76,206+76,230+76,231+76};
            set_of cells_at_t_minus_one;

            std::unordered_set<int> neighbors
            {
                top+left,
                top,
                top+right,
                left,
                right,
                bottom+left,
                bottom,
                bottom+right
            };
            void rule(const std::size_t& position)
            {
                std::size_t live_neighbors{0};

                for(const auto& neighbor : neighbors)
                    //Total Neighbors
                {
                    if(cells_at_t.find(position + neighbor) != dead)
                    {
                        live_neighbors++;
                    }
                }
                if(cells_at_t.find(position) != dead && live_neighbors < 2)
                    //Underpopulation
                {
                    cells_at_t_minus_one.erase(position);
                }
                else if(cells_at_t.find(position) != dead && (live_neighbors == 2 || live_neighbors == 3))
                    //Aging of a Cell
                {
                    cells_at_t_minus_one.insert(position);
                }
                else if(cells_at_t.find(position) == dead && live_neighbors == 3)
                    //Birth of a Cell
                {
                    cells_at_t_minus_one.insert(position);
                }
                else if(cells_at_t.find(position) != dead && live_neighbors > 3)
                    //Overpopulation
                {
                    cells_at_t_minus_one.erase(position);
                }
            }
        public:
            void apply()
            {
                set_of cells;
                for(const auto& position : cells_at_t)
                {
                    if(cells.insert(position).second);
                    {
                        rule(position);
                    }
                    for(const auto& neighbor : neighbors)
                    {
                        if(cells.insert(position + neighbor).second);
                        {
                            rule(position + neighbor);
                        }
                    }
                }
                cells_at_t = cells_at_t_minus_one;
            }
            void display()
            {
                for(int r{0}; r < rows; ++r)
                {
                    for(int c{0}; c < cols; ++c)
                    {
                        if(cells_at_t.find(r * cols + c) != dead)
                            std::cout << '0';
                        else
                            std::cout << ' ';
                    }
                    std::cout << std::endl;
                }
                std::cout << std::endl;
            }
            Grid() {}
            ~Grid() {}
    };
}

#endif // UTILITIES_H_INCLUDED


texts: Displaying a certain element among inputted numbers

texts:
I prompt the user for 9 numbers, store those numbers in 9 pointers and display the element 2. It seem to work just fine, but am I forgetting something? Can I improve it but keep it simple? I'm just a beginner testing what I have learned so far.

int n;
int *array[9];
bool isUsed[10] = {0};

for(int i = 0; i < 9; i++)
{
    cout << "Enter Number " << (i + 1) << endl;
    cin >> n;
    if((n >= 0) && (n <= 9))
    {
        if (isUsed[n] == false)
        {
            array[i] = new int;
            *array[i] = n;
            isUsed[n] = true;
        }

        else
        {
            cout << "Number has already been used." << endl;
            i--;
        }
    }

    else
    {
        cout << "Numbers from 0-9 only." << endl;
        i--;
    }

}

    cout << *array[2]<<endl;


texts:
Heres a code that update weekly datas from production reports
Known flaws :

Im copy pasting the old line and replacing the week number in it to fit it to the one we want to update. The problem is that its not taking in account if cell emplacement of the data is changing.
I also tought it was simpler than re-writing all formulas in every-cell by coding every bits of formula (file emplacement, file name and cell emplacement changes every ranges)
Should i call my action if true in another sub to make this clearer?
(ex: if true, call(copy-paste-find-replace)
I have 1 code per sheet (3 sheets) cause of the ranges are hard coded and changes depending on the sheets, with your answer to (1) i could make it a single sub with variables depending on the sheet
I have a week and a half remaining to make this as clean as possible, i dont want to refactor it all the way .. :(

Heres one of the 3 code :
Sub AjoutSemaineajouterperfo()
    ' AjoutSemaineajouterperfo Macro
    ' Le code permet d'ajouter une nouvelle Semaineajouteraine

    Dim k As Long
    k = 3

    Do While (Cells(k, 3).Value <> "" And k <= 53) ' Boucle qui trouve la première ligne Semaineajouteraine vide
        k = k + 1
    Loop

    k = k - 2                                    ' La boucle while ajoute une Semaine de trop, on veut aussi revenir sur la dernière semaine rentrer (d'ou le -2)

    Dim Semaineajouter As Long
    Dim Destination As Long
    Dim Semaineavant As Long
    Semaineajouter = Cells(59, 3).Value          ' Valeur de la semaine à ajouter(case)
    Destination = Semaineajouter + 1             ' Ligne ou la prochaine semaine va se coller
    Semaineavant = Semaineajouter - 1            ' Ligne de la dernière semaine importer

    Dim semaineactuelle As Long
    semaineactuelle = WorksheetFunction.WeekNum(Now, vbMonday)

    If Semaineajouter > k And Semaineajouter <= 52 And Semaineajouter <> semaineactuelle Then
        ' Si le numéro de Semaineajouteraine entrée est plus grand que la dernière semaine ajouté  et différent de la semaine actuelle
        ' Aussi plus petit que 52 (préserver la mise en forme

        Application.EnableEvents = False
        Application.DisplayAlerts = False
        Application.ScreenUpdating = False

        ActiveSheet.Unprotect

        Dim semaineajoutertex As String
        Dim semaineavanttex As String
        semaineajoutertex = "sem " & CStr(Semaineajouter) ' Transfert des numéros de semaine en texte (pour search and replace)
        semaineavanttex = "sem " & CStr(Semaineavant)

        ' Range 1
        Dim RangeOrigine1 As String
        RangeOrigine1 = "C" & Semaineajouter & ":" & "AX" & Semaineajouter ' Range d'origine (semaine avant)
        Dim RangeDestination1 As String
        RangeDestination1 = "C" & Destination & ":" & "AX" & Destination ' Range à importer (semaine ajout)

        Range(RangeOrigine1).Copy Range(RangeDestination1)

        Range(RangeDestination1).Replace What:=semaineavanttex, Replacement:=semaineajoutertex, LookAt:=xlPart, _
                                         SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                                         ReplaceFormat:=False

        ActiveSheet.Protect

        Application.ScreenUpdating = True
        Application.DisplayAlerts = True
        Application.EnableEvents = True

    Else
        MsgBox "Entrez un numéro de Semaineajouteraine valide", vbCritical, "Ne peut exécuter"
    End If

End Sub

In this case, pressing GO would call the macro and add week 33 by copy-pasting-find-replace the line from week 32, replacing "sem 32" by "sem 33" in every
newly paste entries.


texts:
I come from a C background and am trying to learn Rust. I wrote my first Rust program, to check the battery level on my laptop and warn me if it's low/critical.

It works fine, but I  wrote it in a way I'm familiar with and was wondering if I'm missing out on some features of the Rust language that could make this more portable, more optimal, or safer.

extern crate notify_rust;
use notify_rust::Notification;
use notify_rust::NotificationUrgency;

use std::fs::File;
use std::io::prelude::*;

static CHARGE_NOW: &str =  "/sys/class/power_supply/BAT0/charge_now";
static CHARGE_FULL: &str = "/sys/class/power_supply/BAT0/charge_full";
static STATUS: &str = "/sys/class/power_supply/BAT0/status";
static CHARGING_STR: &str = "Charging";

const CHARGE_WARN: f32 = 15.0;
const CHARGE_CRIT: f32 = 5.0;
const NOTIFICATION_TIMEOUT: i32 = 4000;

fn main() {

    /* If we're charging, just exit */
    if get_str_from_file(STATUS).trim() == CHARGING_STR {
        std::process::exit(0);
    }

    let charge_level: f32 = (get_float_from_file(CHARGE_NOW) /
                             get_float_from_file(CHARGE_FULL)) * 100.0;

    if charge_level < CHARGE_WARN {
        Notification::new()
            .summary("Battery level low!")
            .body(&format!("Battery level: {0:.1$}%", charge_level, 2))
            .icon("dialog-information")
            .urgency(
                if charge_level < CHARGE_CRIT {
                    NotificationUrgency::Critical
                } else {
                    NotificationUrgency::Normal
                }
            )
            .timeout(NOTIFICATION_TIMEOUT)
            .show().unwrap();
    }
}

fn get_str_from_file(file_path: &str) -> String {
    let mut file = File::open(file_path)
        .expect("file not found");
    let mut ret = String::new();
    file.read_to_string(&mut ret)
        .expect("failed to read file");

    ret
}

fn get_float_from_file(file_path: &str) -> f32 {
    get_str_from_file(file_path).trim().parse::<f32>().unwrap()
}

Used crate: notify_rust.


texts:
The code reads in integer array from user input and builds a minimum heap via an iterative scheme.
Are there any edge cases in which this approach would fail?
For the following test case/command sequence:
1 4 3 10 12 6 -1
remove
remove
print

My output is 4 6 10 12 instead of 4 10 6 12, is this an invalid implementation?
#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>
#include <cmath>

int readheap(int* theheap) {
    std::string num;
    int val = 0;
    int size = 0;
    std::cout << "Enter the elements of heap" << std::endl;
    std::getline(std::cin, num);
    std::istringstream iss(num);
    while (iss >> val) {
        if (val != ' ' && val > 0){
            theheap[size] = val;
            ++size;
        }
    }
    if(size <= 1) {
        throw std::runtime_error("Invalid user input");
    }

for (int k = 1; k < size; ++k) {

        if (theheap[k] > theheap[(k - 1) / 2])  {
            int j = k;

            while (theheap[j] > theheap[(j - 1) / 2])  {
                std::swap(theheap[j], theheap[(j - 1) / 2]);
                j = (j - 1) / 2;
            }
        }
    }
    for (int k = size - 1; k > 0; --k) {
        std::swap(theheap[0], theheap[k]);

        int j = 0, index;

        do {
            index = (2 * j + 1);

            if (theheap[index] < theheap[index + 1] && index < (k - 1))
                ++index;

            if (theheap[j] < theheap[index] && index < k)
                std::swap(theheap[j], theheap[index]);

            j = index;

        } while (index < k);
    }
    std::cout << "Size of heap is " << size << '\n';
    return size;
}

void heapRemove(int* theheap, int& size) {
    for(int i=0; i<size-1; ++i){
        theheap[i] = theheap[i+1];
    }
    int* x = theheap;
    x = nullptr;
    delete x;
    size--;
    for (int k = 1; k < size; ++k) {

        if (theheap[k] > theheap[(k - 1) / 2])  {
            int j = k;

            while (theheap[j] > theheap[(j - 1) / 2])  {
                std::swap(theheap[j], theheap[(j - 1) / 2]);
                j = (j - 1) / 2;
            }
        }
    }
    for (int k = size - 1; k > 0; --k) {
        std::swap(theheap[0], theheap[k]);

        int j = 0, index;

        do {
            index = (2 * j + 1);

            if (theheap[index] < theheap[index + 1] && index < (k - 1))
                ++index;

            if (theheap[j] < theheap[index] && index < k)
                std::swap(theheap[j], theheap[index]);

            j = index;

        } while (index < k);
    }
}

void heapPrint(int* theheap, int size) {
    for (int i = 0; i < size; ++i){
        std::cout << theheap[i] << ' ';
    }
    std::cout << '\n';
}

int main() {
    int* theheap = new int[10];
    int size = readheap(theheap);
    heapPrint(theheap, size);
    heapRemove(theheap, size);
    heapPrint(theheap, size);
    std::cout << size << std::endl;
    return 0;
}


texts:
This is my first time messing with PHP and I tried to put together a simple address book that when the user fills out the form it would update a database table, then display the row data on the page after submission.

It works fine, but I just want to make sure I'm headed in the right direction.

index.php:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// connect to database
include("inc/dbconnect.php");

// assigns form data to table columns
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";

// execute query
if (mysqli_query($database,$assign)) {
    header("Location:http://localhost/address-book/");
    exit;
} else {
    echo "Everything blew up!" . mysqli_error($database);
}

// closes database connection
mysqli_close($database);

}

?>

<!DOCTYPE html>

<title>Address Book</title>

Address Book

            Contact name
            Email address
            Phone
            Birth Date

        <?php include("inc/records.php"); ?>

Add new contact

<form method="post" action="index.php">
    <input type="text" name="firstName" id="firstName" placeholder="First name">
    <input type="text" name="lastName" id="lastName" placeholder="Last Name">

    <input type="text" name="email" id="email" placeholder="Email address">
    <input type="text" name="phone" id="phone" placeholder="Phone">

    <input type="text" name="birthday" id="birthday" placeholder="Birthday">
    <input type="submit" value="Save record" placeholder="Save">
</form>

dbconnect.php:

// database connect
$database = mysqli_connect(
            "localhost",
            "user",
            "password",
            "database"
);

records.php:

// connects to database
include("dbconnect.php");

// targets the database table contacts
$records = mysqli_query($database,"SELECT * FROM contacts");

// pull row data from database
while($record = mysqli_fetch_array($records)) {
    echo "
";
    echo "" . $record['firstName'] . " " . $record['lastName'] . "	";
    echo "" . $record['email'] . "	";
    echo "" . $record['phone'] . "	";
    echo "" . $record['email'] . "	";
    echo "
";
}

mysqli_close($database);


texts: Function to get the most frequently appearing pixel

texts:
What i have so far is a nice and rapid algorithm for finding the pixel dominant from bmp image.
I am not sure how to make it to work.. i though it works, but the program freezes.

RGB
bitfox_get_primecolor_direct
(char *FILE_NAME)
{
    RGB primecolor;
    BYTE rgb[3];

    dword *counts = calloc(pow(256, 3), sizeof(*counts));
    dword max_count = 0;

    FILE* fp = fopen(convert(FILE_NAME), "rb");

    fseek(fp, 54, SEEK_SET);
    while (fread (rgb, sizeof(BYTE), 3, fp) != EOF)
    {
        dword idx = (((dword)rgb[0]) << 16) | (((dword)rgb[1]) << 8) | (dword)rgb[2];
        if (++counts[idx] > max_count) max_count = idx;
    }

    primecolor.R = (max_count >> 16) & 0xFF;
    primecolor.G = (max_count >> 8) & 0xFF;
    primecolor.B = max_count & 0xFF;

    free(counts);
    fclose(fp);
    return primecolor;
}

BYTE is unsigned char

RGB is struct containg BYTE R, G and B.


texts: GNUPlot Code for Plotting Three Dimensional Data

texts:
I am trying to plot three dimensional (multiple plane) data onto figures with various perspective view. The input data is tab-separated values in multiple file, and each file represent each plane. The document I referred is http://www.gnuplot.info/docs_5.4/Gnuplot_5_4.pdf .
An example is illustrated as below.
Plane1.txt
1 0 1
0 1 0
1 0 1

Plane2.txt
0 1 0
1 0 1
0 1 0

Plane3.txt
2 0 2
0 2 0
2 0 2

Is there any possible improvement of this code?
do for [LoopNumber1=0:360] {
    dir = 'View'.LoopNumber1
    command1 = "mkdir " . dir
    system command1
    do for [LoopNumber2=0:360] {
        set term jpeg size 1280,1024
        set out dir.'/GNUPlotOutput'.LoopNumber2.'.jpeg'
        set grid
        set key off
        #set logscale cb
        set view LoopNumber1,LoopNumber2

        splot for [i=1:3] 'Plane'.i.'.txt' matrix using 1:2:(i):3 with point pointtype 5 pointsize 0.75 pal
    }
}

One of the plotting result is as below.