Remove all vowel from file C++ i am just start to learn C++ and would like to know if there is a better and efficient way to solve this problem or some recommendations.

  Problem: Remove all vowels from file and create new one without
  vowels.

Here is my solution.

#include <iostream>
#include <fstream>

bool is_vowel(char &ch) {
    ch = tolower(ch);//clion showing warning here(value of type 'int' may not fit into type 'char') ,dont know why , i havent int here.
    return (ch == 'a' || ch == 'o' || ch == 'u' || ch == 'i' || ch == 'e');
}

int main() {
    ifstream file{"data.txt"};
    ofstream outfile{"new.txt"};
    string word;
    getline(file, word);
    for (char &ch : word) {
        if (!is_vowel(ch))
            outfile << ch;
    }
}

For the moment, let's ignore is_vowel itself, and just look at the higher level: what we're doing is copying data from some source to some destination, while removing any items that meet some specified criteria.

As it happens, the standard library already has an algorithm to do exactly that: std::remove_copy_if (I know: crappy name; not clear what it really does--but that really is what it does).

So, I will posit that at the top level, this is how we should be carrying out the overall task:

remove_copy_if(some_input, some_output, your_criteria);

In the case of files, we can use istream_iterators for the input and an ostream_iterator for the output, making this something like:

std::ifstream file{"data.txt"};
std::ofstream outfile{"new.txt"};

file >> std::noskipws;

std::istream_iterator<char> in{file}, end;
std::ostream_iterator<char> out{outfile};

std::remove_copy_if(in, end, out, is_vowel);

Looking at is_vowel itself: it can be defined a number of different ways, depending on the degree to which you care about speed vs. space usage. If you care primarily about space, storing the vowels in a string and searching that string (e.g., as suggested by @utnapistim) is a perfectly fine method. Under the circumstances (copying from one file to another) the I/O will almost certainly be (quite a lot) slower than the processing, so this is probably the most sensible approach.

For another possibility, however, let's assume our source and destination were just strings in memory instead, so we wanted to optimize for speed instead. In this case, we might consider a somewhat different approach. One possibility would be an array (or vector) of Booleans, one for each possible char value, specifying whether that character is a vowel. We probably want to wrap this up in a neat little class so we don't need to deal with the details.

class is_vowel {
    bool table[std::numeric_limits<unsigned char>::max()];
    static const char vowels = "aeiouAEIOU";
public:
    // Here we set up our table. We start by initializing everything to `false`
    // then we set the entries that really do represent vowels to true.
    is_vowel() : table(false) {
        for (auto ch : vowels)
            table[ch] = true;
    }

    bool operator()(unsigned char ch) { return table[ch]; }
};

Unfortunately, it's not always easy to decide which sort of approach will be the best for a given circumstance, but such is life sometimes.

There are also a few intermediate points that probably don't make sense for this specific case, but can for similar cases. For example, here we're dealing with such a small number of items (around 10) that searching the string isn't particularly slow. If we had a list of, say, a few hundred items we wanted to remove, searching the whole list every time could get pretty slow--for such cases, we might consider sorting the list of items to remove, and using a binary search.

I'm starting to get into pretty hypothetical areas though, so perhaps I should just stop for now... :-)


Normalize Sparse Matrix along rows in C++ Eigen I wrote a function to normalize sparse matrix along rows using C++ Eigen; however, I feel that it can be improved, and that I am not using some built in functions of Eigen.

#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <vector>
#include <math.h>

using namespace Eigen;

std::vector<double> get_weights(SparseMatrix<double, RowMajor> sm);
SparseMatrix<double, RowMajor> row_normalize(SparseMatrix<double, RowMajor> sm);

int main()
{
  MatrixXd silly(6, 3);

  silly << 0, 1, 36,
           0, 3, 0,
           0, 0, 0,
           3, 2, 1,
           0, 1, 0,
           2, 0, 9;

  SparseMatrix<double, RowMajor> sparse_silly = silly.sparseView();

  SparseMatrix<double, RowMajor> normalized = row_normalize(sparse_silly);
  std::cout << "normalized" << std::endl;
  std::cout << normalized << std::endl;

  SparseMatrix<double, RowMajor> test = normalized * normalized.transpose();
  // Checking that all diagonal elements of non-zero rows are 1
  std::cout << "test" << std::endl;
  std::cout << test << std::endl;

  return 0;
}

SparseMatrix<double, RowMajor> row_normalize(SparseMatrix<double, RowMajor> sm)
 {
   std::vector<double> weights = get_weights(sm);
   SparseMatrix<double, RowMajor> sm_weights(sm.rows(), sm.rows());
   for(int i = 0; i < weights.size(); ++i)
     {
       sm_weights.insert(i,i) = weights[i];
     }

   return sm_weights * sm;
 }

std::vector<double> get_weights(SparseMatrix<double, RowMajor> sm)
{
  std::vector<double> weights;
  for (int i = 0; i < sm.rows(); ++i)
    {
      double my_sum = 0;
      double *val_ptr = sm.row(i).valuePtr();

      if(sm.row(i).nonZeros())
        // avoid division by zero problem
        {
          for (int j = 0; j < sm.row(i).nonZeros(); ++j)
            {
              my_sum += (*val_ptr * (*val_ptr));
              val_ptr++;
            }
          weights.push_back(1.0 / sqrt(my_sum));
        }
      else
        {
          weights.push_back(0);
        }
    }
  return weights;
}

I'd put the Eigen headers below the STL headers.  Also, <math.h> should be <cmath>, the latter being the C++ library incorporated into the std namespace.
You can define main() below the other functions, allowing you to save a bit of room by eliminating the function prototypes.
You don't need that flushing with std::endl.  To get just a newline, output a "\n".
main() doesn't need an explicit return 0.  As reaching this point implies success, the compiler will do this return for you.
You shouldn't use an int here:

for(int i = 0; i < weights.size(); ++i)
  {
    sm_weights.insert(i,i) = weights[i];
  }

If you had your compiler warnings up high (and they should be), you should've been told about a type-mismatch here.  The type for i should instead be std::size_type (an unsigned type), which is the return type of size() for each STL container class.
For this for loop:

for (int j = 0; j < sm.row(i).nonZeros(); ++j)
  {
    my_sum += (*val_ptr * (*val_ptr));
    val_ptr++;
  }

val_ptr++ can still be put into the loop statement:

for (int j = 0; j < sm.row(i).nonZeros(); ++j, val_ptr++)
{
    my_sum += (*val_ptr * (*val_ptr));
}

I'm also unsure about all the raw pointer use here.  Raw pointers in C++ should be kept to a minimum, so there may be a way to do this without using any of them.
You pass sm by value in both of your functions, however, it doesn't look like you're trying to allow the compiler to perform move semantics.  But you're also using the argument in such a way that it's only being read for writing to other values.  In such a case, you should pass sm by const&.


Care to review my immutable singly linked list? public sealed class SinglyLinkedList<T> : IEnumerable<T>
{
    readonly static SinglyLinkedList<T> _empty = new SinglyLinkedList<T>();
    readonly bool _isEmpty;
    readonly T _head;
    readonly SinglyLinkedList<T> _tail;

    private SinglyLinkedList()
    {
        _isEmpty = true;
    }

    private SinglyLinkedList(T head)
    {
        _isEmpty = false;
        _head = head;
    }

    private SinglyLinkedList(T head, SinglyLinkedList<T> tail)
    {
        _isEmpty = false;
        _head = head;
        _tail = tail;
    }

    public static SinglyLinkedList<T> Empty
    {
        get { return _empty; }
    }

    public int Count
    {
        get
        {
            var list = this;
            var count = 0;
            while (!list._isEmpty)
            {
                count++;
                list = list._tail;
            }
            return count;
        }
    }

    public bool IsEmpty
    {
        get { return _isEmpty; }
    }

    public T Head
    {
        get
        {
            if (_isEmpty)
                throw new InvalidOperationException("The list is empty.");
            return _head;
        }
    }

    public SinglyLinkedList<T> Tail
    {
        get
        {
            if (_tail == null)
                throw new InvalidOperationException("This list has no tail.");
            return _tail;
        }
    }

    public static SinglyLinkedList<T> FromEnumerable(IEnumerable<T> e)
    {
        if (e == null)
            throw new ArgumentNullException("e");
        return FromArrayInternal(e.ToArray());
    }

    public static SinglyLinkedList<T> FromArray(params T[] a)
    {
        if (a == null)
            throw new ArgumentNullException("a");
        return FromArrayInternal(a);
    }

    public SinglyLinkedList<T> Append(T value)
    {
        var array = new T[Count + 1];
        var list = this;
        var index = 0;
        while (!list._isEmpty)
        {
            array[index++] = list._head;
            list = list._tail;
        }
        array[index] = value;
        return FromArrayInternal(array);
    }

    public SinglyLinkedList<T> Prepend(T value)
    {
        return new SinglyLinkedList<T>(value, this);
    }

    public SinglyLinkedList<T> Insert(int index, T value)
    {
        if (index < 0)
            throw new ArgumentOutOfRangeException("index", "Cannot be less than zero.");
        var count = Count;
        if (index >= count)
            throw new ArgumentOutOfRangeException("index", "Cannot be greater than count.");
        var array = new T[Count + 1];
        var list = this;
        var arrayIndex = 0;
        while (!list._isEmpty)
        {
            if (arrayIndex == index)
            {
                array[arrayIndex++] = value;
            }
            array[arrayIndex++] = list._head;
            list = list._tail;
        }
        return FromArrayInternal(array);
    }

    public IEnumerator<T> GetEnumerator()
    {
        var list = this;
        while (!list._isEmpty)
        {
            yield return list._head;
            list = list._tail;
        }
    }

    public override string ToString()
    {
        if (_isEmpty)
            return "[]";
        return string.Format("[{0}...]", _head);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    static SinglyLinkedList<T> FromArrayInternal(T[] a)
    {
        var result = Empty;
        for (var i = a.Length - 1; i >= 0; i--)
        {
            result = result.Prepend(a[i]);
        }
        return result;
    }
}

The constructor with one argument is never used and doesn't make much sense (list with a head but no tail?).
You shouldn't use Count in your own methods unless absolutely necessary, because it's O(n). Or you should cache the result in a field.
Because you use Count so often, your Insert() walks through the whole list three times! The second time it's because of completely unnecessary Count. You should completely rewrite it, Insert() can be done in O(index), which can be much better than your O(n).


Is this a correct use of the std::cout and std::cin basefields/conversions? Considering the code that you can find at the bottom of this post, it's safe to say that this is a good example of how I can use different representations in different basefields correctly in C++ ?

I'm referring to the use of:

std::hex in the std::istringstream case
the use of std::cout.setf() and std::cout.unsetf() in the "output section"

In short is this correct for both input and output ?

This could possibly lead to some bug of some kind on some platforms ?

I also have a doubt about the use of an unsigned int to input a char, the basefield always cares about that ? I mean if I input f I would like to store 15 in decimals and not 102 from the ascii table.
(because a char is often implemented as an unsigned int)

Thanks.

// trying to determine what is the header available for unsigned ints
#if __cplusplus < 201103L
#include <stdint.h>
#else
#include <cstdint>
#endif

#include <cstdlib>
#include <string>
#include <map>
#include <bitset>
#include <iostream>
#include <iomanip>
#include <sstream>

const static uint32_t fieldWidth = 2;

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

  std::map<std::string, uint32_t> bucket;
  bucket["EAX"] = 0x0; // initializing bucket with default values
  bucket["EBX"] = 0x0;
  bucket["ECX"] = 0x0;
  bucket["EDX"] = 0x0;

  if (argc >= 2) {
    switch (argc) {
    case 2:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      break;
    case 3:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      break;
    case 4:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
      break;
    case 5:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
      std::istringstream(argv[4]) >> std::hex >> bucket["EDX"];
      break;
    default:
      std::cout << "Too many arguments, exiting now\n";
      exit(EXIT_FAILURE);
    }

  } else {
    std::cout << "Not enough arguments, exiting now\n";
    exit(EXIT_FAILURE);
  }

  std::cout.setf(std::ios::hex, std::ios::basefield);
  std::cout.setf(std::ios::showbase);

  std::cout << "\nExecuting with this HEX values :\n\n";
  std::cout << "EAX = " << std::hex << bucket["EAX"] << "\n"
            << "EBX = " << std::hex << bucket["EBX"] << "\n"
            << "ECX = " << std::hex << bucket["ECX"] << "\n"
            << "EDX = " << std::hex << bucket["EDX"] << "\n";

  std::cout.unsetf(std::ios::showbase);
  std::cout.unsetf(std::ios::hex);

  asm volatile("cpuid"
               : "=a"(bucket["EAX"]), "=b"(bucket["EBX"]), "=c"(bucket["ECX"]),
                 "=d"(bucket["EDX"])
               : "a"(bucket["EAX"]), "b"(bucket["EBX"]), "c"(bucket["ECX"]),
                 "d"(bucket["EDX"]));

  std::cout << "\nThe results:\n";
  for (std::map<std::string, uint32_t>::const_iterator k = bucket.begin();
       k != bucket.end(); ++k) {

    std::cout << "\n";
    std::cout << k->first << "\n";

    for (int c = 31; c >= 0; c--) {
      std::cout << std::setfill(' ') << std::setw(fieldWidth) << c;
    }

    std::cout << "\n";

    std::string s(std::bitset<32>(k->second).to_string());

    for (std::string::const_iterator j = s.begin(); j != s.end(); ++j) {
      std::cout << std::setfill(' ') << std::setw(fieldWidth) << *j;
    }

    std::cout << "\n";
  }
  std::cout << "\n";
  return (0);
}

