Registering various kinds of blocks in Minecraft After looking at a few tutorials on making minecraft mods i got as far as making my own blocks and the ModBlocks class to me looks awful and unruly especially when more blocks are added:

public class ModBlocks {

public static BlockPlatinum blockPlatinum;
public static BlockNickel blockNickel;

public static void init() {
    registerPlatinum();

    registerNickel();

}

@SideOnly(Side.CLIENT)
public static void initClient(ItemModelMesher mesher) {
    registerClientPlatinum(mesher);
    registerClientNickel(mesher);
}

private static void registerClientNickel(ItemModelMesher mesher) {
    Item item = Item.getItemFromBlock(blockNickel);
    ModelResourceLocation model = new ModelResourceLocation(ModMetaData.RESOURCE_PREFIX + References.NICKEL_BLOCK,
            "inventory");
    ModelLoader.registerItemVariants(item, model);
    mesher.register(item, 0, model);
}

private static void registerClientPlatinum(ItemModelMesher mesher) {
    Item item = Item.getItemFromBlock(blockPlatinum);
    ModelResourceLocation model = new ModelResourceLocation(ModMetaData.RESOURCE_PREFIX + References.PLATINUM_BLOCK,
            "inventory");
    ModelLoader.registerItemVariants(item, model);
    mesher.register(item, 0, model);
}

private static void registerNickel() {
    ResourceLocation location = new ResourceLocation(ModMetaData.MODID, References.NICKEL_BLOCK);
    blockNickel = new BlockNickel();
    blockNickel.setRegistryName(location);
    GameRegistry.register(blockNickel);
    GameRegistry.register(new ItemBlock(blockNickel), location);
}

private static void registerPlatinum() {
    ResourceLocation location = new ResourceLocation(ModMetaData.MODID, References.PLATINUM_BLOCK);
    blockPlatinum = new BlockPlatinum();
    blockPlatinum.setRegistryName(location);
    GameRegistry.register(blockPlatinum);
    GameRegistry.register(new ItemBlock(blockPlatinum), location);
}

}

I have already tried extracting the Block* classes and putting them into a static list and then refactoring the init and client init methods to iterate over the list but that produces invisible blocks.

I am sure this is a problem long since solved by Minecraft mod devs, so if anyone has any guidance that would be awesome.

Your updated version is pretty darn good.  As in, "You're basically done, no need to make any further changes." (See note at the bottom).

The only thing I did differently (aside from creating non-normal registration methods as well that do all sorts of things) was to take two classes I already had and give them the register function: ClientProxy and CommonProxy.

My setup is such that ClientProxy.register calls super (which calls GameRegistry.register for the block as well as creating and registering the itemblock) and then calls ModelLoader.setCustomModelResourceLocation for the item (or registerItemVariants for block-variant items, or other methods for other pathways).

I later moved this code over into a library package I already had (centralizing the gains and avoiding duplication), added some static methods (in the Common) as helper redirects and ended up with this class which can be boiled down to these two methods for the basic no-nonsense blocks:

public void _registerBlockWithItem(Block block, String registryname) {
    super._registerBlockWithItem(block, registryname);
    _registerBlockResources(block);
}

private void _registerBlockResources(Block block) {
    Item item = Item.getItemFromBlock(block);
    ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(block.getRegistryName(),"normal"));
}

The first method being equivalent to your register method which self-calls your registerClient only on the client side, which then allows us to merge init and initClient.

This made my ModBlocks (well, main mod class in my case) very slim when it comes to registering blocks and items. Looks almost 1.7ish!

There are still some minor improvements which could be made, but at two-three lines per block it's a vast improvement over your original thirteen lines per block.

Note: you should also mark registerClient as @SideOnly(Side.CLIENT) as well: that method is still refers to a class that doesn't exist on the server (ModelLoader) and may crash the dedicated server when the JVM tries to load your ModBlocks class.


Pointer handle - follow-up This is a followup to:

Pointer class/handle

Please review this pointer class.

template<typename T>
class Ptr {
public:
    Ptr(T* t, int s = 1) {
        sz = s;
        p = new T[sz];
        for (int i = 0; i < sz; ++i) {
            p[i] = t[i];
        }
    }

    Ptr(const Ptr& t) {
        sz = t.sz;
        p = new T[sz];
        T* x = t.get();
        for (int i = 0; i < sz; ++i) {
            p[i] = x[i];
        }
    }

    Ptr& operator=(const Ptr& t) {
        Ptr copy{t};
        std::swap(copy.sz, sz);
        std::swap(copy.p, p);
        return *this;
    }

    Ptr(Ptr &&t) :p{t.p}, sz{t.sz} {
        t.p = nullptr;
        t.sz = 0;
    }

    Ptr& operator=(Ptr &&t) {
        std::swap(t.p,p);
        std::swap(t.sz,sz);
        return *this;
    }

    T& operator*() {
        check_range();
        return *p;
    }

    T& operator[](int i) {
        check_range(i);
        return p[i];
    }

    T* get() const {
        return p;
    }

    void operator+=(int i) {
        check_range(index+i);
        index += i;
        p+= i;
    }

    void operator-=(int i) {
        check_range(index-i);
        index -= i;
        p -= i;
    }

    Ptr operator+(int i) {
        Ptr old{*this};
        old+=i;
        return old;
    }

    Ptr operator-(int i) {
        Ptr old{*this};
        old-= i;
        return old;
    }

    Ptr& operator++() {
        operator+=(1);
        return *this;
    }

    Ptr operator++(int) {
        Ptr<T> old{p};
        operator++();
        return old;
    }

    Ptr& operator--() {
        operator-=(1);
        return *this;
    }

    Ptr operator--(int) {
        Ptr<T> old{p};
        operator--();
        return old;
    }

    ~Ptr() {
        delete[] p;
    }

private:
    T* p;
    int sz;
    int index = 0;

    void check_range(int i) {
        if (i < 0 || i > sz-1) {
            throw std::out_of_range("out of range");
        }
    }

    void check_range() {
        if (p == nullptr) {
            throw std::out_of_range("null pointer");
        }
    }

};

c++11 Allows constructor chaining:

Ptr(const Ptr& t) {
    sz = t.sz;
    p = new T[sz];
    T* x = t.get();
    for (int i = 0; i < sz; ++i) {
        p[i] = x[i];
    }
}

Can be written as:

Ptr(const Ptr& t): Ptr(t.p, t.sz) {}

Good to see you using the copy and swap idiom.

Ptr& operator=(const Ptr& t) {
    Ptr copy{t};
    std::swap(copy.sz, sz);
    std::swap(copy.p, p);
    return *this;
}

But his can be simlified by making the compiler to the copy.

Ptr& operator=(Ptr copy) {
        //   ^^^^^    Pass by value is generating a copy.
    std::swap(copy.sz, sz);
    std::swap(copy.p, p);
    return *this;
}

This looks good.

~Ptr() {
    delete[] p;
}

But you ca still move p

void operator+=(int i) {
    check_range(index+i);
    index += i;
    p+= i;               // P has changed
}

void operator-=(int i) {
    check_range(index-i);
    index -= i;
    p -= i;               // P has changed
}

Thus using it with delete after the point it changed is going to cause UB.


Method for executing any type of HQL I have written two methods that executes any type of HQL and returns data. Methods are like

public static Query getHqlQueryObject(String hql) throws Exception{

        Query query = null;
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction transaction = session.beginTransaction();
            query = session.createQuery(hql);
        } catch (Exception e) {
            System.out.println("Exception in Helper::getHqlQueryObject");
            e.printStackTrace();
        }
        return query;
    }

    public static List<Object> getHqlQueryData(Query query) throws Exception{
        List dataList = new ArrayList();
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction transaction = session.getTransaction();
            dataList = query.list();
            transaction.commit();
        } catch (Exception e) {
            System.out.println("Exception in Helper::getHqlQueryData");
            e.printStackTrace();
        }
        return dataList;
    }

I am calling this methods like this

Query query = Helper.getHqlQueryObject("from BookDetails where pkBookId = :pkBookId");
query.setParameter("pkBookId", new Long(1));
List dataList = Helper.getHqlQueryData(query);

My question is, is it right approach? or should I write session initialization code every time when I want to execute a query?

or should i write session initialization code every time when i want to execute query?

Sessions are meant to be re-used. You should not initialize a new method every time. I believe HibernateUtil.getSessionFactory().getCurrentSession(); is OK to use as that re-uses an existing session.

As for the rest of your code, I have a couple of things to say.

public static Query getHqlQueryObject(String hql) throws Exception
public static List<Object> getHqlQueryData(Query query) throws Exception

Neither of these methods actually throw an Exception. Because you have this code:

} catch (Exception e) {
    System.out.println("Exception in Helper::...");
    e.printStackTrace();
}

THIS IS BAD! A caller of your method has absolutely no guarantee that nothing went wrong. And is therefore unable to tell any potential user of your application that something did went wrong.

Simply printing the stacktrace accomplishes nothing for robustness!

Additionally, the only exception that should be able to occur is HibernateException, there is no need to catch all the other ones.

Additionally, there is no need for Transaction transaction = session.beginTransaction(); in your getHqlQueryObject. The transaction is only needed when the Query is performed, not when it is created.

Likewise, your getHqlQueryData are not guaranteed that a transaction is active.

I also have to question the usefulness of your code. Hibernate is already an abstraction and does a great job in simplifying things. What is it exactly you want to make easier with these methods?

Your current code:

Query query = Helper.getHqlQueryObject("from BookDetails where pkBookId = :pkBookId");
query.setParameter("pkBookId", new Long(1));
List dataList = Helper.getHqlQueryData(query);

How I would do it:

try {
    Query query = session.createQuery("from BookDetails where pkBookId = :pkBookId");
    query.setParameter("pkBookId", 1L);
    Transaction transaction = session.getTransaction();
    List<?> dataList = query.list();
    transaction.commit();
}
catch (HibernateException ex) {
    if (transaction.isActive()) {
         transaction.rollback();
    }
    // either re-throw the exception, wrap in another exception, or return a value indicating error.
}

You do have a session variable available here already, I hope? If not, you should remember the principle Tell, don't ask. That is, if your code needs some information, you should pass it there. I generally don't recommend calling a public static method or similar to get access to it.

By the way, I am not so sure that query.list(); needs an active transaction.

Also, when a transaction fails (an exception is thrown), you should call transaction.rollback();

And the last thing I'd like to say, with your HQL being "from BookDetails where pkBookId = :pkBookId" there is no need to return a list, you can instead call the method uniqueResult


Maximum Sub-array Problem I started taking a look at a programming challenge I had read about earlier today on 8thlight. Unfortunately, it seems to have been taken down and all I could remember about it was the problem posed: Given an array of integers, find the maximum sum of contiguous values (a sub-array).

I wanted to tackle the problem from a TDD standpoint rather than diving right in, as the poster had recommended. I didn't see his solution, but what I ended up with was remarkably like Kadane's algorithm, despite having never seen or heard of it until after writing my code and attempting to make this post.

My question is as follows: Is there some extraneous logic in here that could be refactored away? Or perhaps more critically, can you provide any test cases that break this? Some solutions I've seen now that I am searching have special restrictions, such as not being able to work with arrays full of negative numbers, while mine will solve them correctly.

public static int HighestContiguousSum(int[] inputArray)
{
    int currentSum = inputArray[0];
    int bestSum = inputArray[0];

    for (int i = 1; i < inputArray.Length; i++)
    {
      int value = inputArray[i];

      if (bestSum < 0 && bestSum < value)
      {
        bestSum = value;
        currentSum = value;
      }
      else if (value > 0 || (value < 0 && value > -1 * currentSum))
      {
        currentSum += value;
        bestSum = Math.Max(currentSum, bestSum);
      }
      else if (value <= -1 * currentSum)
      {
        currentSum = 0;
      }
    }

    return bestSum;
}

I ended up with ~11 tests, although not all of them are probably required (some were me just trying to break things after the fact to prove to myself it was working).

I wanted to tackle the problem from a TDD standpoint

and

  I ended up with ~11 tests, although not all of them are probably required (some were me just trying to break things after the fact to prove to myself it was working).

You should look at other options for example QuickCheck (Haskell), but there apparently is a F# port [fscheck][1].
Basic idea is the quickcheck asserts some invariant of the output value of a function.

Or in the same vein but more simply, why not test the following cases:
For each array with a length between 1 and 5 and whose each element is one of {-2, -1, 0, 1, 2}.
It gives you tests in 10s of thousands tests, not several;
and exhaustively searches the most interesting, albeit small, portion of the problem domain.
You can generate and store the answers or can generate them on the fly.

This is the black box part.

For white box part you can check the internal invariants of the algorithm.
You can use Debug.Assert or whatever else your compiler gives you.

  if (bestSum < 0 && bestSum < value)
  {
    bestSum = value;
    currentSum = value;
  }

...........

bestSum = Math.Max(currentSum, bestSum);

snippets are repetitive

So is value > -1 * currentSum and value <= -1 * currentSum.

Moreover, (currentSum + value) > 0 is more readable than value > -1 * currentSum.
Similarly (currentSum + value) <= 0  is more readable than value <= -1 * currentSum.
Also note there is another currentSum + value hidden in currentSum += value.

Compare

if (value < 0 && value > -1 * currentSum)
     currentSum += value;

and

if (value < 0 && (currentSum + value) > 0)
     currentSum = currentSum + value;

currentSum is called currentSum but most of the time holds the previousSum.
This isn't semantic nitpicking. Correct naming is valuable in itself,
but this also prevents you from bestSum = Math.Max(currentSum, bestSum);
right at the end of the for loop. Which is an important loop invariant.
That is expressed succinctly in a single site.
As it is, this is provided by the two bestSum= assignments mentioned above.
But it requires the reader to reason (rightly or wrongly) third clause and the conspicuously missing 4th (else) clause in the conditional analysis of the code does not break the invariant (that is bestSum remains the maximal sub-array sum).