original repository

it's safe to say that this is a good example of how I can use different representations in different basefields correctly in C++ ?

I presume you stream manipulators.

  I'm referring to the use of:

std::hex in the std::istringstream case
the use of std::cout.setf() and std::cout.unsetf() in the "output section"

These are examples of stream manipulators:

I would not do this:

#if __cplusplus < 201103L
#include <stdint.h>
#else
#include <cstdint>
#endif

In one version you are putting the functions in the global namespace (stdint.h) the other you are putting the functions in the std namespace. This will cause problems and may give you different results on different compilers.

This seems like you are doing it the hard way:

 if (argc >= 2) {
    switch (argc) {
    case 2:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      break;
    case 3:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      break;
    case 4:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
      break;
    case 5:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
      std::istringstream(argv[4]) >> std::hex >> bucket["EDX"];
      break;
    default:
      std::cout << "Too many arguments, exiting now\n";
      exit(EXIT_FAILURE);
    }

Why not a loop?

 if (argc < 2 || argc > 4) {/*ERROR MSG AND EXIT*/}

 std::vector<std::string>  mapIndex = { "EAX", "EBX", "ECX", "EDX" };
 for(int loop = 1; loop < argc; ++loop)
 {
     // PS: just using mapIndex to keep it as close to your original
     //     code as possbile. If I had done this from scratch I would
     //     have just put the values into a four element array.

     std::istringstream(argv[loop]) >> std::hex >> bucket[mapIndex[loop-1]];
 }

The use of std::hex in this situation is correct.
It marks the input stream and the next value (if an hex integer) is correctly read.


C in CRUD for Silverlight The C in CRUD Silverlight:

Create new Silverlight business application "CRUD"
Add ADO.NET Entity Data Model to CRUD.web
Select the db, the tables, build the project
Add Domain Service Class to CRUD.web
Select the tables and also select the allow editing option for the table "tname"
Build the project
Keep two textboxes "ID" and "NAME" on MainPage.xaml
Keep a button "SAVE NEW RECORD" on MainPage.xaml
Build
Add the following code

Partial Public Class MainPage
    Inherits UserControl

    Dim dserv As New DomainService1

//default methods generated
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        'declare a table object
        Dim table As New tname
        'assign values to fields
        table.ID = TextBox1.Text
        table.NAME = TextBox2.Text
        'add table object entity
        dserv.tnames.Add(table)
        'submit the changes, to make it permenant in the db
        dserv.SubmitChanges()
    End Sub

Record inserted

Is this the easiest way for having no side effects to add a new record? Is this the optimal way to add a new record?

I don't think it's best-practice to put any logic that isn't strictly presentation-specific directly into a code-behind event handler like this, let alone that a UserControl knows anything about any DomainService1 object.

If you're shooting for best-practices, you need to look into the Model-View-ViewModel pattern; it's not the job of any UI component to perform any kind of business or data logic.


Program follows sequence of instructions to arrive at destination I'm warming up with Clojure to try my hand at the advent of code challenge that starts in December. This is my attempt at the first challenge from last year.

This is my first attempt at a non trivial program in clojure, so comments on any part of the program would be appreciated.

(defrecord Vector [x y])

(defrecord State [orientation position])

(def orientations {
    :north (Vector. 0 -1),
    :east (Vector. 1 0),
    :south (Vector. 0 1),
    :west (Vector. -1 0) })

;; Given a compass orientation
;; Return the new orientation after a left turn
(defn turnLeft [current_orientation]
    (case current_orientation
        :north :west
        :east :north
        :south :east
        :west :south))

;; Given a compass orientation
;; Return the new orientation after a right turn
(defn turnRight [current_orientation]
    (case current_orientation
        :north :east
        :east :south
        :south :west
        :west :north))

;; Given a position, orientation and distance
;; Return a new position after moving in that direction for that distance
(defn moveForward [current_position orientation distance]
    (let [direction_vector (orientation orientations)]
        (Vector.
            (+ (:x current_position) (* distance (:x direction_vector)))
            (+ (:y current_position) (* distance (:y direction_vector))))))

;; Given a state and an instruction
;; Return a new state
(defn act [state, instr]
    (case instr
        \L (State. (turnLeft (:orientation state)) (:position state))
        \R (State. (turnRight (:orientation state)) (:position state))
        (State.
            (:orientation state)
            (moveForward (:position state) (:orientation state) instr))))

;; Given a starting state and list of instructions
;; Return the final state
(defn doActions [state instrs]
    (if (empty? instrs)
        state
        (doActions (act state (first instrs)) (rest instrs))))

;; Instructions are a sequence of combined instructions as follows:
;; L13, R10, R1, L3, ...
;; Convert this into an alternating list
;; of TurnLeft / TurnRight and Move instructions
(def instrs
    (->> "input.txt"
        slurp
        (re-seq #"[LR]|\d+")
        (map
            (fn [instr]
                (case instr
                    "L" \L
                    "R" \R
                    (read-string instr))))))

(require '(java.lang.Math))
(let [finalstate (doActions (State. :north (Vector. 0 0)) instrs)]
    (+
        (Math/abs (get-in finalstate [:position :y]))
        (Math/abs (get-in finalstate [:position :x]))))

Take a look at Bruce Hauman's answer to the question: https://github.com/bhauman/advent-of-clojure-2016/blob/master/src/advent_of_clojure_2016/day1.clj

One thing that was an eye-opener to me is how we all (my answer had :east and :west etc) fall into the trap of having of describing reality rather than just solving the problem with as simple as possible data structures. You can see how little code he had to write - no need for State, no need for functions describing which way was turned. Albeit his advantage was knowing about reductions, which give a path back for every step taken.


Attributes with special behaviour in Python What is the common practice to implement attributes that have side effects in Python? I wrote the following class which supposed to save singletons when a variable is going to get a certain value. The background is that my program had sparse data, meaning that there were a lot of objects having empty sets in their attributes which wasted a lot of memory. (my actual class is slightly more complex). Here is the solution I took:

class DefaultAttr:
    void="Void"

    def __init__(self, var_name, destroy, create):
        self.var_name=var_name
        self.destroy=destroy
        self.create=create

    def __get__(self, obj, owner=None):
        result=getattr(obj, self.var_name)
        if result is DefaultAttr.void:
            result=self.create()
        return result

    def __set__(self, obj, value):
        if value==self.destroy:
            value=DefaultAttr.void
        setattr(obj, self.var_name, value)

class Test:
    a=DefaultAttr("_a", set(), set)

    def __init__(self, a):
        self._a=None
        self.a=a

t=Test(set())
print(t._a, t.a)

Do you see a way to make it neater? I was wondering if I can avoid the hidden attribute _a. Also the "Void" solution seems dodgy. What would you do?

If you are using python 2, your code doesn't work at all. I'll assume you are using python 3.

There a few cases where this will do unexpected things:

t=Test(set())
t.a.add(2)
print t.a

The set will empty.

b = set()
t = Test(b)
b.add(2)
print t.a

The set will again be empty.

These issues are caused because set are mutable. They go away if you only use immutable objects, such as frozenset(), or if you just never use the mutable operations on the sets.

  I was wondering if I can avoid the hidden attribute _a

Instead of providing the name as a parameter, have DefaultAttr make one up such as '_' + str(id(self)). That'll provide a unique attribute to store data on.

  Also the "Void" solution seems dodgy

Instead of "Void" use object(). It'll avoid a string comparison and be guaranteed unique.

Alternately, delete the attribute using delattr instead of storing anything there. Absence of the attribute indicates that you should use the default value.

Alternately, if you restrict the use of the object to immutable objects, just store a reference to the immutable object there. There is no need to use a special sentinel value. Here is my code to implement that idea:

class DefaultAttr(object):
    def __init__(self, empty):
        self._empty = empty
        self._name = '_' + str(id(self))

    def __get__(self, obj, owner=None):
        return getattr(obj, self._name)

    def __set__(self, obj, value):
        if value == self._empty:
            value = self._empty
        setattr(obj, self._name, value)

  The background is that my program had sparse data, meaning that there
  were a lot of objects having empty sets in their attributes which
  wasted a lot of memory.

Actually, your probably shouldn't be doing this at all. Instead, use frozenset(). Whenever you call frozenset() it returns the same set, so the empty sets won't take up excess memory. If you rework your app to use them, you should use much less memory.


Format simple array in multidimensional I have a simple array in PHP like this :
Array
(
    [max_size_video] => 50000
    [max_size_photo] => 8000
    [token_expire] => 100
    [dns] => mydns.fr
    ...
)

I would like to convert this array to multidimensional format with underscore as a separator:
Array
(
    [max] => Array
        (
            [size] => Array
                (
                    [video] => 50000
                    [photo] => 8000
                )
        )
    [token] => Array
        (
            [expire] => 100
        )
    [dns] => mydns.fr
    ...
)

I can do this with the following ugly code :
$item = explode('_', $row);
switch (count($item)) {
  case 1:
    $array[$item[0]] = $value;
  break;
  case 2:
    $array[$item[0]][$item[1]] = $value;
  break;
  case 3:
    $array[$item[0]][$item[1]][$item[2]] = $value;
  break;
  case 3:
    $array[$item[0]][$item[1]][$item[2]][$item[3]] = $value;
  break;
  ...
}

How can I do this with a more elegant function?

A reference variable will save you from that wicked code bloat!
You can make iterative calls of this Stack Overflow answer from 2012.
Code: (Demo)
function assignArrayByPath(&$arr, $path, $value, $separator = '_') {
    $keys = explode($separator, $path);
    foreach ($keys as $key) {
        $arr = &$arr[$key];
    }
    $arr = $value;
}

foreach ($array as $key => $value) {
    unset($array[$key]);
    assignArrayByPath($array, $key, $value);
}
var_export($array);

Or boil it down to this: (Demo)
function assignArrayByPath(&$result, $path, $value) {
    foreach (explode('_', $path) as $key) {
        $result = &$result[$key];
    }
    $result = $value;
}

$result = [];
foreach ($array as $key => $value) {
    assignArrayByPath($result, $key, $value);
}
var_export($result);

This technique will require that you build logical (non-monkey-wrenching) paths as keys.  I mean:

If after 'max_size_photo' => 8000, you declare 'max' => 10000, then you will get an error.
If after 'max_size_photo' => 8000, you declare 'max_size' => 10000, then you will erase the previously expanded (deeper) elements from the output array.

p.s. You can also write it without any custom functions by nesting the loops so long as you maintain the technique of using a reference variable inside of a reference variable.  Trippy, right?
Code: (Demo)
$result = [];
foreach ($array as $path => $value) {
    $ref = &$result;
    foreach (explode('_', $path) as $key) {
        $ref = &$ref[$key];
    }
    $ref = $value;
}
var_export($result);


Python Bubble sort code I have written the below bubble sort code in Python.

def bubble_sort():
    num_list=[]
    list_cnt=input("How many numbers you would like to sort:")
    for i in range(int(list_cnt)): ### need to convert the value returned by input()
        num_list.append(input("Enter " +str(i)+" number:")) ##here we are using append method of list

    print("The values input are as follows:")
    print(num_list)

    print(len(num_list))
    ### Below new line of code added to convert list to integer###
    num_list=list(map(int,num_list))
    ## with the above line the code is now working as expected##
    max_index=len(num_list)-1 ## because list begins with 0
    print("max_index is:",max_index)
    for i in range(len(num_list)-1):
        j=0
        swapped=False
        for j in range(len(num_list)-1):
            if num_list[j] > num_list[j+1]:
                num_list[j],num_list[j+1]=num_list[j+1],num_list[j]
                print("Sorted when j=" +str(j)+ " and i=" + str(i)+ " is:\n ")
                print(num_list)
                swapped=True
        if not swapped:
            break

    print("The sorted list is :")
    print(num_list)

bubble_sort()

Your code's quite good. I'd however change it in the following ways:

Move the creation of the lits out of the buble_sort.
Remove the prints from buble_sort.
Follow PEP8.
Change for i in range(...) to while True:.
Use better variables. num_list to array could do.
Use str.format, rather than string addition.
Change the creation of num_list to use a list comprehension.

def bubble_sort(array):
    while True:
        swapped = False
        for j in range(len(array)-1):
            if array[j] > array[j+1]:
                array[j], array[j+1] = array[j+1], array[j]
                swapped = True
        if not swapped:
            break

if __name__ == '__main__':
    amount = input("How many numbers you would like to sort:")
    array = [
        int(input("Enter {} number:".format(i)))
        for i in range(int(amount))
    ]

    print("The values input are as follows: {}".format(array))
    bubble_sort(array)
    print("The sorted list is: {}".format(array))


Password Generator Python I decided to make a password generator to get more familiar with Python.
I had to break up the code into two boxes due to weird Stack Exchange highlighting with the triple quotes.
How would you improve this program on the grounds of:

Readability/cleanness,
Performance, and
Security.

Feel free to include any other comments you have on it that may not fit into those three categories.
import string
import random
import secrets
import argparse
import MyFormatter

alphaL = list(string.ascii_lowercase)
alphaU = list(string.ascii_uppercase)
numeric = list(string.digits)
special = list("!@#$%^&*")
special2 = list("""~`!@#$%^&*()+=_-{}[]\|:;"'?/<>,.""")

parser = argparse.ArgumentParser(
    formatter_class=MyFormatter.MyFormatter,
    description="Generates a password",
    usage="",
)

parser.add_argument("-lc", "--lower", type=int, default=1, help="Minimum number of lowercase alpha characters")
parser.add_argument("-uc", "--upper", type=int, default=1, help="Minimum number of uppercase alpha characters")
parser.add_argument("-n", "--numeric", type=int, default=1, help="Minimum number of numeric characters")
parser.add_argument("-s", "--special", type=int, default=1, help="Minimum number of special characters")
parser.add_argument("-se", "--extended", action = 'store_const', default = False, const= True, help="Toggles the extendard special character subset. Passwords may not be accepted by all services")
parser.add_argument("-l", "--length", type=int, default=20, help="Length of the generated password")

args = parser.parse_args()

length = args.length

minimums = [
    args.lower,
    args.upper,
    args.numeric,
    args.special,
]

password = ""

for i in range(0, minimums[0]) :
    password += secrets.choice(alphaL)

for i in range(0, minimums[1]) :
    password += secrets.choice(alphaU)

for i in range(0, minimums[2]) :
    password += secrets.choice(numeric)

if args.extended :
    subset = alphaL + alphaU + numeric + special2
    for i in range(0, minimums[3]) :
        password += secrets.choice(special2)
elif minimums[3] :
    subset = alphaL + alphaU + numeric + special
    for i in range(0, minimums[3]) :
        password += secrets.choice(special)

for i in range(0, 100) :
    random.shuffle(subset)

for i in range(len(password), length) :
    password += secrets.choice(subset)

for i in range(0, 100) :
    password = ''.join(random.sample(password, len(password)))

print("Password: ", password)

Already pointed out by other users

There is no need to make lists from the strings as any sequence will do
minimums - you make bad names where the existing names were better

The if clause
if args.extended :
    subset = alphaL + alphaU + numeric + special2
    for i in range(0, minimums[3]) :
        password += secrets.choice(special2)
elif minimums[3] :
    subset = alphaL + alphaU + numeric + special
    for i in range(0, minimums[3]) :
        password += secrets.choice(special)

is erroneous. The check for elif minimums[3] shall be replaced by an else:
Also - just because you already switch on args.extended you are not required to pack all variation on that argument in there.
You prepare subset for the logically next function (choice from compound set) before even performing the current one (choice from special).
That results in less readability. There is nothing wrong in switching two times if required. However in this case you should simply switch
if args.extended:
    special = """~`!@#$%^&*()+=_-{}[]\|:;"'?/<>,."""
else:
    special = "!@#$%^&*"

Then the choice from special/special2 collapses to the standard pattern.
Names
It was already mentioned that the minimum list is a name worse than the args attributes (which could be even more descriptive).
Also the names for your imports are bad and camel-cased. why not simply follow the existing naming scheme?
ascii_lowercase = string.ascii_lowercase

or even more straight
from string import ascii_lowercase
from string import ascii_uppercase
from string import digits

An extra bad name is subset
subset = alphaL + alphaU + numeric + special

which is clearly a union or superset
The standard pattern
You do
for i in range(0, minimums[0]) :
    password += secrets.choice(alphaL)

the recommended way to character wise join a string is
password += "".join(secrets.choice(ascii_lowercase) for _ in range (0, args.lower)

Cargo cult
You do
for i in range(0, 100) :
    random.shuffle(subset)

which is pointless. It is pointless to shuffle a 100 times. there is no extra quality in randomness compared to a single shuffle.
It is even more pointless to do that before apply secrets.choice(subset). You could safely sort subset before choice().
Final shuffle
You do
for i in range(0, 100):
    print("Password: ", password)
    password = ''.join(random.sample(password, len(password)))

which I interpret as final shuffle to eliminate the order of the subsets ascii_lowercase, ascii_uppercase, ...
Again you shuffle a 100 times which will not add any value compared to a single shuffle. To be cryptographically safe you should implement a shuffle based on secrets.choice.


All Possible Products I'm trying to find all possible product of two 3-digit numbers. When I work with small ranges, I'm able to get an output almost instantly but when the ranges are big, it seems to take really long time. I ran the code below and still didn't get an output past 15 minutes. Is there any way to to shorten the time to get the result?

a = []
for x in 100..999
    for y in 100..999
        num = (x * y)
        unless a.include? num
            a.push num
        end
    end
end

p a

Performance

Your code is slow because your algorithm is \$O(n^4)\$, where \$n = 900\$:

The outer x loop runs for 900 iterations (\$O(n)\$).
For every x, the y loop runs for 900 iterations (\$O(n)\$).
For every product, you search the array to see if the entry already exists.  Since the length of the array will grow up to \$O(n^2)\$, and .include? does a linear search, the deduplication takes \$O(n^2)\$ time.

You can cut the time in half by taking advantage of the fact that \$x \cdot y = y \cdot x\$.  The big win, though, would be to store the results in a Set, which performs deduplication for "free".  That would bring your runtime down to \$O(n^2)\$.

Style

The standard indentation width for Ruby is two spaces.

The parentheses around (x * y) are superfluous.  However, parentheses for the parameter to .include? would be considered good practice.


Key-scanning macro in NASM Win16 against DOSBOX (Intel 8086) Supports backspacing, but not wrapped backspacing.

%macro newline 0.nolist
    mov     ax, 0E0Dh
    int     10h
    mov     al, 0Ah
    int     10h
%endmacro

%macro getc 0.nolist
%%get:
    mov     ah, 11h
    int     16h        ; get keystroke status
    jnz     %%pressed
    hlt
    jmp     %%get
%%pressed:
    mov     ah, 10h
    int     16h        ; get the pressed key on "modern" keyboards
%endmacro

; %1 = string to write into
%macro scan 1
    pushaw
    mov     di, %1     ; prep for stosb
    xor     cx, cx
%%get:
    getc
    cmp     al, 13
    je      %%done     ; enter pressed
    cmp     al, 8
    je      %%bspace
    cmp     al, ' '
    jb      %%get      ; ignore most non-printing characters
    cmp     al, '~'
    ja      %%get

    push    bp
    mov     ah, 0Eh    ; print the valid character
    int     10h
    push    bp

    stosb              ; write the character to the string
    inc     cx
    cmp     cx, 80     ; ensure the buffer isn't exceeded
    jae     near %%done
    jmp     near %%get ; room for more
%%bspace:
    cmp     cx, 0
    je      %%get      ; ignore starting bspace

    push    bp
    mov     ax, 0E08h
    int     10h        ; bspace twice, to clear space
    mov     al, 32
    int     10h
    mov     al, 8
    int     10h
    pop     bp

    dec     di         ; overwrite character position
    dec     cx         ; step back a character
    jmp     %%get
%%done:
    xor     ax, ax
    stosb              ; append null-terminating character (zero)
    newline
    popaw
%endmacro

It's fine to write this scan macro for educational purposes, but I think that considering its length a subroutine would have been more appropriate. The macro's bytes are inserted everywhere the macro is invoked. That adds up! Having that many duplicated bytes in a program is a waste of space.

Some observations

push    bp
mov     ah, 0Eh    ; print the valid character
int     10h
push    bp
stosb              ; write the character to the string

That second push bp was probably meant to be pop bp, wasn't it?
But why would you want to preserve the BP register when the BIOS.Teletype function doesn't even touch it.

User @ecm commented about the BIOS Teletype function: BUG: If the write causes the screen to scroll, BP is destroyed by BIOSes for which AH=06h destroys BP
If this is the bug that made you decide to preserve the BP register, then I would say that preserving BP is still not the right thing to do. Because your code only supports non wrapped backspacing, it is reasonable to assume that no scrolling will occur. If scrolling were to happen then the backspacing user could get confused! Furthermore it's easy to make sure that scrolling can't occur simply by setting the cursor at the left edge of the screen at the start.

For maximum safety, I would write the char from AL in the string before teletyping it. On some implementations of BIOS/DOS etc. , I've seen the AX register modified even when the official documentation told it was preserved.

stosb              ; write the character to the string
mov     bh, 0      ; DisplayPage
mov     ah, 0Eh    ; print the valid character
int     10h

I've added the required BIOS parameter for the DisplayPage. In all of your posts you keep ignoring this parameter. I'm wondering if you have any documentation about these BIOS video functions that possitively states that there are no selectable display pages.

%%bspace:
    cmp     cx, 0
    je      %%get      ; ignore starting bspace

The cmp cx, 0 instruction has a 3-byte encoding, but the test cx, cx instruction (that does the same) has but a 2-byte encoding. In any macro you will want to write the shortest code.

%%bspace:
    test    cx, cx
    jz      %%get      ; ignore starting bspace

There's also the jcxz instruction that you could use here. Again shorter but some people will say it is slow. It's up to you to decide if that is of real importance here. Don't forget that the user at the keyboard is much, much slower than any of the lesser instructions that you could choose!

%%bspace:
    jcxz    %%get      ; ignore starting bspace

cmp     cx, 80     ; ensure the buffer isn't exceeded
jae     near %%done
jmp     near %%get ; room for more

The code becomes a little more efficient if you write the jump that is more likely first. The buffer will nearly never fill up completely, and so the jump to %%done will almost never happen.

cmp     cx, 80     ; ensure the buffer isn't exceeded
jb      near %%get ; room for more
jmp     near %%done

A quick rewrite

; %1 = string to write into
%macro scan 1
    pushaw
    mov     di, %1     ; prep for stosb
    xor     cx, cx
    mov     bh, 0      ; DisplayPage
%%get:
    getc
    cmp     al, 13
    je      %%done     ; enter pressed
    cmp     al, 8
    je      %%bspace
    cmp     al, ' '
    jb      %%get      ; ignore most non-printing characters
    cmp     al, '~'
    ja      %%get

    stosb              ; write the character to the string
    mov     ah, 0Eh    ; print the valid character
    int     10h
    inc     cx
    cmp     cx, 80     ; ensure the buffer isn't exceeded
    jb      near %%get ; room for more
    jmp     near %%done
%%bspace:
    jcxz    %%get      ; ignore starting bspace
    mov     ax, 0E08h
    int     10h        ; bspace twice, to clear space
    mov     al, 32
    int     10h
    mov     al, 8
    int     10h
    dec     di         ; overwrite character position
    dec     cx         ; step back a character
    jmp     %%get

%%done:
    xor     ax, ax
    stosb              ; append null-terminating character (zero)
    newline
    popaw
%endmacro


My insertion sort version I'd like to know what you think of my insertion sort version. I tried to be pythonic and avoid while loops with "ugly" index-management:
def sort(a):
    for i, x in enumerate(a):
        for j, y in enumerate(a):
            if y >= x:
                a.insert(j, a.pop(i))
                break

On lists of 1000 random numbers, it seems to be about four times faster (23 ms vs 96 ms) than the implementation from the top-voted answer for the top result for searching [python] insertion sort.
Benchmark code:
from random import random
from time import perf_counter as timer
from statistics import median

n = 1000
repeat = 50

def insertionSort(lst):
    for index in range(1, len(lst)):

        currentvalue = lst[index]
        position = index

        while position > 0 and lst[position - 1] > currentvalue:
            lst[position] = lst[position - 1]
            position = position - 1

        lst[position] = currentvalue

def sort(a):
    for i, x in enumerate(a):
        for j, y in enumerate(a):
            if y >= x:
                a.insert(j, a.pop(i))
                break

solutions = insertionSort, sort

for r in range(1, 6):
    print('Round %d:' % r, end='')
    a = [random() for _ in range(n)]
    for solution in solutions:
        times = []
        for _ in range(repeat):
            copy = a.copy()
            t0 = timer()
            solution(copy)
            times.append(timer() - t0)
            assert copy == sorted(a)
        print('   %6.2f ms' % (median(times) * 1e3), end='')
    print()

Code review
You should use better variable names then a, x and y. But otherwise since your code works your code is fine.
Performance
It seems a couple of users are confused why Python has strange performance.
Enumerate vs index
This is pretty simple both enumerate and index have the same time and space complexity.
If we have a list of False and set one to True and want to find the index of that, both will run in \$O(n)\$ time. It may seem like enumerate is \$O(1)\$ however it is the same as zip(range(len(sequence)), sequence) and we know range is \$O(n)\$.
The difference in speed that we can see is because index is just faster than enumerate.
Your insertion sort vs Grajdeanu Alex's
This comes down to Python being slower than C. If we look at the core of Grajdeanu's solution:

currentvalue = lst[index]
position = index

while position > 0 and lst[position - 1] > currentvalue:
    lst[position] = lst[position - 1]
    position = position - 1

lst[position] = currentvalue

This is doing two things:

Finding the index to stop iterating to:

while position > 0 and lst[position - 1] > currentvalue:

Performing an optimized version of insert and pop. This is as they only touch a subset of the array, but insert and pop touch the entire array, worst case. (Python lists are arrays in the backend.)

If you were to translate Grajdeanu Alex's solution into C the code would out perform your insert and pop.
Bisecting
There's a nice property about insertion sort, as you're iterating through the data everything before your index is sorted. This means we can use a better algorithm to find where to insert into.
We can use the strategy you use in the Guess a Number Between 1-100. By halving the amount of the list we have to search each check we can find where to insert into in \$O(\log(n))\$ time. This is faster than than the \$O(n)\$ that your enumerate and Grajdeanu's algorithms are running in.
There is a library for this, bisect, and most of the legwork is in C too, so it's nice and fast.
My timings
My code to get the timings:

import time
import math
import random
import copy
import bisect

import matplotlib.pyplot as plt
import numpy as np

from graphtimer import flat, Plotter, TimerNamespace

class Iteration(TimerNamespace):
    def test_baseline(data):
        pass

    def test_iterate(data):
        for value in data:
            pass

    def test_enumerate_list(data):
        for item in list(enumerate(data)):
            pass

    def test_enumerate_partial(data):
        for item in enumerate(data):
            pass

    def test_enumerate(data):
        for i, value in enumerate(data):
            pass

class Insertion(TimerNamespace):
    def test_baseline(data, i, value_i, j, value_j):
        pass

    def test_plain(data, i, value_i, j, value_j):
        data.insert(j, data.pop(i))

    def test_index(data, i, value_i, j, value_j):
        data.insert(data.index(value_j), data.pop(i))

    def test_python(data, i, value_i, j, value_j):
        while i < j:
            data[j] = data[j - 1]
            j -= 1
        data[j] = value_i

class Joined(TimerNamespace):
    def test_enumerate_plain(data, i, value_i, j, value_j):
        for j, value_j in enumerate(data):
            if value_i <= value_j:
                data.insert(j, data.pop(i))

    def test_enumerate_index(data, i, value_i, j, value_j):
        for j, value_j in enumerate(data):
            if value_i <= value_j:
                data.insert(data.index(value_j), data.pop(i))

    def test_iterate_index(data, i, value_i, j, value_j):
        for value_j in data:
            if value_i <= value_j:
                data.insert(data.index(value_j), data.pop(i))
                break

class Sorts(TimerNamespace):
    def test_manuel_base(a):
        for i, x in enumerate(a):
            for j, y in enumerate(a):
                if y >= x:
                    a.insert(j, a.pop(i))
                    break

    def test_manuel_insert(a):
        for i, x in enumerate(a):
            for y in a:
                if y >= x:
                    a.insert(a.index(y), a.pop(i))
                    break

    def test_other(lst):
        for index in range(1, len(lst)):
            currentvalue = lst[index]
            position = index
            while position > 0 and lst[position - 1] > currentvalue:
                lst[position] = lst[position - 1]
                position = position - 1
            lst[position] = currentvalue

    def test_peilon(lst):
        output = []
        for item in lst:
            bisect.insort(output, item)

memoize = {}

def create_args(size, *, _i):
    size = int(size)
    key = size, _i
    if key in memoize:
        return copy.deepcopy(memoize[key])
    array = random_array(size)
    j = random.randrange(0, size)
    array[:j] = sorted(array[:j])
    i = 0
    while array[i] < array[j]:
        i += 1
    output = array, i, array[i], j, array[j]
    memoize[key] = output
    return output

def random_array(size):
    array = list(range(int(size)))
    random.shuffle(array)
    return array

def main():
    fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, subplot_kw=dict(xscale='log', yscale='log'))
    axis = [
        (Iteration, {'args_conv': lambda i: [None]*int(i)}),
        (Insertion, {'args_conv': create_args, 'stmt': 'fn(args[0].copy(), *args[1:])'}),
        (Joined, {'args_conv': create_args, 'stmt': 'fn(args[0].copy(), *args[1:])'}),
        (Sorts, {'args_conv': random_array, 'stmt': 'fn(args[0].copy(), *args[1:])'}),
    ]
    for graph, (plot, kwargs) in zip(iter(flat(axs)), axis):
        (
            Plotter(plot)
                .repeat(10, 2, np.logspace(1, 4), **kwargs)
                .min()
                .plot(graph, title=plot.__name__)
        )
    plt.show()

if __name__ == '__main__':
    main()

(click to expand)

Iteration

test_baseline
The timings are flat as they are the time it takes to run the test suit. When determining the performance of each function we need to see how far away from the baseline it is.

test_enumerate & test_enumerate_partial
These are roughly the same and so we know that enumerate, and not tuple unpacking, is the factor at play that is taking up a lot of performance.

test_enumerate, test_enumerate_list & test_iterate
We can see adding more \$O(n)\$ operations makes the code slower. However enumerate is a pretty slow function.

In all enumerate is slow.
Insertion

test_baseline
Since we are copying the data in the test suit we see that at times the other functions are running the fastest that they can.
This is to be expected as we are running tests on a partially sorted array. Ranging from no sort to fully sorted.

test_plain
We can see that data.insert(j, data.pop(i)) is really fast and is consistently around test_baseline. This means if enumerate was faster than data.index then the other answer would not be true.

test_index & test_python
From the areas we can see that optimized Python runs significantly slower than Python's C methods.
This is to be expected, Python is slow.

Joined
These merge the above two together to show the impact of the difference in timings.
These are a single insertion of a full insertion sort.
Unsurprisingly given the previous timings test_enumerate_plain is by far the slowest.
Sorts
This shows that whilst your changes are fast, my answer from '17 is a pretty darn fast insertion sort.
Complexity vs Performance
It should be apparent that in Python these are two entirely different metrics. Complexity is more important when playing on a level playing field, which isn't the case in Python.
But just because Python isn't a level playing field doesn't make it useless. When programming if you try to get the best performance complexity wise then you'll have a good baseline to then optimize from. From here you can then focus on performance which is harder to reason with and harder to compare. And worst case converting the code into C will be far easier.


PHP JPG image re-creation from original file A third party can upload files via FTP to a client's webserver. These images should be displayed on a public-available webpage. The upload directory is not accessible via normal HTTP. To increase security I thought it might be a good idea to re-create the images and store it in the web-folder manually.

The import format is always JPG. The function will return the new filename if the image could be created or null otherwise.

Is there any way to improve it? Especially all the "early returns" look kind of ugly.

function processImage($filename, $importPath, $storagePath, $quality = 80) {
    $source = $importPath . $filename . '.jpg';
    $target = $filename . '_processed.jpg';
    $storage = $storagePath . $target;

    if (!file_exists($source)) {
        return null;
    }

    $image = imagecreatefromstring(file_get_contents($source));

    if (!$image) {
        return null;
    }

    $dimension = [
        imagesx($image),
        imagesy($image)
    ];

    $newImage = imagecreatetruecolor($dimension[0], $dimension[1]);

    if (!$newImage) {
        return null;
    }

    if (!imagecopyresampled($newImage, $image, 0, 0, 0, 0, $dimension[0], $dimension[1], $dimension[0], $dimension[1])) {
        return null;
    }

    if (!imagejpeg($newImage, $storage, $quality)) {
        return null;
    }

    return $target;
}

PS: The filename is available without the extension .jpg as a string. In case you worry about the first line.

You may use this advice from stackexchange:

$im = imagecreatefrompng(input_filename)
imagejpeg($im, output_filename);

A call to imagecopyresample in your example is quite resource-consuming and can cause image quality loss. The call above is the same as 'open-save' in any graphical editor. I doubt that it leaves any malicious data intact, as imagejpeg re-compresses the raw image again.

Another option is to use exif_imagetype:

  exif_imagetype() reads the first bytes of an image and checks its signature.

This prevents upload of non-graphical files masked as graphical, but does not eliminate a file that contains a jpeg signature, but is not jpeg.


Developing API methods to return JSON When developing API methods to return JSON with details I often find myself creating the following code:

    $response = array('success' => false);

    $user = User::getSessionUser();
    if($user->id > 0){
        if(ItemSKU::stringIsValid($sku)){

            $itemSKU = ItemSKU::getFromString($sku);
            if($itemSKU->isAvailable()){
                if(Carts::add($user->id, $sku)){
                    $response['success'] = true;
                }
                else{
                    $response['error'] = "Item was already added";
                }
            }
            else{
                $response['error'] = "Unavailable Item";
            }
        }
        else{
            $response['error'] = "Invalid SKU";
        }
    }
    else{
        $response['error'] = "Invalid User";
    }

    return response()->json($response);

How can I avoid using this nested if-else chain?

Personally I prefer avoiding such nested if-else constructs, simply by reversing the logic, e.g.:

if(!cond1)
    return value;
if(!cond2)
    return value2;
// etc.

instead of:

 if (cond1)
     if(!cond2)
         return value2;
 else
     return value;


Random timestamp within last 3 relative years I'm trying to generate a random time between now and 3 years ago. To my knowledge, Go doesn't have a random(min,max) feature in either math/rand or crypto/rand where min > 0. To naively combat that, I generate a slice containing every time stamp within the relative now and 3 years ago, and then select the index at random with rand.Intn(len(timeRange)), because I am guaranteed to get a random index between 0 and len(timeRange). It works just fine, and I get a Unix time stamp sometime between now and 3 years ago. However, I want to generate just one timestamp, not ~94m of them and then randomly picking one...it's egregiously slow.

Here is the code:

package main

import (
    "time"
    "math/rand"
    "fmt"
)

func randomTimestamp() time.Time {
    now := time.Now().Unix()
    threeYearsAgo := int64(now - 94608000)
    timeRange := make([]int64,1)
    for i := threeYearsAgo; i < now; i++ {
        timeRange = append(timeRange, i)
    }
    randomTime := rand.Intn(len(timeRange))

    randomNow := time.Unix(timeRange[randomTime], 0)

    return randomNow
}

func main() {
    for i := 0; i < 25; i++ {
        fmt.Println(randomTimestamp().Format(time.RFC3339))
    }
}

How can I optimise randomTimestamp() so it doesn't have to calculate every second over the last 3 years, but it randomly picks one between now and 3 years ago?

As Darren H has said in the comments, just generate a random number between 0 and nanoseconds in three years, and subtract from time.Now():

const threeYears = 3 * 365 * 24 * time.Hour

func main() {
    rand.Seed(time.Now().UnixNano())
    d := time.Duration(rand.Int63n(int64(threeYears)))
    fmt.Println(time.Now().Add(-d))
}


Object spawning script Unity I'm trying to make a random object spawning script in Unity.

Bellow is the code, any suggestions for improvement / changes?
I'm new to both Unity and C#.

// Game objects and Transforms
public Transform playerTransform;
public Transform[] obstaclePrefab;

// spawn params
public float minYDicstane = 6.0f;
public float maxYDistance = 11.0f;
private float boxPositionY;

public float minXDistance = 0.0f;
public float maxXDistance = 3.0f;
private float boxPositionX;

private float minSpawnTime;
private float maxSpawnTime;
private float spawnTime;
private float timeCounter;

// Distances
private float playerDistance;
private float boxDistance;
private float ySpread;

private void Start()
{
    // Count sequence
    minSpawnTime = 3.0f;
    maxSpawnTime = 8.0f;

    // Count timer
    timeCounter = 0;
    spawnTime = Random.Range(minSpawnTime, maxSpawnTime);

}

private void Update()
{
    // Count the random spawn time
    timeCounter += Time.deltaTime;
    Debug.Log ("Spawn Time: " + spawnTime + " spawnCount: " + timeCounter);

    if(timeCounter >= spawnTime)
    {
        // boxDistanceFromPlayer
        playerDistance = playerTransform.position.y;

        // Box spawn distance
        // X position
        boxPositionX = Random.Range(minXDistance, maxXDistance);
        boxPositionX = (boxPositionX-1)*2.0f;

        // Y Position
        boxPositionY = playerDistance + Random.Range(minYDicstane, maxYDistance);

        // Select box color
        int boxColor = Random.Range (0, 4);

        // Let the boxes awake!!!
        Instantiate (obstaclePrefab [boxColor], new Vector2 (boxPositionX, boxPositionY), Quaternion.identity);

        // Make new random spawn time
        spawnTime = Random.Range (minSpawnTime, maxSpawnTime);
        timeCounter = 0;
    }

}

Code after changes, using coroutines

// Game objects and Transforms
public Transform playerTransform;
public GameObject[] obstaclePrefab;

// spawn params
public float minYDicstane = 6.0f;
public float maxYDistance = 11.0f;

public float minXDistance = 0.0f;
public float maxXDistance = 3.0f;

public float minSpawnTime = 2.0f;
public float maxSpawnTime = 5.0f;

public float spawnTime = 4.0f;

IEnumerator SpawnBoxes()
{
    while (true)
    {
        float boxPositionY;
        float boxPositionX;

        //Distances
        float playerDistance;

        // Player position
        playerDistance = playerTransform.position.y;

        // Box position
        boxPositionX = Random.Range(minXDistance, maxXDistance);
        boxPositionY = playerDistance + Random.Range(minYDicstane, maxYDistance);

        // Select box
        GameObject box = obstaclePrefab[Random.Range(0, obstaclePrefab.Length - 1)];

        // Instantiate box
        Instantiate (box, new Vector2 (boxPositionX, boxPositionY), Quaternion.identity);

        // Coroutine random amount of time
        yield return new WaitForSeconds(Random.Range(minSpawnTime, maxSpawnTime));
    }
}

private void Start()
{
    StartCoroutine(SpawnBoxes());
}

public Transform[] obstaclePrefab;

That's wrong. Prefabs are of type GameObject, not Transform.

private float minSpawnTime;
private float maxSpawnTime;

Why did you make these private? They should have been public with default values - just as all the others.

private float boxPositionY;
private float boxPositionX;
// Distances
private float playerDistance;
private float boxDistance;
private float ySpread;

These shouldn't even been private, but local to the Update() method, as their values are never reused.

// Select box color
int boxColor = Random.Range(0, 4);

This is very likely to break. Better read the array length instead of hard coding it:

// Select box color
int boxColor = Random.Range(0, obstaclePrefab.Length - 1);

Or just get rid of boxColor all together:

// Select box
GameObject box = obstaclePrefab[Random.Range(0, obstaclePrefab.Length - 1)];

// Count the random spawn time
timeCounter += Time.deltaTime;
if(timeCounter >= spawnTime)
{
    // Make new random spawn time
    spawnTime = Random.Range (minSpawnTime, maxSpawnTime);
    timeCounter = 0;
}

That's one way to do it. The cleaner method would have been to handle this in a Coroutine and then use WaitForSeconds. Right now, your code runs every single frame, without actually doing anything useful.

Debug.Log ("Spawn Time: " + spawnTime + " spawnCount: " + timeCounter);

Be careful when you log. Logging when something spawns? OK. But spamming a log entry every single frame? Waste of resources.

boxPositionX = (boxPositionX-1)*2.0f;

What is this line supposed to do? That should have been directly computed into minXDistance and maxXDistance, so this line is obsolete.

If this is actually supposed to be C#, the whole script you posted should actually have wrapped in a regular C# class:

using UnityEngine;
using System.Collections;

public class ScriptName : MonoBehaviour {
    // <---- Your stuff goes here
}

Did you just omit this when posting your code here, or did you actually write your scripts without it?


Find articulation points/ cut vertices in graph I would like to get some feedback on my completed code that finds and displays the articulation vertices in an undirected graph.
I included a test case within the code, it should (and does) print c as the only articulation vertex.
Also I would like to clarify my understanding on some things,

This runs in \$\mathcal{O}(V+E)\$ time

In the final line of code I do,  low_vis[vertex] = min(low_vis[neighbour], discovered[vertex])
Does it make a difference if I use the fixed discovered position as shown above, or the lowest reachable visited vertex position (low_vis), my own tests showed no difference and the same answer was returned (c).

Thank you
class vertex:

  def __init__(self, key):

    self.neighbours = {}
    self.key = key

  def add(self, key, edge):
    self.neighbours[key] = edge

class graph:

  def __init__(self):

    self.root = {}
    self.nbnodes = 0
    self.curr = 0

  def add(self, key1, key2, edge=0):
    if key1 not in self.root:
      self.root[key1] = vertex(key1)
      self.nbnodes += 1
    if key2 not in self.root:
      self.root[key2] = vertex(key2)
      self.nbnodes += 1

    self.root[key1].add(key2, edge)
    self.root[key2].add(key1, edge)

  def cutver(self):

    visited = set()
    discovered = {}
    low_vis = {}
    parent = {}
    result = []

    for vertex in self.root:
        if vertex not in visited:
          parent[vertex] = -1
          self._cutver(vertex, parent, visited, discovered, low_vis, result)
    print(result)

  def _cutver(self, vertex, parent, visited, discovered, low_vis, result):

    visited.add(vertex)
    discovered[vertex] = self.curr
    low_vis[vertex] = self.curr
    children = 0
    self.curr += 1

    for neighbour in self.root[vertex].neighbours:

      if neighbour not in visited:
        parent[neighbour] = vertex
        children += 1
        self._cutver(neighbour, parent, visited, discovered, low_vis, result)

        low_vis[vertex] = min(low_vis[vertex], low_vis[neighbour])

        if children > 1 and parent[vertex] == -1:
          result.append(vertex)

        if parent[vertex] != -1 and low_vis[neighbour] >= discovered[vertex]:
          result.append(vertex)

      elif neighbour != parent[vertex]:
        low_vis[vertex] = min(low_vis[neighbour], discovered[vertex])

if __name__ == '__main__':
      a = graph()
      A = 'A'
      B = 'B'
      C = 'C'
      D = 'D'
      E = 'E'
      a.add(A,B)
      a.add(A,C)
      a.add(B,D)
      a.add(D,C)
      a.add(C,E)
      a.cutver()

PEP-8
class vertex:
class graph:

PEP-8 asks that you name these Vertex and Graph, with initial capital.
naming nodes
    self.key = key

Yes, you will be using this as a dict key.
But name would have been the more natural identifier for a node name.
unused attribute
Please delete this line:
    self.nbnodes = 0

That quantity may be trivially obtained with len(self.root),
and in any event you never reference it.
edge weight
At first blush this appears to be a default edge ID of zero:
def add(self, key1, key2, edge=0):

Later it looks more like an edge weight, an attribute of the edge.
It would be helpful for a docstring to clarify this.
Or just name it edge_weight.
API
Consider having cutver() print nothing,
and instead return a result which the caller may print.
Also, _cutver() feels a lot like a Fortran subroutine,
as it has side effects on the result parameter,
rather than returning a result.
sentinel
You use this:
      parent[vertex] = -1

without every verifying that a node name is not -1,
or constraining each node name to be a str.
The usual convention would be to use None to represent this.
docstring
    self.curr = 0

This is absolutely not self-descriptive enough.
Use a """docstring""" or # comment to tell us what quantity it is measuring.
reference
In general _cutver() is obscure,
which increases the difficulty of answering your two questions.
It cites no references and does not attempt to justify
any of its algorithmic steps.
Perhaps it correctly finds cut vertices,
but the text does not give us any reason to see why that is obviously true.
If the code tries to adhere to Hopcroft73 (with Tarjan, algorithm 447),
then choosing to omit identifiers like lowpoint
is not helping the reader to see how the current implementation
corresponds to what Hopcroft describes.


Change upper or lowercase vowels to [0,1,2,3,4] respectively and leave the rest the same The objective was the following to be solved in Python:

  Given a string, def a function that
  returns another string with the vowels
  (upper or lowercase) replaced by
  0,1,2,3,4 respectively.

  Example input:

"bB nN aei ou AEIOU"

  Desired Output:

"bB nN 012 34 01234"

This is in fact quite trivial and can be solved in several ways, one way may be this:

def crypt(s):
    vow = ["a","e","i","o","u"]
    stringL = []

    for x in s:
        if x in vow or x.lower() in vow:
            stringL.append(str(vow.index(x.lower())))
        else:
            stringL.append(x)

    return "".join(stringL)

I was told this was over-complicated for such a simple task, that code like this would be difficult to debug etc.

Would you consider this approach a "bad" one, which way would you have gone instead, is it unclear?

Use string.maketrans().

from string import maketrans

input = "aeiouAEIOU"
output = '0123401234'
trans = maketrans(input,output)
str = 'This is a Q&A site, not a discussiOn forUm, so please make sure you answer the question.'
print str.translate(trans)

Output:

Th2s 2s 0 Q&0 s2t1, n3t 0 d2sc4ss23n f3r4m, s3 pl10s1 m0k1 s4r1 y34 0nsw1r th1 q41st23n.


Refactoring jQuery slider code suggestions I needed to build a slider, and this is my first attempt. I'm trying to make it as dynamic as possible. My code works, but I'm wondering if there is a better way and if anyone has any suggestions. I'll be making the width calculated as well. I just have it hardcoded for testing.

Also, I need to make pagination for this. I'm not sure where to start with the way I have things set up. Any hints as to where to start would be much appreciated.

Here is the link to the working slider: http://wss.manage-website.com/stg/4406

Javascript:

jQuery.noConflict();
  jQuery(document).ready(function ($) {
    function doAnimation() {
      count = $('.slider img').length;
      $('.slider img').each(function(index) {
        // calculate and asign z-index to the images. First image in the stack recieves highest.
        var zindex = count - index;
        $(this).css('z-index', zindex);
        $(this).delay(3000*index).animate({
          left: '495px'
        }, 500, function() {
          $('.slider img').each(function(index) {
            // convert z-index to an integer
            var zindex = parseInt($(this).css('z-index'));
            // calculate z-index of images to retain order in the stack. Send this one to the back, push the rest up one.
            if (zindex < count) {
              $(this).css('z-index', zindex + 1);
            } else {
              $(this).css('z-index', zindex - (count-1));
            }
          });
          $(this).animate({
            left: '0'
          }, 500, function() {
            // if we're at the end, repeat.
            if (index == count - 1) {
              setTimeout(doAnimation,1500);
            }
          });
        });
      });
    }
    doAnimation();
  });

Some minor improvements you can make:

Cache your DOM lookups (e.g. $('.slider img')) to prevent having to parse the DOM multiple times. That's as simple as making a new variable:

var sliderImages = $('.slider img');

Use a ternary statement for setting your z-index:

$(this).css('z-index', zindex < count ? zindex + 1 : zindex - count - 1);

That'll remove 4 lines and remove unnecessary repetition.
Add the var keyword to your count variable so it's not global (it should remain accessible to all the functions within your function scope anyway).
Add some simple comments to explain why you're changing the z-index in the first place.


Implementing a 7-3-1 check digit I need to implement a method that adds a "7-3-1" check digit to my id. The "7-3-1" method works as following:

Weights 7, 3, 1 are assigned to the original number from right to left. So if the original number is 12345, then 5 will have weight 7, 4 will have weight 3, 3 will have weight 1, 2 will have weight 7, 1 will have weight 3.
Numbers are multiplied by their weight and added to each other. So 5*7 + 4*3 + 3*1 + 2*7 + 1*3 = 67.
Sum is rounded to next full tenth and then from that sum is subsctracted to get the weight. So 70 - 67 = 3.

And the number with check digit would be 123453.

Here is what I have at the moment:

class ReferenceNumberUtil
{
    private static $offset = 0; // possiblity to set offset

    public static function referenceNumberFromId($id)
    {
        $id = $id + ReferenceNumberUtil::$offset;
        $weights = [7, 3, 1];
        $sum = 0;
        foreach (array_reverse(str_split($id)) AS $index => $digit) {
            $weightIndex = $index % 3;
            $sum += $digit * $weights[$weightIndex];
        }
        $checkDigit = (ceil($sum / 10) * 10) - $sum;
        return $id . $checkDigit;
    }

    public static function idFromReferenceNumber($number)
    {
        $numberWithoutCheckDigit = substr($number, 0, -1);
        return $numberWithoutCheckDigit - ReferenceNumberUtil::$offset;
    }
}

I've ran some tests and as far as i can tell this works correctly. But i'm still kind of hesitant. I would appreciate a review of this code to be certain that it works correct in all situations and also any ideas on how to improve it further are also welcome.

What is the purpose of $offset? It doesn't seem to do anything here.
What is the possible range of values of $id? Do you need to check that it is an integer, and that it is not negative?
Can $id have leading zeroes? That would naturally mess up the alignment with the 7 3 1 array, and possibly interfere with using str_split.
I would personally be very nervous about mixing around types like this, treating things as integers, then strings, then integers, then strings again.... At a minimum I would recommend being explicit about every time you do so. Otherwise it's far from clear what is going on.

  Sum is rounded to next full tenth and then from that sum is subsctracted

I would personally always prefer to use mod for this sort of thing, partly because messing with floating point numbers is confusing and partly just because the operation is inherently a mod calculation. For example something like this works as long as $sum is at least 1:

$checkDigit = 9 - (($sum - 1) % 10)


Raise an event (sample 1) I'm writing tutorials for new programmers. The tutorials show programmers how to structure events.

I've attached the code for one of the tutorials. Can someone take a look at my code and let me know if you see any bugs or gotchas? The goal of the code is to

be extremely easy to read and short
show a clear separation of the publisher and listener
use custom arguments

You can test the code here.

using System;

// program that managers publisher and listener
public class Program
{
    // subscribe to event, raise event
    public static void Main()
    {
        // new publisher
        Publisher publisher = new Publisher();
        // new listener
        Listener listener = new Listener();
        // subscribe to event
        listener.Subscribe(publisher);
        // raise event
        publisher.RaiseEvent();
    }
}

// object with the event
public class Publisher
{
    // declare event handler
    public delegate void EventHandler(Object sender, RaiseArgs e);
    // declare event
    public static event EventHandler Event;
    // raise event, result: "hello"
    public void RaiseEvent()
    {
        RaiseArgs args = new RaiseArgs();
        args.Message = "hello";
        Event(this, args);
    }
}

// object that listens for the event
public class Listener
{
    // subscribe to event
    public void Subscribe(Publisher publisher)
    {
      Publisher.Event += HeardEvent;
    }

    static void HeardEvent(Object sender, RaiseArgs e)
    { Console.WriteLine(e.Message); }
}

// the arguments to use with an event
public class RaiseArgs : EventArgs
{
    public string Message { get; set; }
}

I'm bringing your code in line with C#3, which is about 8 years old, so hopefully can be used by your audience. By and large, it's making the class Listener static because it contains no state, using EventHandler<T> to create an event handler rather than using a custom delegate and using var to declare local variables with. I also added some vertical spacing so the code could breathe. The class 'RaiseArgs' is now immutable since the state should remain the same after creation. I like having classes sealed unless my design requires them not to be (it prevents them from being inherited). And lastly, I used a thread-safe access to the event by copying it to a local variable and comparing to null. And now the code:

using System;

// program that managers publisher and listener
public static class Program
{
    // subscribe to event, raise event
    public static void Main()
    {
        // new publisher
        var publisher = new Publisher();

        // subscribe to event
        Listener.Subscribe(publisher);

        // raise event
        publisher.RaiseEvent();
    }
}

// object with the event
public sealed class Publisher
{
    // declare event
    public event EventHandler<RaiseArgs> Event;

    // raise event, result: "hello"
    public void RaiseEvent()
    {
        var handler = Event;

        if (handler != null)
        {
            var args = new RaiseArgs("hello");

            handler(this, args);
        }
    }
}

// object that listens for the event
public static class Listener
{
    // subscribe to event
    public static void Subscribe(Publisher publisher)
    {
        publisher.Event += HeardEvent;
    }

    private static void HeardEvent(object sender, RaiseArgs e)
    {
        Console.WriteLine(e.Message);
    }
}

// the arguments to use with an event
public sealed class RaiseArgs : EventArgs
{
    private readonly string _Message;

    public RaiseArgs(string message)
    {
        _Message = message;
    }

    public string Message
    {
        get
        {
            return _Message;
        }
    }
}


Splitting a range into min and max? I needed to get the minimum and maximum date values from a query using the Sequel ORM in Ruby from my database. Sequel has a range method that returns a Range value. I'm having it return values from a timestamp field, so they're coming back as a range of Time objects.

In order to split it into two variables using parallel assignment, I figured this was about as concise and succinct as I could get:

template_min_datestamp, template_max_datestamp = [Template.range(:created_at)].map{ |r| [r.min, r.max] }

I considered using:

template_min_datestamp, template_max_datestamp = Template.min(:created_at), Template.max(:created_at)

but that'd cause two hits to the database, which just makes my eye twitch.

Simplifying it for the innocent, and factoring out the ORM calls, it'd look something like this in regular Ruby:

t1 = Time.parse('Jan 1, 2013 12:00:00 -700')
t2 = Time.parse('Jan 31, 2013 12:00:00 -700')
template_min_datestamp, template_max_datestamp = [t1..t2].map{ |r| [r.min, r.max] }

It seems like there'd be a more direct way to break apart a range into two elements on one line using parallel assignment, but it's escaping me right now.

Anyone got some enlightenment to share?

Update

@steenslag points out the minmax builtin. No monkey patching necessary.

template_min_datestamp, template_max_datestamp = Template.range(:created_at).minmax


Transpose 2D Matrix in Java - Time & Space Complexity? Here's my algorithm / approach for transposing a 2D Matrix on the main diagonal.

Before:

a L M d
b G c N
H K e F
I J O P

After:

a b H I
L G K J
M c e O
d N F P

My code:

public class Matrix {

    static String[][] matrix = {

            {"a", "L", "M", "d"},
            {"b", "G", "c", "N"},
            {"H", "K", "e", "F"},
            {"I", "J", "O", "P"}
    };

    public void transpose(String[][] matrix) {
       String[][] transposedArray = new String [4][4];
       for (int row =0; row < 4; row ++) {
           for (int col = 0; col < 4; col++) {
               transposedArray[row][col] = matrix[col][row];
           }
       }
    }
}

What is the time & space complexity of this approach?

Is there a better optimal solution?

I have three suggestions for you.

Instead of String, you can use char, less memory footprint than a String.
In the transpose method, I suggest that you return the array, since the method does nothing at the moment.

static char[][] matrix = {
   {'a', 'L', 'M', 'd'},
   {'b', 'G', 'c', 'N'},
   {'H', 'K', 'e', 'F'},
   {'I', 'J', 'O', 'P'}
};

public char[][] transpose(char[][] matrix) {
   char[][] transposedArray = new char [4][4];

   for (int row = 0; row < 4; row ++) {
      for (int col = 0; col < 4; col++) {
         transposedArray[row][col] = matrix[col][row];
      }
   }

   return transposedArray;
}

Since the matrix variable is static, I suggest that you also put the method static.

Refactored code

public static void main(String[] args) {
   System.out.println(Arrays.deepToString(transpose(matrix)));
}

static char[][] matrix = {
   {'a', 'L', 'M', 'd'},
   {'b', 'G', 'c', 'N'},
   {'H', 'K', 'e', 'F'},
   {'I', 'J', 'O', 'P'}
};

public static char[][] transpose(char[][] matrix) {
   char[][] transposedArray = new char [4][4];

   for (int row = 0; row < 4; row ++) {
      for (int col = 0; col < 4; col++) {
         transposedArray[row][col] = matrix[col][row];
      }
   }

   return transposedArray;
}


Validating a tab-delimited string This code checks if string has correct format for passing to struct. Correct format needs to be [123456789'\t'First Name'\t'Last Name'\t'City]. I didn't know how to enter tabs, so I used '\t'. I use them to separate different word blocks so e.g. first and middle name can be read to a first name in struct.

I wrote alternative version as well (in comments). Which one is more preferable?
How is the correct form to write nested ternary operator

int checkString(char *string, int len)
{

    char *ch;
    int flag = FALSE;
    int i = 0;

    ch = string;

    i = 0;
    /*
    while (ch[i] && ch[i] != '\t') {
        if (isdigit(ch[i])) {
            if (++i == len) {
                flag = ch[i] == '\t' ? TRUE : FALSE;
            }
        } else { ch++; }
    }
    */

    /* ID code needs to be 11 digits */
    for (i = 0; ch[i] && ch[i] != '\t';
        isdigit(ch[i]) ?
        flag = ++i == len ?             // while true
        ch[i] == '\t' ? TRUE : FALSE    // while true
        : FALSE
        : *ch++);

    /* Three tabs is correct */
    if (flag) {
        for (i = 0; ch[i];
        ch[i] == '\t' ?
        flag = ++i == 3 ? TRUE : FALSE
        : *ch++);
    }

    return flag;
}

Avoid nested ternary operators. It hardly ever improves readability over proper if-else conditions.

When the boolean values true and false are involved, often there's simply no need for tensors at all, like in this example:

flag = ch[i] == '\t' ? TRUE : FALSE;

This is equivalent and simpler:

flag = ch[i] == '\t';

When a condition gets complicated, another technique is to extract the complex boolean expression to a helper method with a good descriptive name.


Pointers for struct and `for` I know something about pointers, but I'm trying to check my knowledge on a sample.  Can somebody check if my code is good?  I don't think that I should use pointers in these structs.

The second question is: Can I use a for loop like this?

for(DLList* i=first; i!=0; i=i->next)

Is it correct?

struct Node
{
    int id;
    int dist;
    Node* prev;
    vector<Edge*> edges;
};

struct Edge
{
    int length;
    Node* to;
};

struct DLList
{
    DLList *next;
    DLList *prev;
    Node* val;
};

struct DList
{
    DLList *first,*last;

    DList()
    {
        first = 0;
        last = 0;
    }

    DLList* add(Node* n)
    {
        DLList *newNode = new DLList;
        if(first == 0)
        {
            newNode->val = n;
            newNode->next = 0;
            newNode->prev=0;
            first =  newNode;
            last = newNode;
        }
        else
        {
            newNode->val = n;
            newNode->next = 0;
            newNode->prev=last;
            last = newNode;
            last->next=newNode;
        }
        return last;
    }

    void removeFirst()
    {
        if(first!=0)
        {
            first = first->next;
            if(first != 0)
            {
                first->prev = 0;
            }
        }
    }

    void remove(DLList* e)
    {
        if(e==0)
        {
            return;
        }
        else if(e==first)
        {
            removeFirst();
        }
        else if(e==last)
        {
            last = last->prev;
            last -> next = 0;
        }
        else
        {
            e->prev->next = e->next;
            e->next->prev = e->prev;
        }
    }

    void remove(Node* n)
    {
        if(first == 0)
        {
            return;
        }
        if(n==first->val)
        {
            removeFirst();
        }
        else if(n==last->val)
        {
            last = last->prev;
            last->next = 0;
        }
        else
        {
            for(DLList* i=first; i!=0; i=i->next)
            {
                if(n==i->val)
                {
                    i->prev->next = i->next;
                    i->next->prev = i->prev;
                    break;
                }
            }
        }
    }

    bool isEmpty()
    {
        return first == 0;
    }

};

I'm assuming that this is basically a pointer exercise rather than a real piece of code that you're planning to use.  If it's the latter, please reconsider -- there are STL containers that do this better and safer.  As to your question about the for loop, there's nothing wrong with that if you're using pointers.  In fact it's a pretty common idiom in C.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  I don't know that you're doing that, but the use of vector in the definition of Node suggests it.

Use nullptr

Every instance of 0 in your code would probably more correctly be encoded as nullptr as defined in C++11.  If you're using an older compiler, you can use NULL instead which will more clearly indicate to readers of your code that these are pointers.

Reconsider the interface

If this is a pointer exercise, that's fine, but if you actually intend to use this for something, you should probably reconsider the interface.  Specifically, passing around raw pointers is not generally a good idea in C++.  Better would be to use unique_ptr (C++11) or auto_ptr (C++03).

Also the version of remove() that takes a linked list node pointer as an argument is a very dangerous thing to have in an interface.  Knowledge of a node's structure would be better encapsulated within the class and not revealed as part of the interface.

Use better names

Having DLList as the name of a class implementing a doubly-linked list makes sense, but having that actually be the name of an individual node in such a list does not.  Instead of DList and DLList, it would be much easier to interpret your code if they were named DLList and DLListNode.  Also the function add suggests that the node is added to the end, but the code actually prepends this to the list which is, at best, confusing.

Simplify remove(Node* n)

The remove(Node *n) is more complex than it needs to be.  It could be rewritten as:

void remove(Node* n)
{
    for(DLListNode* i=first; i!=nullptr; i=i->next)
    {
        if(n==i->val)
        {
            i->prev->next = i->next;
            i->next->prev = i->prev;
            break;
        }
    }
}

Note that this still has a bug just like the original.  What happens if i->prev or i->next are null pointers?  You should handle those cases.

A similar simplification could be done for the other remove functions.

Don't leak memory

Your program uses new but not delete which is a surefire recipe for memory leaks.

Be explicit about whether your container owns contained objects

It's not clear (because there are not comments) whether the contained Node objects should be destroyed or not when either of the two remove functions is called.

Define a destructor

Because you have a constructor, you really should define a destructor as well.  See the note above about leaking memory.

Consider using an anchor node

Much of the special-case checking for null pointers in your code would disappear if you defined an anchor or head node in the constructor.  In that case, there would always be one node and you wouldn't have to check for null pointers quite as often.


Implementing console.table in JavaScript I just wrote this simple function in order to implement something like console.table:

function toTable(obj) {
    let arr = '';
    arr += '--------------------------\r\n';
    for (let [key, value] of Object.entries(obj[0])) {
        arr += ' ' + key + '\t';
    }
    for (let i = 0; i < obj.length; i++) {
        arr += '\r\n--------------------------\r\n';
        for (let [key, value] of Object.entries(obj[i])) {
            arr += ' ' + value + '\t\t';
        }

    }
    arr += '\r\n--------------------------';
    return arr;
}

An example with an array of objects:

let arr = [
    { firstName: 'Sirwan', lastName: 'Afifi', age: 27 },
    { firstName: 'Person2', lastName: 'P2', age: 32 }
];

It gives you following result:

--------------------------
 firstName   lastName    age
--------------------------
 Sirwan      Afifi       27
--------------------------
 Person2     P2          32
--------------------------

Any suggestions?

Here are some things that can be improved

Naming:

toTable is expressive but also confusing. It looks like it is converting something to table. When used in conjunction with HTML this could be confused with <table>. Adding comments to the function can be helpful to understand what the function is doing. But again, if comments are needed that means you're not naming variables correctly.
obj the short of object is descriptive when used for naming object. However, for this function it is wrong as the function is expecting an array. arr or array would be better.
arr Again, the variable is used to store a string. str can be used or some developers even use str as prefix e.g. strTable, strLine.

Repetitive Code:

'--------------------------\r\n' is used three times in the code. You can create a variable to store this string value and use it anywhere to add the line of hyphens.

for loops:

for loops is used three times in the code. Nested loops should be avoided. There are very few cases when nested loops are required. Always try to avoid nested loops wherever possible.

In the first loop, the keys of the object are joined using tab character.

for (let [key, value] of Object.entries(obj[0])) {
    arr += ' ' + key + '\t';
}

This can be done using Object.keys() which returns an array of keys. Then Array#join can be used on keys array to join the array elements by glue-\t in this case.

So, the new code will be

Object.keys(arr[0]).join('\t') // That's it!

The other nested loop will be slow if object is having large number of properties.

for (let i = 0; i < obj.length; i++) {
    arr += '\r\n--------------------------\r\n';
    for (let [key, value] of Object.entries(obj[i])) {
        arr += ' ' + value + '\t\t';
    }
}

Looking at it carefully shows that this only create a string of values separated by tab. Object.values can be used for this. But again, as the objects are inside array, it need to be iterated over and then values can be extracted from object. New code using this function will look like

arr.forEach(function(obj) {
    someVar += line + Object.values(obj).join('\t\t'); // Sweet!
});

Apart from these, below are some suggestions:

Using console.table consistently: If console.table is supported by target environment then why not use the beautiful function? Although, this function(toTable() from question) is not complete as it doesn't support printing object in table, object containing different keys, nested object, etc. For the basic implementation, it can override default method.

if (!console.table) {
    // Use fallback only when not available
    console.table = function(arr) {
        // Code here
    };
}

Creating the horizontal line dynamically.

The horizontal line is static. In case when the object contain less/more properties, it'll not fit correctly. To create the line dynamically again, Object.keys() can be used.

'-'.repeat(8 * keys.length) // Assuming a tab(\t) is eight characters long

Using monospace font to log data

For non-monospace fonts not all characters occupy same space. For example, i takes less space than O. console.log can be set with custom font using the second parameter which is CSS styles.

console.log('%c' + someString, 'font-family: monospace');

Here's code with these changes

if (!console.table) {
    console.table = function(arr) {
        'use strict';

        let keys = Object.keys(arr[0]);
        const horizontalLine = '\r\n' + '-'.repeat(8 * keys.length) + '\r\n';
        let heading = Object.keys(arr[0]).join('\t');

        let str = horizontalLine;
        str += heading;

        arr.forEach(function(obj) {
            str += horizontalLine + Object.values(obj).join('\t\t');
        });
        str += horizontalLine;
        console.log('%c' + str, 'font-family: monospace');
    };
}

let arr = [
    { firstName: 'Sirwan', lastName: 'Afifi', age: 27 },
    { firstName: 'Person2', lastName: 'P2', age: 32 }
];
console.table(arr);

Here's fiddle to try out it.

And here's output of the above code

------------------------
firstName   lastName    age
------------------------
Sirwan      Afifi       27
------------------------
Person2     P2      32
------------------------

Note:

As some of the features are only available in latest browsers/nodeJS version and some are experimental, see the MDN link embedded for browser support and polyfill.
This, by any means is not polyfill for console.table. This is just another version of the OP's code. console.table is overriden with assumptions that only the provided input format is used to log in table.
The horizontal lines are not perfect. They can contain less/more depending on the min and max length of key in the object.


List all the git branches I have written a toy script to list all the git branches in cwd. I am interested in knowing how can I make this code more modular and flexible.
For example I would like to have features like:

List only local branches.
List only remote branches.
Etc.

const os = require('os');
const cp = require('child_process');

const REGEX_STAR = /^\*\s*/g;

const promiseExec = (cmd) =>
  new Promise((resolve, reject) => {
    cp.exec(cmd, (err, stdout, stderr) => {
      if (err) {
        return reject(err);
      }
      resolve(lines(`${stdout}`));
    });
  });

const lines = (str) =>
  str.trim().split(os.EOL).map((line) =>
    line.trim().replace(REGEX_STAR, '')
  );

const branches = () =>
  promiseExec('git branch -a')
    .then((res) => {
      console.log(res);
    });

branches();

Just return the data and leave it to the consumer what to do with it. That way, branches becomes a generic data grabber. If you want to have printer functions, keep them separate from the raw command.

Your Promise wrapper appears to expect the output of the branches command. Move the use of lines to the branches function instead.

Also, arrow functions with single arguments can omit the parens.

const promiseExec = (cmd) => new Promise((resolve, reject) => {
  cp.exec(cmd, (err, stdout, stderr) => {
    if (err) reject(err);
    else resolve(stdout);
  });
});

const branchLines = (str) => str.trim().split(os.EOL).map(line => line.trim().replace(REGEX_STAR, ''));

const branches = () => promiseExec('git branch -a').then(res => branchLines(res));

const printBranches = () => branches().then(res => console.log(res));

// Print manually
branches().then(res => console.log(res));

// or have a printer function do it
printbranches();


Web Service implementation on the client I will be creating a web service as part of a group project for university, which will be developed using Java within the Eclipse IDE.

Having no prior experience using web services, I managed to find some tutorials that were useful, but struggled to find enough database code examples which suited my needs (though, perhaps I was looking in the wrong places).

My team member has failed to produce even the slightest example of a web service client, so I have taken it upon myself to develop both the web service and client.

I would like to know whether or not my web service example method is suitable for client-side implementation: i.e - Do I have to change the method in order for the client to execute the method or is it acceptable as is?

(I have been creating basic web services using the axis2 framework and running them on the Apache Tomcat server. However, I am open to any suggestions or recommendations in regards to alternative servers and frameworks.)

/**
* Adds a new product to the database
*
* @param name -- name of the game product (e.g - call of duty, grand theft auto)
* @param genre -- genre of the game product (e.g - action, adventure)
* @param platform -- platform of the game product (e.g - playstation 4, xbox one)
* @param developer -- developer of the game product (e.g - sledgehammer games, rockstar north)
* @param publisher -- publisher of the game product (e.g - activision, rockstar games)
* @param ageRating -- age rating of the game product (based on the PEGI rating system)
* @param price -- price of the game product in pounds (£)
* @param quantity -- quantity of the game products
* @param description -- brief description of the game product
*/
public void addProduct(String name, String genre, String platform, String developer, String publisher,
int ageRating, double price, int quantity, String description)
{
try
{
// 1. Connects to the database
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/Products", "root", "root");

// 2. Executes SQL query
String SqlString = "INSERT INTO Games(Game_Name, Genre, Platform, Developer, Publisher, Age_Rating, Price, Quantity, Description) VALUES(?,?,?,?,?,?,?,?,?)";

PreparedStatement prepStatement = connection.prepareStatement(SqlString);
prepStatement.setString(1, name);
prepStatement.setString(2, genre);
prepStatement.setString(3, platform);
prepStatement.setString(4, developer);
prepStatement.setString(5, publisher);
prepStatement.setInt(6, ageRating);
prepStatement.setDouble(7, price);
prepStatement.setInt(8, quantity);
prepStatement.setString(9, description);

// 3. Updates the database using the SQL query
prepStatement.executeUpdate();

// 4. Closes database connection
connection.close();
}
catch(Exception e)
{
System.out.println("Problems were encountered when trying to insert new records to the database. (Ref. to SQL statements)");
}
}
}

Looked briefly into your program, here are few points:

  I would like to know whether or not my web service example method is
  suitable for client-side implementation

Web Client implementation doesn't need the actual implementation, if the service is hit able, it's client can surely be written.

addProduct(String name, String genre, String platform, String developer, String publisher,
int ageRating, double price, int quantity, String description)

Why not create a Product bean and pass it instead of so many params?

  (I have been creating basic web services using the axis2 framework and
  running them on the Apache Tomcat server. However, I am open to any
  suggestions or recommendations in regards to alternative servers and
  frameworks.)

This seems fine but from the learning perspective, give Jersey a try.