if (bestSum < 0 && means we only encountered negative numbers and this is a special case and should be handled lower than the main cases. Or better yet do not handle this case separately.

  Is there some extraneous logic in here that could be refactored away?

I think your algorithm is not fundamentally different Kadane's algorithm, unless there is a missed case in the confusing conditional.


Conway's Game of Life in JavaScript sprawling iterative function I'm new to JS, React and functional programming and am trying to make the Game of Life in React. My cycle function looks like iterative sprawl but all my attempts to refactor have been equally bad. The full code is here.

Any recommendations to make the function more elegant or efficient or best practices tips?

cycle() {
    //a large array representing the grid with "X" for alive and "O" for dead
    let s = this.state.squares;
    let adjacents = [];
    let neighborCount = 0;
    let n = Math.sqrt(this.size);
    let births = [];
    let deaths = [];

    for (let i=0; i<s.length; i++) {

        //finds the eight neighboring squares for each square
        adjacents.push(i-1, i+1, i-n-1, i-n, i-n+1, i+n-1, i+n, i+n+1);
        for (let j=0; j<adjacents.length; j++) {
            if (s[adjacents[j]] == "X") {
              neighborCount++;
            }
        }

        //determines if the central square will be born or die in this round
        if (s[i] == "O" && neighborCount == 3) {
          births.push(i);
        }
        else if ((s[i] == "X" && neighborCount < 2)
        || (s[i] == "X" && neighborCount > 3))
        {
          deaths.push(i);
        }
        neighborCount = 0;
        adjacents = [];
    }

    //the grid array updates after all births and deaths for the round have been computed
    for (let k=0; k<births.length; k++) {
      s[births[k]] = "X";
    }

    for (let k=0; k<deaths.length; k++) {
      s[deaths[k]] = "O";
    }

    births = [];
    deaths = [];

    this.setState({
    squares: s
    })
}

Functional Techniques

The post was tagged with functional-programming but the example doesn't appear to make use of many functional-programming approaches.

You could use functional approaches when iterating over the states, like using Array.forEach(), Array.filter(), but bear in mind that each iteration involves calling a function so it won't be as efficient as using the for loops - especially considering that there are 4900 states!

For example, the loop starting with:

for (let i=0; i<s.length; i++) {
    //check adjacents to determine if death or birth
}

Could be rewritten as:

this.states.forEach(function(state, i) {
    //check adjacents to determine if death or birth
});

And this block:

for (let j=0; j<adjacents.length; j++) {
    if (s[adjacents[j]] == "X") {
        neighborCount++;
    }
}

Could be re-written utilizing Array.filter():

const neighborCount = adjacents.filter(function(adjacentIndex) {
    return s[adjacentIndex] == 'X';
  }).length;

which can eliminate the lines for initial assignment (i.e. let neighborCount = 0;) and re-assignment (i.e. neighborCount = 0;) at the end of each iteration. Note that const is used there because the value is not re-assigned (within the context of the loop).

These functional JS exercises are really helpful for those who want to learn more about using functional programming in JavaScript.

Single assignment for adjacent squares

Correct me if this leads to a difference in functionality but the array adjacents could be set with the following line:

const adjacents = [i-1, i+1, i-n-1, i-n, i-n+1, i+n-1, i+n, i+n+1];

That way it doesn't need to be re-assigned (and cleared after evaluating the neighbors) in every iteration (and the initial line let adjacents = []; can be removed from the start of cycle()).


Saving data to a session I'm a bit confused if saving the information to session code below, belongs in the controller action as shown below or should it be part of my Model?

I would add that I have other controller methods that will read this session value later.

public ActionResult AddFriend(FriendsContext viewModel)
{
    if (!ModelState.IsValid)
    {
        return View(viewModel);
    }

    // Start - Confused if the code block below belongs in Controller?

    Friend friend = new Friend();
    friend.FirstName = viewModel.FirstName;
    friend.LastName = viewModel.LastName;
    friend.Email = viewModel.UserEmail;

    httpContext.Session["latest-friend"] = friend;

    // End Confusion

    return RedirectToAction("Home");
}

I thought about adding a static utility class in my Model which does something like below, but it just seems stupid to add 2 lines of code in another file.

public static void SaveLatestFriend(Friend friend, HttpContextBase httpContext)
{
    httpContext.Session["latest-friend"] = friend;
}

public static Friend GetLatestFriend(HttpContextBase httpContext)
{
    return httpContext.Session["latest-friend"] as Friend;
}

This is something I always get confused with as well!!

I would probably think it's fine where it is but if you were considering moving it I might suggest using an interface and injecting that into the controller.  That way it doesn't matter where the latest friend information is persisted and the controller remains separate from this concern.

Although this might be overkill for your situation and example of this in use might be:

public interface IFriendProvider
{
   Friend GetLatest();
   void SaveLatest(Friend friend);
}

Your controller action might then become:

public ActionResult AddFriend(FriendsContext viewModel)
  {
        if (!ModelState.IsValid)
        {
            return View(viewModel);
        }

        // where _friendProvider has been supplied through the controller constructor
        // using DI  (See Ninject or Unity for example)
        _friendProvider.SaveLatest(new Friend()
        {
           FirstName = viewModel.FirstName;
           LastName = viewModel.LastName;
           Email = viewModel.UserEmail;
        });
}

Your implementation of the friendProvider would be something like:

public class SessionFriendProvider : IFriendProvider
{
   private readonly HttpContext __httpContext;

   // or instead of Context maybe the session object itself?
   public SessionFriendProvider(HttpContextBase context)
   {
      __httpContext = context;
   }

   public void SaveLatest(Friend friend)
   {
       _httpContext.Session["latest-friend"] = friend;
   }

   public Friend GetLatest()
   {
      return _httpContext.Session["latest-friend"] ?? new Friend();
   }
}


Amplitude and Frequencies of sound Analyser As I'm beginner with mobile/OO programming, I reached a situation that confused me and made me wonder if I was coding correctly...

The main class:

    class ViewController: UIViewController, SoundAnalyserDelegate{

        lazy var fontSize : SoundAnalyser = {
            return SoundAnalyser(delegate: self)
        }()

        @IBOutlet var frequencyLabel: UILabel!
        @IBOutlet var amplitudeLabel: UILabel!
        @IBOutlet var note: UILabel!

        override func viewDidLoad() {
            super.viewDidLoad()
            soundAnalyser.start()

        }

        func setLabelAmp (_ text:String) {

            frequencyLabel.text = text

        }

        func setLabelFreq (_ text:String) {

            frequencyLabel.text = text

        }

        func setLabelNote (_ text:String) {

            frequencyLabel.text = text

        }

And the Second class:

    class SoundAnalyser {

        var delegate:SoundAnalyserDelegate?

        let minimum = Double(160)
        let maximum = Double(1400)

        var mic: AKMicrophone
        var tracker: AKFrequencyTracker
        fileprivate var silence: AKBooster
        fileprivate var timer: Timer?
        fileprivate var notesArray: [(String, Double)]?

        init(delegate: SoundAnalyserDelegate){
            mic = AKMicrophone()
            tracker = AKFrequencyTracker(mic, hopSize: minimum, peakCount: maximum)
            silence = AKBooster(tracker, gain:0)
            notesArray = self.getNotesFrequencies()
            self.delegate = delegate

        }

        func tick(){
            let amp = tracker.amplitude
            let freq = tracker.frequency

            if amp > 0.05 && freq > minimum && freq < maximum{
                let readNote = notesArray![analyseCapturedSound()]

                delegate?.setLabelAmp(String(format:"%f", amp)) //Setting the text of a label from the UI

                delegate?.setLabelFreq(String(format:"%f", freq))

    //            delegate?.setLabelNote(String(format:"%f", readNote))

                print("freq:", freq," amp:", amp," NOTE: \(readNote)")
            }
        }

I just included the most important code to express what I am trying to ask.

Summary:
Class ViewController initiates SoundAnalyser.
Under SoundAnalyser, there's a function that executes a function from ViewController ("delegate?.setLabel..."). I've made it with a delegate class using protocol, but I don't know why I feel that something is wrong.. I mean, executing a method of its creator... is it right? If not, what's the most 'good citizen' way to implement something with the same result?

This is mostly correct. The reasoning for using delegates is that the class should inform its delegate, not instruct it. A symptom of this is that SoundAnalyser is formatting the text, which should be the responsibility of the view controller.

Consider the SoundAnalyzer to be filling the role of the model in the MVC pattern. The model is only responsible for providing data, and should not be concerned with reinterpreting the data for display.

You can use a helper class to encapsulate formatting if the functionality is needed in multiple places.

Examples

SoundAnalyserDelegate: The delegate methods are in the form of advisory notifications or events, instead of instructions. The delegate receives data, instead of pre-formatted text. This can be further improved by passing an aggregate object if the frequency and amplitude always change at the same time (which seems to be the case):

struct SoundAnalyserSample {
    let frequency: Double
    let amplitude: Double
}

protocol SoundAnalyserDelegate {
    func soundAnalyserSample(sample: SoundAnalyserSample)
    // ... and so on
}

SoundAnalyser: Notify the delegate passing a sample.

func tick(){
    let amp = tracker.amplitude
    let freq = tracker.frequency

    if amp > 0.05 && freq > minimum && freq < maximum {
        let readNote = notesArray![analyseCapturedSound()]
        let sample = SoundAnalyserSample(
            frequency: freq,
            amplitude: amp
        }
        delegate?.soundAnalyserSample(sample: sample)
    }
}

ViewController: The view controller responds to notifications from the sender (the sound analyser in this case), formats the data, and updates the UI. Note that you also need to ensure that the UI update occurs on the main queue, which is not necessarily guaranteed by the caller.

class ViewController: UIViewController, SoundAnalyserDelegate {

    func soundAnalyserSample(sample: SoundAnalyserSample) {
        DispatchQueue.main.async {
            let frequencyText = String(format:"%f", sample.frequency)
            let amplitudeText = String(format:"%f", sample.amplitude)
            frequencyLabel.text = frequencyText
            amplitudeLabel.text = amplitudeText
        }
    }


Validating a model that requires database access Let's say I have this User model:

class User
{
    public $id;
    public $email;
    public $password;
    public $errors;

    public function isValid()
    {
        if (strpos($this->email, '@') === false) {
            $this->errors['email'] = 'Please enter an email address';
        }
        if (!$this->password) {
            $this->errors['password'] = 'Please enter a password';
        } elseif (strlen($this->password) < 4) {
            $this->errors['password'] = 'Please enter a longer password';
        }

        return !$this->errors;
    }
}

And let's say I have this UserDAO for retrieving, adding, updating, and deleting users:

class UserDAO
{
    protected $conn;
    protected $logger;

    public function __construct(PDO $dbh, Logger $logger)
    {
        $this->dbh = $dbh;
        $this->logger = $logger;
    }

    public function getUsers()
    {
        $rows = null;
        try {
            $rows = $this->dbh->query("SELECT * FROM users")->fetchAll();
        } catch (PDOException $e) {
            $this->logger->log($e->getMessage(), __METHOD__);
        }
        return $rows;
    }

    public function getUserById($id)
    {
        $row = null;
        try {
            $sth = $this->dbh->prepare("SELECT * FROM users WHERE id = ?");
            $sth->execute(array($id));
            $row = $sth->fetchObject('User');
        } catch (PDOException $e) {
            $this->logger->log($e->getMessage(), __METHOD__);
        }
        return $row;
    }

    public function addUser(User &$user)
    {
        $success = false;
        try {
            $sth = $this->dbh->prepare("
                INSERT INTO users (email, password) VALUES (?, ?)
            ");
            $sth->execute(array($user->email, $user->password));
            if ($success = (bool) $sth->rowCount()) {
                $user->id = $this->dbh->lastInsertId();
            }
        } catch (PDOException $e) {
            $this->logger->log($e->getMessage(), __METHOD__);
        }
        return $success;
    }

    public function updateUser(User $user)
    {
        // ...
    }

    public function deleteUser($id)
    {
        // ...
    }

    public function isEmailUnique($email)
    {
        $count = 0;
        try {
            $sth = $this->dbh->prepare("SELECT COUNT(id) FROM users WHERE email = LOWER(?)");
            $sth->execute(array($email));
            $count = $sth->fetchColumn();
        } catch (PDOException $e) {
            $this->logger->log($e->getMessage(), __METHOD__);
        }
        return !$count;
    }
}

When I process a form, I typically do something like this:

// ...

$userDAO = new UserDAO($dbh, $logger);
$user = new User();
$user->email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$user->password = filter_input(INPUT_POST, 'password');
// validate user
if ($user->isValid()) {
    // check if email address is unique (SO UGLY!)
    if ($userDAO->isEmailUnique($user->email)) {
        $user->errors['email'] = 'Please use a different email address';
    }
    // save user
    if ($user->addUser($user)) {
        // ...
    } else {
        // ...
    }
} else {
    // do something with $user->errors
}

This works great for simple cases, but how can I improve this? In particular, how can I do validations that require database access? For example, if I wanted to check that the email is unique and make it part of my validation, what would be a better way of doing this?

Best approach would be to have another Object to do the validation based on specific configuration.

Your User should NOT be responsible for validating itself, neither should the DAO.
Validation is a specific task and should be handled by a specific Class.

Example of this approach would be something like this (omitiong interfaces for brevity):

validation class

Class Validator
{
   protected $errors = [];

   public function __construct(DaoInterface $daoDependency, $otherDependency)
   {
      //...
   }

   public function validate($object, array $rules)
   {
       foreach ($rules as $rule)
       {
           $propertyName = $rule['property'];
           if (!$this->isValidateProperty($object, $propertyName, $rule['config'])) {
               $this->errors[$object->$propertyName] = 'is invalid ' . $rule['message'];
           }
       }
   }

   public function isValid()
   {
       return (bool)count($this->errors);
   }

   public function getErrors()
   {
       return $this->errors;
   }

   protected function isValidProperty($object, $propertyName, $ruleConfig)
   {
       // $ruleConfig should have information about what validation you want to use and relevant validation should be executed base on it (it can separate objects etc)
       if (!property_exists($object, $propertyName)
          throw new MissingPropertyException();

       if (isset($ruleConfig['email-unique-in-db') {
           if ($daoDependecny->emailExists($object->$propertyName) {
               return false;
           }
       }
       if (isset($ruleConfig['email-is-valid') {
           return (bool)strpos($object->$propertyName, '@');
       }
       // ... etc but better with objects for each validation type.
   }
}

usage

$userDAO = new UserDAO($dbh, $logger);
$user = new User();
$user->email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$user->password = filter_input(INPUT_POST, 'password');

// get your validation rules
// you can have them stored in other object, plain array, yml whatever you like. for instance $rules = new UserConstrains(); or
$rules['config] = [
  'email' => [
      'email-unique-in-db',
      'email-is-valid'
  ],
  'otherfield' => [
      'callback' => ['someCallbackFunction']
  ]
];

// create validator
$validator = new Validator($userDao, $otherDepenency);
$validator->validate($user, $rules);
// validate user

if (validator->isValid()) {
   // .. do stuff
} else {
   // do something with $user->errors
}

The separation of concerns is the most important thing here.
You can extend/decorate the validator class for specific use cases

Also if would recommend using some specialized validation library for this task for instance symfony2 validation component can be used stand alone: http://symfony.com/doc/current/book/validation.html


Is it effective to use get; set; to avoid redundant processes? I wanted to avoid running the code HttpContext.Current.Server.MapPath every time file_path_includes is called.

Is the below an effective way of doing so?

private static string file_path_includes_;
public static string file_path_includes
{
    get
    {
        if (file_path_includes_ == null)
            file_path_includes_ = HttpContext.Current.Server.MapPath("/_includes") + @"\";
        return file_path_includes_;
    }
}

So the better implentation would be a static constructor as such:

public static string file_path_includes;

static ParentClassName()
{
    file_path_includes = HttpContext.Current.Server.MapPath("/_includes") + @"\";
}

Is it best to initialize a static member once, in a static constructor. If that is not possible, then a lazy initialization can be done like this. (Similar code to yours, just using the null coalescing operator.)

private static string file_path_includes_;

public static string file_path_includes
{
    get
    {
        return
            file_path_includes_ ??
                (file_path_includes_ = HttpContext.Current.Server.MapPath("/_includes") + @"\");
    }
}


Can I avoid nested for loop in this case? this code works fine but i want to know if this can be improved in any manner .

For every user I am fetching the namesList corresponding to that user and for each fetched nameList , i am fetching the ItemsList .

I have tried to replicate the sample using this below standalone program as i cant paste my project code as it got huge dependencies

So i am hardcoding the users and the names List corresponding to that user .

package com;

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

public class Test {

    public static void main(String args[]) {
        List<String> users = new ArrayList<String>();
        users.add("user101");
        users.add("adminuser");

        for (String user : users) {
            try {
                ArrayList<String> namesCorrespondingtoUser = getNamesCorrespondingtoUser(user);
                for (String Id : namesCorrespondingtoUser) {

                    List<String> Items = getItemsCorrespondingtoId(user, Id);

                    filter(Items, user,Id);
                }
            } catch (Exception e) {
            }
        }
    }

    public static ArrayList<String> getNamesCorrespondingtoUser(String userName)
            throws Exception {
        ArrayList<String> names = new ArrayList<String>();
        if (userName.equals("user101")) {
            names.add("UBSC1");
            names.add("HDBG1");
            names.add("GHYU1");
        }
        if (userName.equals("adminuser")) {
            names.add("UBSC1");
            names.add("HDBG1");
            names.add("GHYU1");
        }
        return names;

    }

    public static List<String> getItemsCorrespondingtoId(String userName,
            String Id) throws Exception {
            ArrayList<String> items = new ArrayList<String>();
        return items ;
    }

    private static void filter(List<String> Items, String user,String Id) {

// do something with the ID value of that User .

    }

}

I've seen, that you made up this code as an example, so I hope, that this is not your production code:

public static ArrayList<String> getNamesCorrespondingtoUser(String userName)
        throws Exception {
    ArrayList<String> names = new ArrayList<String>();
    if (userName.equals("user101")) {
        names.add("UBSC1");
        names.add("HDBG1");
        names.add("GHYU1");
    }
    if (userName.equals("adminuser")) {
        names.add("UBSC1");
        names.add("HDBG1");
        names.add("GHYU1");
    }
    return names;

}

If you take a look at both blocks, they are the same, aren't they?
But for further improvement, I would suggest working with a Map where you have usernames as the key and the according List of Names as the result.

Second: I would reccomend you to take a look at Google's Guava Library esp. the section about predicates .

Third: I am wondering, how you could retrieve any correct item. As far as I can see your names have to be unique to resolve the correct items. The collision rate for (nick-)names is generally high. So it would be better to switch to some ID-mechanism.

Fourth: The task is in itself nested; you need to iterate over a list of items and over a list of users. So you couldn't "avoid" a nested loop. Okay: If you let a database do the magic, you didn't loop at all - the database does. But I think, that is not the answer you wanted.


8086 ASM Bresenham's Line Algorithm As part of a first year university course in computer architecture some time ago we were tasked with learning 8086 ASM.  The final course work required creating a small animation of shapes moving around the screen changing colours and the like.

As I would not expect anyone to review 720 lines of assembler I'm just going to provide my implementation of Bresenham's Line Algorithm.

Note that this is not the entire program but a single macro from the working program.

Also note that at the time of writing I had little to no experience with 8086 ASM (I still don't in fact), but I'm very interested in knowing how I did and how it could have been improved upon.

If anyone is interested in reviewing the rest of the project as well (it can be done in small parts) then let me know.

;=========================================================================================================
;                       BRESENHAM LINE ALGORITHM (lx1,ly1)-(lx2,ly2)
;=========================================================================================================
line macro lx1, ly1, lx2, ly2
    local ldxsetup1, ldxsetup2, ldysetup1, ldysetup2
    local lxisetup1, lxisetup2, lxisetupexit, lyisetup1, lyisetup2, lyisetupexit
    local numsetup1, numsetup2, numsetupexit
    local lloopstart, lloopif, lloopifexit, lloopend
    pushall
    mov ax, lx2
    sub ax, lx1
    cmp ax, 0
    jge ldxsetup2
ldxsetup1:
    mov bx, -1
    mul bx
ldxsetup2:
    mov ldx, ax
    mov ax, ly2
    sub ax, ly1
    cmp ax, 0
    jge ldysetup2
ldysetup1:
    mov bx, -1
    mul bx
ldysetup2:
    mov ldy, ax
    mov ax, lx1
    mov lx, ax
    mov ax, ly1
    mov ly, ax
    mov ax, lx2
    cmp ax, lx1
    jge lxisetup1
    jmp lxisetup2
lxisetup1:
    mov ax, 1
    jmp lxisetupexit
lxisetup2:
    mov ax, -1
lxisetupexit:
    mov lxi1, ax
    mov lxi2, ax
    mov ax, ly2
    cmp ax, ly1
    jge lyisetup1
    jmp lyisetup2
lyisetup1:
    mov ax, 1
    jmp lyisetupexit
lyisetup2:
    mov ax, -1
lyisetupexit:
    mov lyi1, ax
    mov lyi2, ax
    mov ax, ldx
    mov bx, ldy
    cmp ax, bx
    jge numsetup1
    jmp numsetup2
numsetup1:
    mov ax, 0
    mov lxi1, ax
    mov lyi2, ax
    mov ax, ldx
    mov lden, ax
    mov lnumpix, ax
    shr ax, 1
    mov lnum, ax
    mov ax, ldy
    mov lnumadd, ax
    jmp numsetupexit
numsetup2:
    mov ax, 0
    mov lxi2, ax
    mov lyi1, ax
    mov ax, ldy
    mov lden, ax
    mov lnumpix, ax
    shr ax, 1
    mov lnum, ax
    mov ax, ldx
    mov lnumadd, ax
numsetupexit:
    mov ax, lnum
    mov dx, 0
lloopstart:
    cmp dx, lnumpix
    jg lloopend
    plot lx, ly
    add ax, lnumadd
    cmp ax, lden
    jge lloopif
    jmp lloopifexit
lloopif:
    sub ax, lden
    mov bx, lx
    add bx, lxi1
    mov lx, bx
    mov bx, ly
    add bx, lyi1
    mov ly, bx
lloopifexit:
    mov bx, lx
    add bx, lxi2
    mov lx, bx
    mov bx, ly
    add bx, lyi2
    mov ly, bx
    inc dx
    jmp lloopstart
lloopend:
    popall
endm
;=========================================================================================================

Here's the definitions of pushall and popall:

;=========================================================================================================
;                       PUSH ALL DATA TO STACK
;=========================================================================================================
pushall macro
    push ax
    push bx
    push cx
    push dx
endm
;=========================================================================================================
;=========================================================================================================
;                       POP ALL DATA FROM STACK
;=========================================================================================================
popall macro
    pop dx
    pop cx
    pop bx
    pop ax
endm
;=========================================================================================================

These are just some quick thoughts, not a detailed analysis.

Comments.  Enough said.
If a conditional jump (like jge) is not taken, execution just continues with the next instruction.  So this seems redundant (likewise with numsetup1):

    jge lxisetup1
    jmp lxisetup2
lxisetup1:

could be written as:

    jl lxisetup2

You are repeatedly moving -1 into registers and using it in other ways.  Why not make use of an additional register (say si)?  Set it to -1 at the top of this routine (remember to push/pop it if your calling convention requires it) and use it as needed: mul si, mov ax, si.
A common shortcut for zeroing registers is xor ax, ax.  Produces slightly smaller code.
Looking at your final loop, you have:

lloopstart:
    cmp dx, lnumpix
    jg lloopend
    inc dx
    jmp lloopstart
lloopend:

This means that you will be doing 2 jumps in a row (jmp lloopstart, jg lloopend).  An alternative might be:

    cmp dx, lnumpix
    jg lloopend
lloopstart:
    inc dx
    cmp dx, lnumpix
    jle lloopstart
lloopend:

Instead of having your loop count up (for x=0 to 10), sometimes having your loop count down to zero (for x=10 to 0) can produce (slightly) more efficient code (not sure it would work in this case):

mov dx, lnumpix
lloopstart:
    dec dx
    jnz lloopstart


Group orders with Ramda I made some crude code using RamdaJS to essentially group orders by their states. There are some nested structures. Currently, I have a working code, but I wondering if Ramda can perhaps help to clean that up more? I've added TypeScript annotations to present (simplified) structures more clearly.

I've also prepared codesandbox with example data: https://codesandbox.io/s/yqwm2p65zz

import * as R from 'ramda'

export default function(orders: Order[], orderListing: OrderListing[]) {
  const pluckStateEnum = (orderState: OrderState) => orderState.enum

  const ordersByState = (states: OrderStateEnum[]) =>
    orders.filter(
      (order: Order) =>
        !R.isEmpty(
          R.intersection(R.map(pluckStateEnum, order.orderStates), states),
        ),
    )

  return orderListing.map(listing => ({
    id: listing.id,
    orders: ordersByState(listing.orderStateEnums).map(order => order.id),
  }))
}

interface Order {
  id: string
  orderStates: OrderState[]
}

interface OrderState {
  enum: OrderStateEnum
}

interface OrderListing {
  id: string
  orderStateEnums: OrderStateEnum[]
}

type OrderStateEnum =
  | 'RECEIVED'
  | 'PAID'
  | 'UNPAID'
  | 'CUSTOMER_NOTIFIED'
  | 'FINISHED'

First, a couple Typescript notes:

I assume you cannot change the data format, if you can, I would highly recommend renaming the enum property. enum is a keyword in Typescript.
OrderStateEnum should be represented as an actual enum. I'd also consider dropping the Enum suffix.

enum OrderStateEnum {
  RECEIVED = 'RECEIVED',
  PAID = 'PAID',
  UNPAID = 'UNPAID',
  CUSTOMER_NOTIFIED = 'CUSTOMER_NOTIFIED',
  FINISHED = 'FINISHED'
}

Avoid default exports - see Typescript Deep Dive

You are correct, Ramda can help simplify this code.

pluckStateEnum is equivalent to R.prop('enum')
ordersByState can have the nesting level reduced, additionally, checking if the intersection of two arrays is empty can be better represented with R.any(R.contains(R.__, arr1), arr2). I also use chain to flatten the array while getting properties.

const ordersByState = states => orders.filter(R.pipe(
  R.prop('orderStates'),
  R.chain(R.prop('enum')),
  R.any(R.contains(R.__, states))
))

With this change, the function becomes much easier to read. See the repl.

For completeness, here is how I would implement this function:

function group(orders, orderListing) {
  const ordersByState = states => orders.filter(R.pipe(
    R.prop('orderStates'),
    R.chain(R.prop('enum')), // you might know this as flatMap
    R.any(R.contains(R.__, states))
  ))

  return orderListing.map(listing => ({
    id: listing.id,
    orders: ordersByState(listing.orderStateEnums).map(R.prop('id')),
  }))
}


Semantic implementation of the structure of a web page with header, main, and footer I'm new to web development, and currently learning the basics of HTML and CSS. Many web pages follow the structural pattern of header, main, and footer; so I figured it'd be a good idea to try and implement this structure to see how things are carved.

body {
  display: flex;
  flex-direction: column;
  font-family: sans-serif;
  margin: 0;
  min-height: 100vh;
}

header,
footer {
  background-color: dodgerblue;
  color: white;
  text-align: center;
}

main {
  background-color: snow;
  flex: 1;
  padding: 1rem;
}

footer {
  margin-top: auto;
}
<!DOCTYPE html>

  <title>Test</title>
  <link rel="stylesheet" href="main.css">
  <meta charset="UTF-8">

Header

Main content

Footer

I'm looking for all kinds of feedback, from style, to anti-patterns, ways to do things more concisely, and whatever other observation you can find useful. I do have some specific questions:

Are the semantic HTML elements used correctly? There's no need for an article element inside the main element, right?
In the CSS I selected both header and footer for stuff that they have in common, is this good practice? Or should I keep a single header and a single footer selectors, separately? Could be more maintainable that way?
Is this normally handled using Flexbox? Or is Grid display a better tool for this?
What things would you do differently?

I myself am also a beginner in the world of web development (So any comments about my answer are more than welcome!)
But maybe my tips can still be useful in one way or another. ;-}
The first thing that came to mind is your header and footer element question about grouping them together that way in CSS because they have things in common...My short answer is no, I would change my HTML element for these, or better said, add a class or id attribute, and group it together this way.
Example:
 .....
         .....

CSS example:
 .header, topAndBottom {
.......
}

I personally prefer the class attribute over the id, because you can use it more often in your HTML, the id attribute is once or maybe twice acceptable in your HTML(Not my rules)
Or you can only style your
 inside your header and the
 inside your footer, I would recommend this if it is mainly text that you want to style.
And one tiny comment about the order in your CSS, and this is purely personal, but maintain the order from your HTML in your CSS for better reading, especially when your code will be more advanced and complex.
Good luck with your learning for web development! I started also not long ago and I am addicted!


Computing the Fourier transform of a distribution of electron charge (represented by atomic positions in space) I am computing a nested loop operation using OpenCL (open computing language). My main question is, given the code outlined below, how might I optimize the speed and efficiency of using the GPU, for instance by using local memory calls instead of global ones?

Given some input vector \$V=(v_x, v_y, v_z)\$ (in math terms, the input vector is a point in reciprocal space where we evaluate the Fourier transform),  the desired computation involves iterating over a collection of atoms in space (of different species, like Hydrogen, Oxygen, etc.) and using the input vector to compute a function. Each atom is described by a 4-tuple, consisting of 3 spatial coordinates, \$A=(a_x, a_y, a_z)\$, and 1 species identifier, species_id, which ranges from 0 to the number of unique atom species.

The iterations look like this (in pseudocode):

for V in input_vectors:
    ft_magnitude = 0
    for (A, species_id) in atoms:
        ft_magnitude += get_scale_factor(V, species_id) * exp( -i * dot(A,V))

where i in the exponential is the complex number \$i=\sqrt{-1}\$, the term dot(A,V) is the dot product of two vectors \$A \cdot V = a_x \cdot v_x + a_y \cdot v_y + a_z \cdot v_z\$, and get_scale_factor(V,species_id) is a lookup operation which returns the correct, pre-computed scale factor, which changes with each vector V and species_id.

The idea of using a GPU for this problem is to let each GPU worker compute the output for one vector V. I wrote a kernel posted below to be used with OpenCL, after following several examples I saw online.

The inputs to the kernel are the following:

input_vectors which has length 3*n_vectors, 3 per input vector
atoms which has length 4*n_atoms, 4 per atom
scale_factors which has length n_species * n_vectors , 1 per atom species per input vector
outputs which has length 2*n_vectors, 1 complex number per input vector, representing the Fourier transform magnitude

Here is the kernel (note the use of cosine and sine to evaluate the complex exponential using Euler's formula) :

__kernel void compute(
__global float *input_vectors,
__global float *atoms,
__global float *scale_factors,
__global float2 *outputs,
const int n_vectors,
const int n_atoms){

int i_v = get_global_id(0);

if ( i_v < n_vectors) {

    float vx = input_vectors[i_v*3];
    float vy = input_vectors[ i_v*3+1];
    float vz = input_vectors[ i_v*3+2];

    for (int i_a=0; i_a< n_atoms; i_a++){

        float ax = atoms[ i_a*4];
        float ay = atoms[ i_a*4+1];
        float az = atoms[ i_a*4+2];
        int species = atoms[i_a*4+3];
        float factor = scale_factors[ species * n_vectors + i_v ];

        float dot = vx*rx + vy*ry + vz*rz;

        outputs[i_v].x += factor*native_cos(-dot);
        outputs[i_v].y += factor*native_sin(-dot);
        }
    }
}

I am using PyOpenCL to wrap to the kernel but could be convinced to switch to something else if it would get speedups. To give a sense of scale, typically, n_vectors is on the order of 1,000,000, and n_atoms is on the order of 100,000, with about 10 different atom species.

Here is the GPU information for the machine I am using:

81:00.0 3D controller: NVIDIA Corporation GK110BGL [Tesla K40m] (rev a1)
Subsystem: NVIDIA Corporation 12GB Computational Accelerator
Physical Slot: 4
Flags: bus master, fast devsel, latency 0, IRQ 64
Memory at fa000000 (32-bit, non-prefetchable) [size=16M]
Memory at 27800000000 (64-bit, prefetchable) [size=16G]
Memory at 27c00000000 (64-bit, prefetchable) [size=32M]
Capabilities: <access denied>
Kernel driver in use: nvidia
Kernel modules: nvidia, nouveau, nvidiafb

The most immediate optimization is to use coalesced reads by switching to array of structs form to structure of arrays.


Given bit strings, perform a bitwise addition I'm looking for code-review, optimizations and best practices. This code is a Java adaptation of code on geeksforgeeks.org. Please verify if space complexity is \$O(n)\$ where n is number of bits, and aux complexity is \$O(1)\$, since no temporary space was needed. Whatever space was needed was used for return value not for temporary purpose. Rectify my understanding of space and aux complexity if wrong.

public class AddBinaryStrings {

    public static String addBinaryStrings(String num1, String num2) {

        final StringBuilder sum = new StringBuilder(Math.max(num1.length(), num2.length()) + 1);
        String shortNum;
        String longNum;
        if (num1.length() < num2.length()) {
            shortNum = num1;
            longNum = num2;
        } else {
            shortNum = num2;
            longNum = num1;
        }

        int carry = 0;
        int i = longNum.length() - 1;
        int j = shortNum.length() - 1;

        for (; j >= 0; j--, i--) {
            int num1Digit = longNum.charAt(i) - '0';
            int num2Digit = shortNum.charAt(j) - '0';

            sum.append(num1Digit ^ num2Digit ^ carry);
            carry = (num1Digit & num2Digit) | (num1Digit & carry) | (num2Digit & carry);
        }

        for (; i >= 0; i--) {
            int num1Digit =  longNum.charAt(i) - '0';
            sum.append(num1Digit ^ carry);
            carry = num1Digit & carry;
        }

        if (carry == 1) {
            sum.append(1);
        }

        return sum.reverse().toString();
    }
}

public class AddBinaryStringTest {

    @Test
    public void testCarry() {
        assertEquals("1000" , AddBinaryStrings.addBinaryStrings("101","11"));

    }

    @Test
    public void testNoCarry() {
        assertEquals("1101", AddBinaryStrings.addBinaryStrings("1000", "101"));
    }

}

Please verify if space complexity is O(n) where n is number of bits, and aux complexity is O(1), since no temporary space was needed. Whatever space was needed was used for return value not for temporary purpose. Rectify my understanding of space and aux complexity if wrong.

Wrong.

Let's use another example. Bubble-sort uses \$O(1)\$ auxiliary space complexity. Bubble-sort does an "in-place sort", it does not require additional space except for a single temp variable.

Auxiliary means "helper". In the case of your code, the "helper" is the return value. The auxiliary space complexity of your code is \$O(n)\$.

Also remember this line:

return sum.reverse().toString();

How could you possibly reverse a string without storing the string in the first place? The space required to store this String is \$O(n)\$

There is an article on Geeks for Geeks explaining this and a question on Stack Overflow about it.

Auxiliary space ignores the size of the input, not the output.


Calling a Luhn check function when a credit card field changes I feel like I should not be duplicating the code to gather the credit card number, but I am not sure how best to do it. Any suggestions?

$('input[name="payment\[cc_number\]"]').keyup(function() {
    var ccNum = $(this).val();
    ccNum = ccNum.replace(/[^\d]/g, '');
    setSelectValue(ccNum);
});

$('input[name="payment\[cc_number\]"]').blur(function(ccNum) {
    var ccNum = $(this).val();
    ccNum = ccNum.replace(/[^\d]/g, '');
    if (!luhnCheck(ccNum)) {
        alert('Please enter a valid credit card number.');
    }
});

$(function() {
  // Always select a context and use it as the second parameter
  // it will make everything far faster and less prone to errors
  var form = $('form');
  var stripCcNum = function(el) {
      return $(this).val().replace(/[^\d]/g, '');
  }

  $('input[name="payment\[cc_number\]"]', form).keyup(function() {

    setSelectValue(stripCcNum(this));

  }).blur(function(ccNum) {

    if (!luhnCheck( stripCcNum(this) )) {
        alert('Please enter a valid credit card number.');
    }

  });

});

Or for the totally and absolute 1337 (meaning you shouldn't do it for something this simple but it demonstrates some useful techniques)

$(function() {
  var form = $('form'),
    handleCcNum = function(doThis) {
      return function() {
        doThis.call(this, $(this).val().replace(/[^\d]/g, ''));
      }
    }

  $('input[name="payment\[cc_number\]"]', form)
    .keyup( handleCcNum(function(num) { setSelectValue(num); } )
    .blur( handleCcNum(function(num) {
       !luhnCheck(num) && alert('Please enter a valid credit card number.');
    }));
});


Simple average grade calculator I'd like this code to be minimized, while displaying the exact same stuff.

Specifically, on how to remove some of the repetitions made within the code (such as "if, else if") etc. using other statements or making the compiler go through it faster, as I feel like I lack the experience and the knowledge to do this without messing up everything (such as using switch & case).

For example, when I test for "tf", I'd like not to be forced to repeat the "average" depending on whether or not we add the "TEZA" grade.

#include <iostream>
using namespace std;
int main()

{
    string sub, tf;
    int m1, m2, m3, m4, sum, TEZA;
    double avg, tzm;

    cout << "SIMPLE AVERAGE CALCULATOR";
    cout << "\n" << "\n" << "Subject at hand?: ";
    cin >> sub;
    cout << "\n" << "Input the FOUR marks you'd like verified: " << "\n";
    cout << "\n" << "M1: ";
    cin >> m1;
    cout << "\n" << "M2: ";
    cin >> m2;
    cout << "\n" << "M3: ";
    cin >> m3;
    cout << "\n" << "M4: ";
    cin >> m4;
    cout << "\n" << "Would you like to include the TEZA grade?(Y/N): ";
    cin >> tf;

    sum = m1 + m2 + m3 + m4;
    avg = (double) sum / 4;

    if (tf == "Y" | tf == "y")
    {
        cout << "What is the TEZA grade?: ";
        cin >> TEZA;
        int tzm = ((double) avg * 3 + TEZA) / 4;
        cout << "\n" << "Your average grade at " << sub << " is " << tzm << "\n"
             << "\n";

        cout << "You got the following mark: ";
        if (tzm >= 9 && tzm <= 10)
            cout << "A" << "\n";
        else if (tzm >= 8 && tzm <= 9)
            cout << "B" << "\n";
        else if (tzm >= 7 && tzm <= 8)
            cout << "C" << "\n";
        else if (tzm >= 6 && tzm <= 7)
            cout << "D" << "\n";
        else if (tzm >= 5 && tzm <= 6)
            cout << "E" << "\n";
        else if (tzm < 5)
            cout << "F" << "\n";

        if (tzm >= 5)
        {
            cout << "DO YOU PASS: " << "\n";
            cout << "Yes." << "\n";
        }
        else
            cout << "No." << "\n";
    }

    else

    {
        cout << "\n" << "Average at " << sub << " is " << avg << "\n" << "\n";

        cout << "You got the following mark: ";
        if (avg >= 9 && avg <= 10)
            cout << "A" << "\n";
        else if (avg >= 8 && avg <= 9)
            cout << "B" << "\n";
        else if (avg >= 7 && avg <= 8)
            cout << "C" << "\n";
        else if (avg >= 6 && avg <= 7)
            cout << "D" << "\n";
        else if (avg >= 5 && avg <= 6)
            cout << "E" << "\n";
        else if (avg < 5)
            cout << "F" << "\n";

        cout << "\n" << "DO YOU PASS?: " << "\n";

        if (avg >= 5)
            cout << "Yes." << "\n";
        else
            cout << "No." << "\n";

    }
}

Bug

This calculation looks suspiciously buggy:

int tzm = ((double) avg * 3 + TEZA) / 4;

Why are you taking avg, which is already a double, and casting it to a double?  Furthermore, why are you taking the right-hand side, which is a double, and coercing it into an int variable?  Note that you had declared double tzm earlier in the code; this int tzm declaration shadows the earlier declaration.  Your compiler should have warned you that the tzm on line 8 is unused.  (You do compile with warnings enabled, right?  It's a good habit.)

In any case, you should write a comment explaining why the tzm formula is the way it is.  I don't understand the calculation.

By the way, you can get floating-point division without explicitly casting, simply by writing / 4.0.

Using the bitwise | operator in tf == "Y" | tf == "y" is not really appropriate; it should be a logical || operator.

Optimization

There is absolutely no point in optimizing this code for performance.  Nearly all of the time is going to be spent waiting for input; the calculations are trivial.

What you should do, though, is to optimize it for elegance and readability.

The key is to identify functionality within main() that can be extracted out into functions, so that main() no longer has any tedious details.  For example, a common pattern is printing a question, and expecting a response from the user.  I'd define three functions, to ask the user for string, integer, and yes/no responses.

I would also define a letterGrade() function so that all of the results can be reported using just one statement.

Avoid cluttering your code with variables that don't mean much.  I'd get rid of sum and tf, for example.  The tzm variable is simply a recalculated average of sorts, so I'd get rid of it too.

Suggested solution

#include <iostream>
#include <string>

std::string ask(const std::string& prompt) {
    std::string answer;
    std::cout << prompt;
    std::cin >> answer;
    return answer;
}

int askInt(const std::string& prompt) {
    int answer;
    std::cout << prompt;
    std::cin >> answer;
    return answer;
}

bool askYN(const std::string& prompt) {
    std::string answer = ask(prompt);
    return answer == "Y" || answer == "y";
}

std::string letterGrade(double grade) {
    return (grade > 10) ? "" :
           (grade >= 9) ? "A" :
           (grade >= 8) ? "B" :
           (grade >= 7) ? "C" :
           (grade >= 6) ? "D" :
           (grade >= 5) ? "E" : "F";
}

int main() {
    std::cout << "SIMPLE AVERAGE CALCULATOR\n\n";
    std::string subject = ask("Subject at hand?: ");

    std::cout << "\nInput the FOUR marks you'd like verified:\n";
    int m1 = askInt("\nM1: "),
        m2 = askInt("\nM2: "),
        m3 = askInt("\nM3: "),
        m4 = askInt("\nM4: ");
    double avg = (m1 + m2 + m3 + m4) / 4.0;

    if (askYN("\nWould you like to include the TEZA grade?(Y/N): ")) {
        int teza = askInt("What is the TEZA grade?: ");
        avg = (3 * avg + teza) / 4.0;
    }

    std::cout << "\nYour average grade at " << subject << " is " << avg << "\n\n"
                 "You got the following mark:" << letterGrade(avg) << "\n"
                 "DO YOU PASS: " << (avg >= 5 ? "Yes." : "No.") << "\n";
}


Two dimensional arrays with nulls I'm new with Kotlin, and this is my first attempt of a two dimensional array.

 // private var roomGrid = arrayOfNulls<arrayOfNulls<Room>>(4)
private var roomGrid = Array(roomCountX) {arrayOfNulls<Room>(roomCountY)}

 init {
    for (gridY in 0 until roomCountY) {
        for (gridX in 0 until roomCountX) {
            val pixelX = gridX * roomWidth
            val pixelY = gridY * roomHeight
            val room = Room(pixelX.toFloat(), pixelY.toFloat(), s)
            roomGrid[gridX][gridY] = room
        }
    }

     // neighbor relations
    for (gridY in 0 until roomCountY) {
        for (gridX in 0 until roomCountX) {
            val room = roomGrid[gridX][gridY]
            if (gridY > 0)
                roomGrid[gridX][gridY - 1]?.let { room?.setNeighbor(Room.SOUTH, it) }
            if (gridY < roomCountY - 1)
                roomGrid[gridX][gridY + 1]?.let { room?.setNeighbor(Room.NORTH, it) }
            if (gridX > 0)
                roomGrid[gridX - 1][gridY]?.let { room?.setNeighbor(Room.WEST, it) }
            if (gridX < roomCountX - 1)
                roomGrid[gridX + 1][gridY]?.let { room?.setNeighbor(Room.EAST, it) }
        }
    }
}

Even though it works I don't like the look of these:

roomGrid[gridX][gridY + 1]?.let { room?.setNeighbor(Room.NORTH, it) }

They are harder to read, and I'm not really sure what .let and it are.
I would like some simpler syntax/solution to a two dimensional array.

How might I improve this?

let

If you use let, you ask Kotlin to create an invisible function with a parameter.

1.let { println(5) }
    //changes to:
    fun func(it : Int) {
        println(5)
    }
    func(1)

Do you see the it? That's the name of the parameter.
Therefor, you can use it inside let.

1.let { println(it) }
//changes to
fun func(it : Int) {
    println(it)
}
func(1)

Now, the function returns something too, namely the result of the last statement.
In this case, it's just Unit, or void in Java (emptyNess):

fun func(it : Int) : Unit {
    return println(it)
}
func(1)

If we take another example, it will be clearer:

val a = 5.let { 3 + it }
//changes to
fun func(it: Int) : Int {
     return 3 + it
}
val a = func(5)

?.let

?. is very simple:

val b = a?.foo()
//changes to:
val b = if (a == null) a else a.foo()

?.let is exactly the same:

val b = a?.let { it+3 }
//changes to
fun func(it: Int){
   it + 3
}
val b = if (a == null) null else func(a)

inline

Kotlin is smart. it actually uses an inline function for let.
An inline function is a function that actually doesn't exist.
Instead, the code is copy pasted into the real code.
The parameters are just variables with random names.

so

val b = a?.let { it + 3 }
//is actually changed to
val b = if (a == null) null else {
    val ac432cd = a
    ac432cd + 3
}

simplyfication

roomGrid[gridX][gridY - 1]?.let { room?.setNeighbor(Room.SOUTH, it) }

step 1

// I would check room first:
if (room != null) {
   roomGrid[gridX][gridY - 1]?.let { room.setNeighbor(room.SOUTH, it) }
}

step 2

// flip the rooms (and directions)
if (room != null) {
   roomGrid[gridX][gridY - 1]?.let{ it.setNeighbor(room.SOUTH, room) }
}

step 3

//remove let
if (room != null) {
   roomGrid[gridX][gridY - 1]?.setNeighbor(room.SOUTH, room)
}

full code until now

 // neighbor relations
for (gridY in 0 until roomCountY) {
    for (gridX in 0 until roomCountX) {
        val room = roomGrid[gridX][gridY]
        if (room != null) {
            if (gridY > 0)
                roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)
            if (gridY < roomCountY - 1)
                roomGrid[gridX][gridY + 1]?.setNeighbor(Room.SOUTH, room)
            if (gridX > 0)
                roomGrid[gridX - 1][gridY]?.setNeighbor(Room.EAST, room)
            if (gridX < roomCountX - 1)
                roomGrid[gridX + 1][gridY]?.setNeighbor(Room.WEST, room)
        }
    }
}

step 4

At the moment, we test in the beginning if room isn't null.
If it is, it skips the if-statement and continues with the next iteration.
We can tell to go to the next iteration immediately using the keyword continue.

// neighbor relations
for (gridY in 0 until roomCountY) {
    for (gridX in 0 until roomCountX) {
        val room = roomGrid[gridX][gridY]
        if (room == null) continue
        if (gridY > 0)
            roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)
        ...
    }
}

step 5

last, kotlin has another language feature: ?:

val a = foo() ?: bar()
//will be rewritten to
val tmp = foo()
val a = if (tmp != null) tmp else bar()

Just as return continue skips immediately to the next variable.
This means that we can rewrite the code we wrote in step 4.

// neighbor relations
for (gridY in 0 until roomCountY) {
    for (gridX in 0 until roomCountX) {
        val room = roomGrid[gridX][gridY] ?: continue
        if (gridY > 0)
            roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)
        ...
    }
}

full code

 // neighbor relations
for (gridY in 0 until roomCountY) {
    for (gridX in 0 until roomCountX) {
        val room = roomGrid[gridX][gridY] ?: continue
        if (gridY > 0)
            roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)
        if (gridY < roomCountY - 1)
            roomGrid[gridX][gridY + 1]?.setNeighbor(Room.SOUTH, room)
        if (gridX > 0)
            roomGrid[gridX - 1][gridY]?.setNeighbor(Room.EAST, room)
        if (gridX < roomCountX - 1)
            roomGrid[gridX + 1][gridY]?.setNeighbor(Room.WEST, room)
    }
}


Streamlined for-loop for comparing two lists I'm new to Python and I'm wondering is there a way to streamline this clunky code I've written. Maybe a built-in function I've never come across before?

I run through two lists of binary numbers and if the same number appears at the same index in list one and two, do x.

So in the example below the number 1 appears at index 2 in both lists.

list1 = [0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
list2 = [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0]

for position, binary in enumerate(list1):
    for placement, number in enumerate(list2):
            if position == placement and binary == 1 and binary == number:
                do x

Your solution's time complexity is O(n2), which is far from optimal. Your lists contain 19 elements - so your solution performs an order of 361 operations.
In order to get a linear solution, you can simulate a "c-style" for loop using range:

for i in range(len(list1)): # assuming the lists are of the same length
    if list1[i]==list2[i]:
                do x

Now the loop runs exactly 19 times - much better!

Another thing: your code checks if binary==1. Is it what you want? If so, Python's equal operator can operate on three arguments, making it more readable:

for i in range(len(list1)): # assuming the lists are of the same length
    if list1[i]==list2[i]==1:
                do x

Lastly, you may want to represent a binary number using the most natural way - as a number. Aside from space consideration, most languages (including Python) have standard binary (often called bitwise) operations.


Reading and printing sudoku input I have seen programs to solve sudoku puzzles but to be honest.. They were badly written.
First of all, readability of the program itself was horrible and the code was really long and confusing.

So I decided to start from scratch, using my own style to write really good solver.
What I have this far is reading a board input from the user and outputting the board representation:

#include <stdio.h>
#include <ctype.h>
#include <iso646.h>
#include <conio.h>
#include <windows.h>

#define FOREGROUND_LBLUE 9
#define COLORSET_MAIN 3

char sudoku [9][9];

int chrton (unsigned char chr)
{
    if(chr >= '0' && chr <= '9')    { return chr - '0'; }
    else                            { return 0;         }
}

int main()
{
    char num = 0;
    char x = 0, y = 0;

    SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_LBLUE | BACKGROUND_BLUE);
    printf("Validate numbers:\t\t\t\t\n\n");
    SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), COLORSET_MAIN);

    // Part 1 : validating hint numbers
    while(y != 9)
    {
        if(kbhit() && isdigit(num = _getch()))
        {
            printf("%c"" ", num);

            sudoku[x][y] = chrton(num);

            if( ++x == 9 )                  { putchar('\n'); x = 0; y++; }
            if( not((x * x) % 3) and x)     { putchar('\t');             }
            if( not((y * y) % 3) and !x)    { putchar('\n');             }
        }
    }
    system("PAUSE");

    return 1;
}

Obviously it is written for Windows compatibility but I use it as for advantage to exploit some rules of commonly-accepted IO.

I have found a couple of things that could help you improve your code.

Avoid the use of global variables

I understand that it's just partial code so far, but it's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable as with sudoku in this code.

Don't use system("pause")

There are two reasons not to use system("cls") or system("pause").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++. In this case, a better alternative would be getchar().

Be careful with char and int

Your chrton function returns an int and then stores it in a char-sized location.  Better would be to return char, since that's how sudoku is defined.

Consider using unsigned char for subscripts

It's not technically wrong, but you may wish to use unsigned char for the type of x and y.  It eliminates a class of errors that can occur if the array subscript is a negative number.  This is a fairly minor point, however.

Consider using more idiomatic C

While your use of and and not is not techncially wrong, because you have correctly included the iso646.h header, you should be aware that many experienced C programmers will be unfamiliar with these operator alternatives, and so if others read your code, it might be an impediment to their understanding of the code.  Similarly, your unusual formatting of if statements as one-liners is likely to seem a bit strange to experienced programmers.

Consider separating input and output

Right now, the main function issues a prompt, reads in the sudoku board and then prints it out as each character is read.  A more modular (and likely more maintainable) approach would separate these into separate functions.

Consider returning 0 instead of 1

A non-zero return value is interpreted as an error condition on most operating systems.  Normal program exit should return 0 or EXIT_SUCCESS or simply omit it, because the compiler will automatically insert the equivalent of return 0; at the end of main.


Function from WordPress VoteItUp function This code comes from a Wordpress plugin's forum called Vote it Up.
It sort posts by vote. A lotof people say that there is more code than is needed.
So I was wondering if someone have any idea about how to clean it a bit.

votingfunctions.php:

function ShowPostByVotes() {
    global $wpdb, $voteiu_databasetable;

    mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
    mysql_select_db(DB_NAME) or die(mysql_error());
    //Set a limit to reduce time taken for script to run
    $upperlimit = get_option('voteiu_limit');
    if ($upperlimit == '') {
        $upperlimit = 100;
    }
    $lowerlimit = 0;

    $votesarray = array();
        $querystr = "
            SELECT *
            FROM $wpdb->posts
            WHERE post_status = 'publish'
            AND post_type = 'post'
            ORDER BY post_date DESC
         ";
        $pageposts = $wpdb->get_results($querystr, OBJECT);
    //Use wordpress posts table
    //For posts to be available for vote editing, they must be published posts.
    mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
    mysql_select_db(DB_NAME) or die(mysql_error());
    //Sorts by date instead of ID for more accurate representation
    $posttablecontents = mysql_query("SELECT ID FROM ".$wpdb->prefix."posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT ".$lowerlimit.", ".$upperlimit."") or die(mysql_error());

    $returnarray = array();
    while ($row = mysql_fetch_array($posttablecontents)) {
        $post_id = $row['ID'];
        $vote_array = GetVotes($post_id, "array");
        array_push($votesarray, array(GetVotes($post_id)));
    }
    array_multisort($votesarray, SORT_DESC, $pageposts);
    $output = $pageposts;
    return $output;

}

index.php:

$pageposts = ShowPostByVotes();

?>
 <?php if ($pageposts): ?>
  <?php foreach ($pageposts as $post): ?>
    <?php setup_postdata($post); ?>

Attention! Code above is something like:

<?php if (have_posts()) : ?>

        <?php while (have_posts()) : the_post(); ?>

so in foreach loop you can use statements like in standard "The Loop" for example the_content, the_time().
To end this add

<?php endforeach; ?>

  <?php else : ?>

Not Found

Sorry, but you are looking for something that isn't here.

    <?php include (TEMPLATEPATH . "/searchform.php"); ?>
 <?php endif; ?>

EDIT:

How I run a custom loop:

        <?php $custom_posts = new WP_Query(); ?>
        <?php $custom_posts->query('category_name=Pictures'); ?>
        <?php while ($custom_posts->have_posts()) : $custom_posts->the_post(); ?>

                <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_content(); ?>

        <?php endwhile; ?>

These are my suggestions

Don't use mysql functions to connect and query Wordpress posts.
You can replace the first SQL statement with this WP_Query.

$query = new WP_Query('post_type=post&post_status=publish&orderby=date&order=DESC');
$pageposts = $query->get_posts();

This way the code is somewhat protected from future Wordpress database changes.
The second select statement is a bit unnecessary as each $post in the $pagepost already contains the post id.
Only thing missing is the limit, but we'll add that to the WP_Query by adding

$query = new WP_Query('post_type=post&post_status=publish&orderby=date&posts_per_page='.$upperlimit);

Refactor and remove unused/unnecessary code

global $wpdb, $voteiu_databasetable - are not needed anymore
$upperlimit - assignment can be done on one line
$lowerlimit - not used anymore as it's enough with the $upperlimit
$output = $pageposts; - assigmentent before return is unnecessary

So the complete ShowPostByVotes in votingfunctions.php would look something like this now:

function ShowPostByVotes() {

    $upperlimit = is_numeric(get_option('voteiu_limit')) ? get_option('voteiu_limit') : 100 ;

    $query = new WP_Query('post_type=post&post_status=publish&orderby=date&posts_per_page='.$upperlimit);
    $pageposts = $query->get_posts();
    $votesarray = array();
    foreach ($pageposts as $post) {
        $vote_array = GetVotes($post->ID, "array");
        array_push($votesarray, array(GetVotes($post->ID)));
    }

    array_multisort($votesarray, SORT_DESC, $pageposts);
    return $pageposts;

}

And you can use it in your index.php by using this code

 <?php $pageposts = ShowPostByVotes();  ?>
 <?php if ($pageposts): ?>
  <?php global $post; ?>
  <?php foreach ($pageposts as $post): ?>
    <?php setup_postdata($post); ?>

    <div class="post" id="post-<?php the_ID(); ?>">

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">
      <?php the_title(); ?>

      <?php the_time('F jS, Y') ?>

         <?php the_content('Read the rest of this entry »'); ?>

Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?>
      <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?>

  <?php endforeach; ?>

  <?php else : ?>

Not Found

Sorry, but you are looking for something that isn't here.

    <?php include (TEMPLATEPATH . "/searchform.php"); ?>
 <?php endif; ?>


std::string like compile-time const char* string I want to write a very simple std::string like compile-time const char* string.

I need to work with strings in the compiletime, just like with strings, I implemented basic functions.

class cstring final {
const char* str_;
std::size_t size_;

public:
constexpr cstring(const char* str, std::size_t size, std::size_t prefix = 0, std::size_t suffix = 0) noexcept
    : str_{str + prefix},
        size_{size - prefix - suffix} {}

template <std::size_t N>
constexpr cstring(const char (&str)[N]) noexcept : cstring{str, N - 1, 0, 0} {}

constexpr cstring() noexcept : cstring{nullptr, 0, 0, 0} {}

cstring(const std::string& str) noexcept : cstring{str.data(), str.size(), 0, 0} {}

constexpr cstring(const cstring&) = default;

cstring& operator=(const cstring&) = default;

constexpr std::size_t size() const noexcept { return size_; }

constexpr std::size_t length() const noexcept { return size_; }

constexpr std::size_t max_size() const noexcept {
    return (std::numeric_limits<std::size_t>::max)();
}

constexpr bool empty() const noexcept { return size_ == 0; }

constexpr const char* begin() const noexcept { return str_; }

constexpr const char* end() const noexcept { return str_ + size_; }

constexpr const char* cbegin() const noexcept { return begin(); }

constexpr const char* cend() const noexcept { return end(); }

constexpr const char& operator[](std::size_t i) const { return str_[i]; }

constexpr const char& at(std::size_t i) const {
    return (i < size_) ? str_[i]
                    : (throw std::out_of_range{"cstring::at"}, str_[0]);
}

constexpr const char& front() const { return str_[0]; }

constexpr const char& back() const { return str_[size_ - 1]; }

constexpr const char* data() const noexcept { return str_; }

constexpr cstring remove_prefix(std::size_t n) const {
    return {str_ + n, size_ - n};
}

constexpr cstring add_prefix(std::size_t n) const {
    return {str_ - n, size_ + n};
}

constexpr cstring remove_suffix(std::size_t n) const {
    return {str_, size_ - n};
}

constexpr cstring add_suffix(std::size_t n) const {
    return {str_, size_ + n};
}

constexpr cstring substr(std::size_t pos, std::size_t n) const {
    return {str_ + pos, n};
}

constexpr int compare(cstring other) const {
    return (size_ == other.size_) ? detail::StrCompare(str_, other.str_, size_)
                                : ((size_ > other.size_) ? 1 : -1);
}

friend constexpr bool operator==(cstring lhs, cstring rhs) {
    return lhs.compare(rhs) == 0;
}

friend constexpr bool operator!=(cstring lhs, cstring rhs) {
    return !(lhs == rhs);
}

std::string append(cstring s) const {
    return std::string{str_, size_}.append(s.str_, s.size_);
}

friend std::string operator+(cstring lhs, cstring rhs) {
    return std::string{lhs.str_, lhs.size_} + std::string{rhs.str_, rhs.size_};
}

friend std::ostream& operator<<(std::ostream& os, cstring str) {
    os.write(str.str_, str.size_);
    return os;
}

operator std::string() const { return std::string{str_, size_}; }
};

Note that I use C++11 in my project so I can't use std::string_view.

I would only ever mark polymorphic classes final. For them, there's a potential benefit to balance out the unnaturalness of not being able to inherit.
You should really indent the contents of the class by one step. Though that could possibly be an artifact of only partially adapting to SE's markup.
Consider verifying that prefix and suffix have sensible values, at least in debug-mode (assert()).
The first ctor has sensible defaults for its last two parameters. Why not take advantage of that?
Is there a reason you only accept std::string, instead of generally std::basic_string<char, std::char_traits<char>, AnyAllocator>?
You could use !_size instead of _size == 0. Well, de gustibus.
Your comparison is curious, but at least consistent.
I would suggest conforming to C++17 std::string_view as closely as possible so you can later remove your custom class, and to ease the burden for users.


Using jquery to prepare jQuery UI tabs, optimize? I am looking for someone to review my solution to a jQuery DOM manipulation exercise on appendto.com: http://learn.appendto.com/lesson/dom-manipulation-101#exercise

I'm wondering if there is a way I can optimize or if there are other aspects I need to consider when building a solution like this.

The problem is outlined in the fiddle: http://jsfiddle.net/KhwZS/1283/

Here is my solution:

var getFirstTwoWords = function(str) {
    return str.split(/\s+/).slice(1,3).join(" ");
}

var tabLinks = $("

");
$("div.tab").each( function( idx ) {
    var id = "tabs-" + (idx + 1);

    var text = $(this)
        .removeClass("tab")
        .attr("id", id)
        .text();

    var tabLabel = getFirstTwoWords(text);

    // Create corresponding tab link
    tabLinks.append("
" + tabLabel + "
");
});

$(".tabs div:first").before(tabLinks);
$( ".tabs" ).tabs();

Optimized version:

var tabLinks = $("

");
$("div.tab").each( function( idx ) {
    var id = "tabs-" + (idx + 1);

    var tabLabel = $(this)
        .removeClass("tab")
        .attr("id", id)
        .find("h3")
        .remove()
        .text();

    // Create corresponding tab link
    tabLinks.append("
" + tabLabel + "
");
});

$(".tabs")
   .prepend(tabLinks)
   .tabs();

Your code's very nice. My points below are mostly of the "but what if..." variety concerning the DOM manipulation, rather than the JavaScript itself. In other words, your solution seems spot on for the given exercise, whereas my comments mostly refer to situations which are not part of the exercise, but could arise in the real world.

Aside: The exercise could be clearer in its naming. The container element (singular) has a class called tabs (plural), while the DIVs (plural) within it have a class called tab (singular). It's sort of logical, but it gets confusing nonetheless. And I say "sort of logical", because the .tab elements aren't actually tabs - they're "panels" in jQuery UI's terminology. Hence, their class name should really be "panel". But I digress...

First off, what would happen if the page contains several "tabable" sections? The fact that .tabs is a class name - not an ID - suggests that there might be multiple div.tabs container elements, each with their own set of div.tab elements.

Well, with your code, things go a little awry (see here): Both tab containers get tab links for all the panels on the page, even those belonging to another container.

The trick would be to go through each div.tabs (i.e. tab container) element in turn, and manipulate their individual structures one by one:

$("div.tabs").each(function (containerIndex) {
  var container = $(this),
      tabLinks  = $("

");

  container.find("div.tab").each(function (tabIndex) {
    var id = "tabs-" + containerIndex + "-panel-" + tabIndex; // more precise ID

    // your code here ...
  });

  container
    .prepend(tabLinks)
    .tabs();
});

See the result here

Second, what might happen if an
 heading has HTML in its text or has its own child elements? Here are examples of each of those cases:

Literal HTML:
When to use &lt;div&gt; elements

HTML formatting:
When to use div elements

Here's the result, using your code

Now, this is something where there may not be "one right answer" - it all depends on the content you're working with. However, it's worth considering.

In your case, you use .text() to get the text out of the heading, but you don't use .text() to put that text into the the link; you "manually" create a link by concatenating strings.
So, in the first case, the string you get out is When to use
 elements. Notice that the entity-encoded < and > have become plain characters. When you then concatenate that with other strings of HTML to make the link, you end up more HTML than you intended; there's an unclosed DIV in the middle of your link!
In the second case, .text() completely ignores the  tag. That doesn't break the link, but you lose the formatting and semantics of the  tag, which - one might assume - was put there for a reason by whoever wrote the heading. Since you also remove the original
, that formatting is now nowhere to be found.

I said there was no right answer, because to fix the first case, you'd need to use .text() to extract and insert the heading's content, as it prevents the string from being interpreted as HTML. But to fix the other case, you'd need to use .html() instead, to ensure the string is interpreted that way. Now, using .html() would actually solve both cases (preserving already-encoded entities and tags), but the next question is whether you actually want that. What if the heading itself contains a link? Then you'll end up with a link inside a link... This of course doesn't apply only to tabs and headings, but to any situation where you're extracting and inserting content, which is why I brought it up.

But again, I'm just trying to poke holes in things here, so don't let it discourage you. It's more to illustrate the sort of things you might run in to. The possible solutions I can think are outside the scope of this answer though (it'd involve some different approaches), and very much outside the scope of the original exercise.

Speaking of "out of scope", I've rambled plenty here, so I'll stop.


jQuery password confirmation I have built a "reset and confirm password" section on a site. It works great. I just have this suspicion that maybe it isn't the most efficient way. I am relatively new to
jQuery but I can usually make things work well. I am just wanting to make sure I am doing them right.

Any suggestions are appreciated.

/////////////// RESET PASSWORD  /////////////////////
$('#reset_password').click(function reset_password(){
    //Enter a password input field a button
    $('#new_pass_field').html('<input type="text" id="new_password" name="new_password"><button id="submit_new_pass">Submit New Password</button>');
    // Bind a click to the button
    $('#submit_new_pass').bind('click', function submit_new_pass (){
        // When clicked get val of the new_password field.
        $get_val = $("#new_password").val();
        // Hide the new_pass field and button so the confirm field and button can be entered.
        $('#new_pass_field').hide("fast").html('<input type="text" id="password" name="password"><button id="confirm_new_pass">Confirm New Password</button>');
        // Bind click to that confirm button
        $('#confirm_new_pass').bind('click', function confirm_new(){
            // Get val of the confirm pass field
            $get_confirm_val = $("#password").val();
            // Check valdation if 2 passwords match
            if($get_val == $get_confirm_val){
                // If they match send to DB and encrypt.
                $.get(uri_base +'/AJAX/update_password/admin_users/'+$get_confirm_val+'/'+Math.random(), function(msg){
                    //If returns true then send msg password changed. and hide the password row.
                    if(msg){
                        $("#err_password").html("Your Password has been changed.").queue(function(){
                            setTimeout(function(){
                                $("#err_password").dequeue();
                            }, 3000);
                        })
                        $('#reset_pass_results').slideUp("slow");
                        $('#new_pass_field').hide("fast").html('');
                    }else{
                        // Error in the DB
                        $("#err_password").html("There was an error. Your password was not changed.");
                    }
                });
            }else{
                // Passwords didn't match now reset the clicks to try again and hide the error
                $("#err_password").html("Your Passwords didn't match!").delay(3000).fadeOut("slow");
                $('#confirm_new_pass').bind('click', confirm_new);
                $('#reset_password').bind('click', reset_password);
            }
            return false;
        });
        // Show the password field
        $('#new_pass_field').show("fast");
        return false;
    });
    // Show initial field and button.
    $('#reset_pass_results').slideDown("slow", function(){
        $('#new_pass_field').show("fast");
    });
    return false;
});

Looks fine to me but one way to write a lot less code for these relatively simple ajax calls is to use the Jquery Form plugin that converts a form tag to an ajax call. I believe you'll find it a huge time save going forward.


How best to differentiate boolean values in a long list? I have a large C# Dictionary of string keys and boolean values. Background on the reason for it is this: my program builds up a bunch of the same objects from two different sources, and then compares all the properties to see if there are any disparates. But I want to ignore the differences where I know one source hasn't exposed that property for comparison, so I have this array that lists the properties that are actually 'gathered'.

Then when filtering the differences before user display, I ask if(!gathered[prop]) and remove it in that case. It would throw an exception if I hadn't defined a case for the property, and I don't want to ignore that as it may just mean I neglected to specify if it was or wasn't gathered.

    public Dictionary<string, bool> TPORGatheredData = new Dictionary<string,bool>()
    {
        // Represents fields that are actually retrieved from TP data
        { "Reference", true },
        { "Title", true },
        { "Status", true },
        { "Status.State", true },
        { "OriginatorName", true },
        { "InvestigatorName", true },
        { "ManagerName", true },
        { "ObservedOn", true },
        { "RaisedOn", true },
        { "ClosedOn", true },
        { "Project", true },
        { "VariantObservedOn", true },
        { "SoftwareVersionObserved", true },
        { "AreaObservedOn", true },
        { "StageObservedOn", true },
        { "VariantAppliedTo", true },
        { "AreaAppliedTo", true },
        { "FaultClassification", true },
        { "Type", true },
        { "SecurityClassification", true },
        { "CommercialClassification", true },
        { "SecurityGroup", true },
        { "SafetyRelated", true },
        { "Description", false },
        { "Recommendations", true },
        { "Recommendations.PointNumber", true },
        { "Recommendations.Id", true },
        { "Recommendations.Type", true },
        { "Recommendations.RecommendationText", true },
        { "ClosureText", true },
    };

The problem with this is that the value of false is quite significant. How could I differentiate the false from the true here?

Two options I can think of:

I could tab align all the values but this looks ugly as the farthest extent they need to go for alignment is a bit too far to easily see which value is for which key.
assume if there's no key then the value is true (although that depends on the context making this a suitable option, and as it stands in my case not having the value may be an indicator of a field that needs checking to see if it is or isn't handled).

Is this more like what you're after?

var TPORGatheredData = new[]
        {
            // Add all values in the logical order that you want them
            "Reference",
            "Title",
            "Status",
            "Status.State",
            //...omitted for brevity
            "Description",
            "ClosureText"

        }.ToDictionary(x=>x,x=>true);

        // This is significant
        TPORGatheredData["Description"] = false;


String contains non-overlapping letter pairs I was trying my hand at learning Elixir via ancient adventofcode puzzles and was trying to write a function to satisfy this requirement:

  It contains a pair of any two letters that appears at least twice in
  the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but
  not like aaa (aa, but it overlaps).

Here is what I came up with, but it feels like it might be unwieldy. Is there a way to make it more elegant?

  def has_non_overlapping_pair(string) do
    0..String.length(string)-2
      |> Enum.map(fn n ->
          String.slice(string, n, 2)
      end)
      |> Enum.reduce(["_"], fn pair, acc ->
          if pair == hd(acc) do ["_"|acc]
          else [pair|acc] end
      end)
      |> count_occurrences
      |> Map.delete("_")
      |> Map.values
      |> Enum.any?(fn val -> val > 1 end)
  end

You could use a map to store the pairs with their first occurrence while iterating over the pairs. Break if the current pair was already found at a position less than the current position minus 1.

def has_non_overlapping_pair(string) do
  0..String.length(string) - 2
  |> Enum.reduce_while(%{}, fn n, m ->
    pair = String.slice(string, n, 2)
    pos  = Map.get(m, pair, n)
    cond do
      pos == n     -> {:cont, Map.put(m, pair, n)}
      pos == n - 1 -> {:cont, m}
      true         -> {:halt, true}
    end
  end) == true
end


Find all occurrences of the word "the" without using regex I have an assignment to find all occurrences of the word "the" without using regex:

  Use the indexOf method to do this. The word "the" could also appear in a larger word, such as "Theresa" or "other".

Please confirm if this is the best way to do that.

import java.util.Scanner;

public class TheFinder
{
    public static void main(String[] args)
    {
        int theCounter;
        int indexOfThe = 0;

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a sentence with a word \"the\" or type \"quit\" to quit: ");
        String sentence = input.nextLine();

        while(!(sentence.equalsIgnoreCase("quit")))
        {
            theCounter = 0;
            sentence = sentence.toLowerCase();

            while(sentence.contains("the"))
            {
                ++theCounter;
                sentence = sentence.substring((sentence.indexOf("the") + 3), sentence.length());
            }
            if(theCounter > 0)
            {
                System.out.println("The number of times \"the\" appears in the sentence is " + theCounter + ".");
            }
            else
            {
                System.out.println("There is no word \"the\" in the sentence");
            }

            System.out.print("Please enter a sentence with a word \"the\" or type \"quit\" to quit: ");
            sentence = input.nextLine();
        }
    }
}

Just some ideas:

The code should work as it is and is OK if performance doesn't matter, or the searched strings are small and occurrences few.

You don't need to call both contains(...) and indexOf(...); this iterates through the string twice.
The substring method copies the whole remaining string into a new string.

Easiest way is to call indexOf(String s, int fromIndex), with the start index parameter.

You can also build a state machine, representing how many letters of "the" have been found sequentially. Then analyze the string char by char.

Also keep in mind that your search will not work for repeating character sequences: if you search for "thethe" instead, and your searched text contains "thethethe", it will be found only once, although it occurs twice. Because your next index skips the entire search phrase when found (here by hardcoded "3"). It depends on what the demands are in your case, and what to do with such search phrases.