FutureTask in Android, wait for a thread to execute the next one This code is executed on a background service every 60 seconds on an Android app. Each class instantiated on FutureTask (WifiInfoFetch and WifiApResults) contains an insert to an SQLite database. We changed the original implementation (without a FutureTask) as we think the first insert was still locking the database when the second one tried to do its insert as they were executed very close to each other.

I think that with the code below, the second thread should wait until the first one is finished to start. Is this true? Also, what happens if for any reason thread 1 does not finish? Is there a way to set a timeout to interrupt it?

WifiInfo wifi = wifiManager.getConnectionInfo();
if (wifi == null) return;

WifiInfoFetch wifiInfo = new WifiInfoFetch(getApplicationContext(), wifi);
WifiApResults scanResults = new WifiApResults(getApplicationContext(), wifiManager.getScanResults());

FutureTask<String> futureWifiInfo = new FutureTask<>(wifiInfo);
FutureTask<String> futureScanResults = new FutureTask<>(scanResults);

ExecutorService executor = Executors.newFixedThreadPool(2);
try {
    executor.submit(futureWifiInfo).get();
    executor.submit(futureScanResults);
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

Thanks!

There is no need for the FutureTask, the executor service will create a future that you can use to wait on the task and get the result (if any).

executor.submit(futureWifiInfo).get();

This is basically the same as just calling futureWifiInfo.run(); (or call) In other words you aren't quite there yet with making this properly asynchronous.

It does let you set a timeout on the get simply by adding the timeout parameters:

Future<String> futureWifiInfo = executor.submit(wifiInfo);
try {
    futureWifiInfo.get(1, TimeUnit.SECONDS);
    executor.submit(scanResults);

} catch (TimeoutException e) {
    // get timed out -> cancel it
    futureWifiInfo.cancel(true);

} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}


Parametrization of a curve For a set of 2D or 3D points \$\{\mathbf P_0, \mathbf P_1,\cdots,\mathbf P_n\}\$, their parameters \$\mathbf T = \{t_0,t_1,\cdots,t_n \}\$ could be computed as follow:

$$\begin{align}
t_0&=0\\
t_i&=\frac{\sum_{j=1}^{i}||\mathbf P_j- \mathbf P_{j-1}||}{\sum_{j=1}^{n}||\mathbf P_j-\mathbf P_{j-1}||} \qquad i=1,2,\cdots,n
\end{align}$$

Here is my C implementation:

/********************************************************************
         v1 = {v1(0),v1(1),...,v1(c-1)}
         v2 = {v2(0),v2(1),...,v2(c-1)}
     compute the 2-norm of the difference of two vector v1 and v2
*********************************************************************/
double vector_norm(double *v1, double *v2, int c) {
    int i;
    double res = 0.0;
    for (i = 0; i < c; i++) {
        res += pow(v1[i] - v2[i], 2);
    }
    return sqrt(res);
}

/********************************************************
 In general, P is a matrix of dimensions {n + 1, c}
 here, it was saved as a vector
********************************************************/
void calc_paras(double *P, int n, int c, double *paras) {
    int i;
    double len = 0.0;
    double chord;
    //compute the length and total length
    paras[0] = 0.0;
    for (i = 0; i < n; i++) {
        chord = vector_norm(P + (i + 1) * c, P + i * c, c);
        len += chord;
        paras[i+1] = len;
    }
    //normalize the paras to [0,1]
    for (i = 0; i <= n; i++) {
        paras[i] /= len;
    }
}

Is a more efficient C implemetation of calc_paras() possible?

That is basically the same technique that I would use.

My only suggestion is to consistently use

for (i = 1; i <= n; i++)

for both loops, to match the stated definition.


Checking whether customers in a dataframe have social media accounts I am using an API to check if customers have social media profiles.

Depending on whether they have phone or email or both there's a different search type.

There's a lot of conditions in this function, and the real dataframe has about 50 columns. So I'm just wondering if this is the most efficient way to go about it.

I'm aware that I'm applying this on a full row when I only need to work with a few in the df.

So I have two fake customer records here, and I'm trying to fill the social media columns with info returned from an API call:

import pandas as pd

df = pd.DataFrame(columns=['name','phone','email','facebook','foursquare','instagram','linkedin','skype','twitter'],index=range(0,2))

df['email'] = ['jim@email.com',pd.np.nan]
df['name'] = ['Jim Bob','Joe Bloggs']
df['phone'] = [pd.np.nan,'35543256']

print(df)

         name     phone          email facebook foursquare instagram linkedin  \
0     Jim Bob       NaN  jim@email.com      NaN        NaN       NaN      NaN
1  Joe Bloggs  35543256            NaN      NaN        NaN       NaN      NaN

  skype twitter
0   NaN     NaN
1   NaN     NaN

Depending on the presence of phone/email, the function goes as follows (I believe I've commented my logic acceptably .. if something isn't clear please let me know)

# the columns from the df we want to fill
mycols = ['facebook','foursquare','instagram','linkedin','skype','twitter']

def checksocial(row):

    # if both phone and email are null
    if pd.isnull(row['phone']) and pd.isnull(row['email']):

        # do nothing
        # (analyzing and returning a whole row here, is this efficient?)
        return row

    # if there is no phone number but email is present
    elif pd.isnull(row['phone']) and pd.notnull(row['email']):

        # use phone to search for social media
        # fake API response
        returned_results = ['facebook','foursquare','instagram']

        for socialmedia in returned_results:

            # if it's one of the social media profiles we are looking for
            if socialmedia in mycols:

                # add result to DF under same social media column
                row[socialmedia] = 'Found Social Media'
        # return updated row
        return row

    # if there is a phone number and email is empty
    elif pd.notnull(row['phone']) and pd.isnull(row['email']):

        # use phone to search for social media
        # fake API response
        returned_results = ['facebook','linkedin','twitter']

        for socialmedia in returned_results:

            # if it's one of the social media profiles we are looking for
            if socialmedia in mycols:

                # add result to DF under same social media column
                row[socialmedia] = 'Found Social Media'

        # return updated row
        return row

    # repeat the same for when both email and phone are present

Applying the function:

df = df.apply(checksocial,axis=1)

print(df)

        name     phone          email            facebook  \
0     Jim Bob       NaN  jim@email.com  Found Social Media
1  Joe Bloggs  35543256            NaN  Found Social Media

           foursquare           instagram            linkedin  skype  \
0  Found Social Media  Found Social Media                 NaN    NaN
1                 NaN                 NaN  Found Social Media    NaN

              twitter
0                 NaN
1  Found Social Media

It works fine, but the reason I'm asking for advice here is that the actual code I have is starting to become way too long. (There's parsing a json response that I didn't add here) and there are like 100,000 rows.

I have a lot of if statements, and I'm working with a full row and returning it.

Any advice on how to make this more cleaner/efficient?

Few things to note here:

Columns:

email_results=['facebook','foursquare','instagram']
phone_results=['facebook','linkedin','twitter']

Conditions:

c1=df.phone.isna()&df.email.notna()
c2=df.phone.notna()&df.email.isna()

Method1

You can try and replace if else conditions with np.where , also take a look at np.select() if you have elif conditions:

df[email_results]=np.where(c1[:,None],'Found Social Media',df[email_results])
df[phone_results]=np.where(c2[:,None],'Found Social Media',df[phone_results])
print(df)

Method2

Or you can take a look at df.mask():

df[email_results]=df[email_results].mask(c1,'Found Social Media')
df[phone_results]=df[phone_results].mask(c2,'Found Social Media')
print(df)


Alternative to using sleep() to avoid a race condition in PyQt I have a situation where I would like to use a single QThread to run two (or more) separate methods at different times. For example, I would like the QThreadto run play() sometimes, and when I am done playing, I want to disconnect the QThread.started() signal from this method so that I may connect it somewhere else. In essence I would like the QThread to act as a container for anything I would like to run in parallel with the main process.

I have run into the problem where starting the QThread and then immediately disconnecting the started() signal it causes strange behavior at runtime. Before I discovered what 'race condition' meant (or really understanding much about multithreading), I had the sneaking suspicion that the thread wasn't fully started before being disconnected. To overcome this, I added a 5 ms sleep in between the start() and disconnect() calls and it works like a charm. It works like a charm but it isn't The Right Way.

How can I implement this functionality with one QThread without making the call to sleep()?

def play(self):

    self.stateLabel.setText("Status: Playback initated ...")

    self.myThread.started.connect(self.mouseRecorder.play)
    self.myThread.start()
    time.sleep(.005)  #This is the line I'd like to eliminate

    self.myThread.started.disconnect()

def record(self):

    self.stateLabel.setText("Status: Recording ...")

    self.myThread.started.connect(self.mouseRecorder.record)
    self.myThread.start()
    time.sleep(.005) #This is the line I'd like to eliminate

    self.myThread.started.disconnect()

Use a Queue, python has a threadsafe Queue class.

Push the function you want to run on the background thread onto the queue.

Have the thread wait on the queue executing functions as they are put into it.


Efficiency of calling other classes After much trial and error, I finally came up with this code to call on other classes to perform their function.  This code works and does what I want it to do, so I am looking for some comments on the code efficiency.

What I want to happen is have the user input which calculator they would like to use and have that calculator come up presenting its own variables and calculations.  The code for the calculators works just fine, so I don't need help with that.  Just the efficiency of my calling from other classes.

My first iteration of this was to have the other calculators inside methods within the class.  When I tried to call them up, it was nothing but problems, but this way seems to work. (I only mention this because my last question got knocked out because the code didn't work, so I found a way that worked, albeit not how I intended.)

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter 1 for Quadratic Calculator");
    System.out.println("Enter 2 for Compound Interest Calculator");
    int ans = sc.nextInt();

    if (ans == 1) {
        Quadratic.CalcQuad();
    } else if (ans == 2){
        CompInt.CalcInt();
    } else {
        System.out.println("That was not an option.");
    }

    sc.close();
}

Simplify multiple conditions using a switch

Whenever multiple conditions depend only on the value of a single variable,
consider using a switch instead to simplify:

switch (ans) {
    case 1:
        Quadratic.CalcQuad();
        break;
    case 2:
        CompInt.CalcInt();
        break;
    default:
        System.out.println("That was not an option.");
}

Naming

The common convention is to use camelCase for function names.
The method names CalcQuad and CalcInt violate that.

It also seems that the class names could be better.
If you spell out their purpose, the names won't be much longer but a lot more intuitive and unambiguous, for example:

Quadratic -> QuadraticCalculator
CompInt -> CompoundInterestCalculator

And then the methods that do the calculation can be simply calculate in both classes, without including the type of calculation, which is already included in the class name.

Alternatively, you could use a single Calculator class with calculateQuadratic and calculateCompoundInterest methods.


Storing transactions with amounts and payment types I have a table where I'm storing a row for each transaction that records the type of transaction along with the amount of money being recorded for the transaction type. I then need to write a report to sum the amounts of various types.

At the moment I'm doing this with a series of CTE's, but I'm sure there's a better way:

;with cte_foodCard as (
    select  isnull(sum(cast(o.FinancialContribution as money)), 0) as 'FoodCardContributions'
    from    dbo.CriticalAssistanceInternalOutcomes as o
    where   upper(o.PaymentType) = 'FOOD CARD'
), cte_fuelCard as
(
    select  isnull(sum(cast(o.FinancialContribution as money)), 0) as 'FuelCardContributions'
    from    dbo.CriticalAssistanceInternalOutcomes as o
    where   upper(o.PaymentType) = 'FUEL CARD'
), cte_gocard as
(
    select  isnull(sum(cast(o.FinancialContribution as money)), 0) as 'GoCardContributions'
    from    dbo.CriticalAssistanceInternalOutcomes as o
    where   upper(o.PaymentType) in ( 'GO CARD' , 'GOCARD')
), cte_invoicePayment as
(
    select  isnull(sum(cast(o.FinancialContribution as money)), 0) as 'InvoicePaymentContributions'
    from    dbo.CriticalAssistanceInternalOutcomes as o
    where   upper(o.PaymentType) = 'INVOICE PAYMENT'
)
select *
from cte_foodCard , cte_fuelCard, cte_gocard, cte_invoicePayment

For more context, a sampling of the data from development (needs better rules and cleanup) looks like:

select  o.Id ,
        o.FinancialContribution ,
        o.PaymentType
from dbo.CriticalAssistanceInternalOutcomes as o

When you use the same base query with different WHERE-conditons you can usually rewrite it using Conditional Aggregation with CASE (aka pivoting):

select -- you can easily add a GROUP BY column here
   sum(cast(case when upper(o.PaymentType) = 'FOOD CARD'
            then o.FinancialContribution end else 0 as decimal(18,4))) as FoodCardContributions
  ,sum(cast(case when upper(o.PaymentType) = 'FUEL CARD'
            then o.FinancialContribution end else 0 as decimal(18,4))) as FuelCardContributions
  ,sum(cast(case when upper(o.PaymentType) in ('GO CARD' , 'GOCARD')
            then o.FinancialContribution end else 0 as decimal(18,4))) as GoCardContributions
  ,sum(cast(case when upper(o.PaymentType) = 'INVOICE PAYMENT'
            then o.FinancialContribution end else 0 as decimal(18,4))) as InvoicePaymentContributions
from dbo.CriticalAssistanceInternalOutcomes as o
where
   upper(o.paymentType)
     in ('GO CARD', 'GOCARD', 'FOOD CARD', 'FUEL CARD', 'INVOICE PAYMENT')

I changed the deprecated MONEY to a better DECIMAL.

Btw, who created that table? Storing numeric values in a VarChar column is very bad practice...


Some kind of encryption in C++ It's my university task. Can I get some opinions on it?

#include <iostream>
#include <vector>

using namespace std;

string toBinary(short n) {
   string r;
   while(n != 0) {
      r = ( n % 2 == 0 ? "0" : "1" ) + r;
      n /= 2;
   }
   return r;
}

int has_even_parity(int c) {
   int k = 0;
   if (c != 0)
      k++;
if ((c & 0x2) >> 1 == 1)
    k++;
if ((c & 0x4) >> 2 == 1)
    k++;
if ((c & 0x8) >> 3 == 1)
    k++;
if ((c & 0x10) >> 4 == 1)
    k++;
if ((c & 0x20) >> 5 == 1)
    k++;
if ((c & 0x40) >> 6 == 1)
    k++;
if ((c & 0x80) >> 7 == 1)
    k++;
 return k % 2;
}

char decode(short int a) {
  char result;
  unsigned short int mask = 0b0111111110000000;
  return (char)((a & mask) >> 7);
}

int main() {
short int result[64];
string str;
vector<string> text_list;

for (int i = 0; i < 8; i++) {
    getline(cin, str);
    text_list.push_back(str);
}
cout << endl;
int k = 0;

for (int i = 0; i < text_list.size(); i++) {
    string l = "";
    for (int j = 0; j < text_list[i].size(); j++) {
        short int c_ = text_list[i][j];
        short int l_ = 0b0000000;
        c_ = l_ | c_;
        result[k] = (short) has_even_parity(c_);
        result[k] = result[k] << 8;
        result[k] = result[k] | c_;
        result[k] = result[k] << 1;
        c_ = (short) (has_even_parity(i) ^ has_even_parity(j));

        result[k] = result[k] | c_;
        result[k] = result[k] << 3;
        result[k] = (short) (result[k] | i);

        result[k] = result[k] << 3;
        result[k] = (short) (result[k] | j);

        l += decode(result[k]);
        k++;
    }
    cout << l << endl;
}

return 0;
}

I have input as text 8 letters x 8 lines, 2 bytes for one letter.

In bit 0-2 number of line
In bit 3-5 number of position in line
In bit 6 parity bit of 1) and 2)
In bit 7-14 ASCII code of letter
In bit 15 parity bit of 4)

And after, decode letter.

using namespace std; is a bad habit. It's not that tedious to write std:: a few times and you get less name collisions on things you define.

Your indentation is inconsistent. This makes it difficult to follow the control flow.

The even parity can be discovered with repeated xors:

int has_even_parity(int c) {
   c ^= c >> 4;
   c ^= c >> 2;
   c ^= c >> 1;
   return ! (c&1);
}

short int l_ = 0b0000000;
c_ = l_ | c_;

This doesn't do anything.

I suggest adding some underscores in the binary literals to group the digits:

unsigned short int mask = 0b0111_1111_1000_0000;

This makes it easier to tell at a glance that there are 7 zeros at the end and that you meant for them to be there. Though once you are more comfortable with hexadecimal then 0x7f80 is just as clear.


Insertion Sort Implemented in Ruby I'm a new programmer and I'm periodically going into the Intro To Algorithms CLRS textbook and trying to translate pseudocode into Ruby for skill practice. This is my implementation/translation of insertion sort.
I'm looking for feedback on readability as well as efficiency.
Pseudocode is found on page 17 of Intro To Algorithms Second Edition just in case you happen to have it lying around, more interested in the feedback just on the code itself.
class InsertionSort
    attr_accessor :arr
    def initialize(arr)
      @arr = arr
    end

    def sort
      key = 1
      to_the_left = key - 1

      while key < self.arr.length
        if arr[key] < arr[to_the_left]

          mover_key = key
          left_ele_moving_right = to_the_left

          until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right < 0

            arr[left_ele_moving_right], arr[mover_key] =
            arr[mover_key], arr[left_ele_moving_right]

              mover_key -= 1
              left_ele_moving_right -= 1
          end
        end

        key += 1
        to_the_left += 1
      end

      self.arr
    end
end

```

Consistency
Sometimes you are using 4 spaces for indentation, sometimes 2. Sometimes you are using vertical whitespace (an empty line) before a method definition, sometimes you don't. Sometimes you have whitespace at the end of a line, sometimes you don't. In one case, you indent a couple of lines just for no discernible reason.
You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.
Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).
In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing IFF you actually want to convey some extra information.
For example, some people always use parentheses for defining and calling purely functional side-effect free methods, and never use parentheses for defining and calling impure methods. That is a good reason to use two different styles (parentheses and no parentheses) for doing the same thing (defining methods).
Indentation
The community standard for indentation is 2 spaces. For example, your first two lines should look like this:
class InsertionSort
  attr_accessor :arr

Instead of this:
class InsertionSort
    attr_accessor :arr

Furthermore, you should only indent in places where there is a logically nested structure, e.g. a method definition inside a class definition, the body of the method definition, the body of a block, etc. An exception is a continuation of the previous line, this should also be indented.
Here, you are indenting for no apparent reason:
arr[left_ele_moving_right], arr[mover_key] =
arr[mover_key], arr[left_ele_moving_right]

  mover_key -= 1
  left_ele_moving_right -= 1

On the other hand, in the same place, you should indent this:
arr[left_ele_moving_right], arr[mover_key] =
  arr[mover_key], arr[left_ele_moving_right]

To make it clear that the second line is a continuation of the first.
No whitespace at the end of the line
There should be no whitespace at the end of the line. For example, this line:
if arr[key] < arr[to_the_left]

Has a space at the end. That shouldn't be there. And there are two more lines like this.
Also, there are multiple "empty" lines that actually contain only spaces. Again, those shouldn't be there.
No empty line at the end of the file
Your file should end with a single newline. There should not be an extra empty line at the end of the file.
Vertical whitespace
There should be a blank line after every "logical" break. In particular, there should be a blank line after the attr_accessor:
attr_accessor :arr

def initialize(arr)

On the other hand, there should be no empty line directly after the if and the until.
Otherwise, your use of vertical whitespace looks good! Logical steps in the method are clearly separated by empty lines, the code looks "light", not all bunched together with "room to breathe". I like it, well done!
self is the implicit receiver
In Ruby, if you don't explicitly specify the receiver of a message send, the receiver is self. In idiomatic code, you should never explicitly specify the receiver self, unless it is absolutely necessary.
Right now, I can only think of cases, where it would be necessary:

To use an attribute writer method: self.foo = bar.
To use an operator: self + foo

So, this:
self.arr

should just be:
arr

Same here:
while key < self.arr.length

should be
while key < arr.length

Prefer predicate methods over relational operators
You should prefer "speaking" predicate methods such as Numeric#negative? over relational operators such as < 0.
So, this:
left_ele_moving_right < 0

should be
left_ele_moving_right.negative?

Code Formatting
If possible, you should set your editor or IDE to automatically format your code when you type, when you paste, and when you save, and set up your version control system to automatically format your commit when you push, as well as set up your CI system to reject code that is not correctly formatted. If not possible, you should seriously consider using a different editor or IDE, version control system, or CI system.
Here's the result of your code, when I simply paste it into my editor, without doing anything else:
class InsertionSort
  attr_accessor :arr

  def initialize(arr)
    @arr = arr
  end

  def sort
    key = 1
    to_the_left = key - 1

    while key < arr.length
      if arr[key] < arr[to_the_left]

        mover_key = key
        left_ele_moving_right = to_the_left

        until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right < 0

          arr[left_ele_moving_right], arr[mover_key] =
            arr[mover_key], arr[left_ele_moving_right]

          mover_key -= 1
          left_ele_moving_right -= 1
        end
      end

      key += 1
      to_the_left += 1
    end

    arr
  end
end

As you can see, simply copying your code into my editor, the editor corrected every single thing I wrote above except one.
Linting
You should run some sort of linter or static analyzer on your code. Rubocop is a popular one, but there are others.
Rubocop was able to detect all of the style violations I pointed out above (plus some more), and also was able to autocorrect all of the ones I listed.
Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can actually correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit "save".
In particular, running Rubocop on your code, it detects 26 offenses, of which it can automatically correct 23.
Here's what the result of the auto-fix looks like:
class InsertionSort
  attr_accessor :arr

  def initialize(arr)
    @arr = arr
  end

  def sort
    key = 1
    to_the_left = key - 1

    while key < arr.length
      if arr[key] < arr[to_the_left]

        mover_key = key
        left_ele_moving_right = to_the_left

        until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right.negative?

          arr[left_ele_moving_right], arr[mover_key] =
            arr[mover_key], arr[left_ele_moving_right]

          mover_key -= 1
          left_ele_moving_right -= 1
        end
      end

      key += 1
      to_the_left += 1
    end

    arr
  end
end

And here are the offenses that Rubocop could not automatically correct:
Inspecting 1 file
C

Offenses:

insertion_sort.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.
class InsertionSort
^^^^^
insertion_sort.rb:8:3: C: Metrics/AbcSize: Assignment Branch Condition size for sort is too high. [<10, 21, 7> 24.29/17]
  def sort ...
  ^^^^^^^^
insertion_sort.rb:8:3: C: Metrics/MethodLength: Method has too many lines. [17/10]
  def sort ...
  ^^^^^^^^

1 file inspected, 3 offenses detected

Similar to Code Formatting, it is a good idea to set up your tools such that the linter is automatically run when you paste code, edit code, save code, commit code, or build your project, and that passing the linter is a criterium for your CI pipeline.
attr_reader vs. attr_accessor
You are never writing to arr, so it should probably be a Module#attr_reader instead of a Module#attr_accessor:
attr_reader :arr

Access Restrictions
arr is not intended to be used by other objects. In fact, it shouldn't be used by other objects! It is private internal state of the sorter object. Therefore, it should not be part of the public API, it should be private:
private attr_reader :arr

Iterators
In Ruby, you almost never use loops. You would normally use at least an low-level iterator such as Kernel#loop, [#each], or Integer#. Really, you want to use higher-level iterators such as Enumerable#map, Enumerable#select, Enumerable#group_by, Enumerable#flat_map, Enumerable#inject, etc.
In this case, we are going to use Integer#times for the outer loop.
def sort
  arr.length.times do |key|
    to_the_left = key - 1

    if arr[key] < arr[to_the_left]
      mover_key = key
      left_ele_moving_right = to_the_left

      until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right.negative?
        arr[left_ele_moving_right], arr[mover_key] =
          arr[mover_key], arr[left_ele_moving_right]

        mover_key -= 1
        left_ele_moving_right -= 1
      end
    end
  end

  arr
end

Guard clauses
If you have a case where an entire method or block is wrapped in a conditional, you can replace that with a "guard clause" and reduce the level of nesting.
E.g. this:
def something
  if foo
    bar
    baz
    quux
  else
    42
  end
end

can become this:
def something
  return 42 unless foo

  bar
  baz
  quux
end

After the above change, there is now an opportunity to do that in your code:
def sort
  arr.length.times do |key|
    to_the_left = key - 1

    next unless arr[key] < arr[to_the_left]

    mover_key = key
    left_ele_moving_right = to_the_left

    until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right.negative?
      arr[left_ele_moving_right], arr[mover_key] =
        arr[mover_key], arr[left_ele_moving_right]

      mover_key -= 1
      left_ele_moving_right -= 1
    end
  end

  arr
end

Objects
I don't see a particular reason why insertion sort should be an object. It doesn't have any state (having the array to be sorted, as you do, as state is somewhat weird), and it only has a simple single behavior. It would make more sense for a sorting algorithm to be an object if it carries some complex state that persists between different runs of the algorithm.
In a language which supports procedures or functions, this should probably be a function.
In Ruby, I would make it maybe a singleton method of a module, or an instance method of Array. However, I would not name it sort because that method already exists. I would also not name it insertion_sort because that is an implementation detail. I think stable_sort would be a good name, because the fact that insertion sort is stable (if implemented correctly) is an important distinguishing feature that sets it apart from the default sort in Ruby, which is not stable.
So, either something like this:
module Sort
  module_function def stable_sort(arr)
    # …
  end
end

or something like this:
class Array
  def stable_sort
    length.times do |key|
      # …
    end
  end
end

Actually, I am not a big fan of monkey-patching core classes. At least put the method in a separate mixin, so that it is easier to trace where the code is coming from:
module StableSortExtension
  def stable_sort
    length.times do |key|
      # …
    end
  end
end

class Array
  include StableSortExtension
end

But even better would be to make it a Refinement:
module StableSort
  module StableSortExtension
    def stable_sort
      length.times do |key|
        to_the_left = key - 1

        next unless self[key] < self[to_the_left]

        mover_key = key
        left_ele_moving_right = to_the_left

        while self[mover_key] <= self[left_ele_moving_right] && left_ele_moving_right >= 0

          self[left_ele_moving_right], self[mover_key] =
            self[mover_key], self[left_ele_moving_right]

          mover_key -= 1
          left_ele_moving_right -= 1
        end
      end
    end
  end

  refine Array do
    include StableSortExtension
  end
end

Now, the Array#stable_sort method will only exist for code which explicitly activates the Refinement with
using StableSort

Observe:
ary = [5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10]

ary.stable_sort
# undefined method `stable_sort' for [5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10]:Array (NoMethodError)

using StableSort

ary.stable_sort

p ary
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

However, I would not do it this way. This stable_sort method mutates its receiver, which is generally not the case for other sort methods in Ruby, and thus very surprising to people.
So, the method should at least dup the receiver and perform its mutations on that duplicate, then return it.
Which brings me to my next point:
Mutation
Your method mutates its argument. That is an absolute no-go. You should never-ever break someone else's toy. An argument that is handed to you, is sacred.
You can fix this by simply adding something like arr = arr.dup at the beginning of the method (or arr = dup for the case where you want to make it an instance method). But I believe we can improve the code more generally.
More generally, your code looks more like FORTRAN, Pascal, or C, with lots of mutation, looping, manual fiddling with indices.
Insertion sort can actually be expressed very elegantly without mutation and without looping, which will not only simplify the code, but also get rid of the mutation problem.
Something like this:
module Enumerable
  protected def ins(element)
    return [element] if count.zero?

    head = first
    return [element] + self if element <= head

    [head] + drop(1).ins(element)
  end

  def stable_sort
    return [] if count.zero?

    drop(1).stable_sort.ins(first)
  end
end

This version does not mutate anything, and it works with all Enumerables (including Enumerators), not just Arrays. (It does not work with infinite Enumerators, though.)
Frozen string literals
Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:
# frozen_string_literal: true

It is generally preferred to add this comment to all your files.
Note: I put this at the very end, because there actually are no String literals in your code, so it doesn't matter. Rubocop and some other Linters will complain about this regardless. It's your choice whether you want to get into the habit of always adding it, regardless of whether you use String literals in the code or not. Personally, I always add it, just in case I add a String literal later on.


On Implementing a Lisp Background:
This began with James Colgan's Lisp-Dojo for Ruby.  My implementation can be found here. I then moved on to Write yourself a scheme in 48 hours.  This question has to do with one of the implementation decisions.

Code:

My implementation of eval

--# The eval function takes a scope and paresed Lisp value and
--# returns the resulting Lisp Value.
--# String, Number and Bool return themselves.
--# An Atom trys to find its self in the scope and retrun that value
--# A List is evaluated using the normal Lisp rules.
eval :: LispScope-> LispVal -> IOThrowsError LispVal
eval s val@(String _) = return val
eval s (Atom val) =  do
  (liftIO $ getValue s val) >>= maybe (throwError $ "Value not in scope: " ++ val) (return)
eval s val@(Number _) = return val
eval s val@(Bool _) = return val
eval scope (List (fn:lvs)) = do
    fun <- eval scope fn
    case fun of
      Syntax f _-> f scope lvs
      Function f _-> evalMap scope lvs >>= f
      val -> throwError $ (show val) ++ " is not a function"
eval scope (List []) = return $ List []
eval _ badForm = throwError $ "Unrecognized form: " ++ show badForm

Note two things: 1) I do not refer to any special forms, 2) the use of Syntax for hygenic forms.

This is a piece of code from Write yourself a scheme in 48 hours:

--# evaluate the "if" form
eval (List [Atom "if", pred, conseq, alt]) =
    do result <- eval pred
       case result of
         Bool False -> eval alt
         otherwise -> eval conseq

Note that in the tutorial the form is written directly into the eval function.  This pattern is followed for other syntaxes like define and lambda.

Question:
When I implemented my version I followed what I thought was a wise choice demonstrated in James Colgan's solution to the lisp-dojo to keep eval as simple as possible and instead to push the syntax implementations into the root scope.  eg:

ifSyntax :: LispScope -> [LispVal] -> IOThrowsError LispVal
ifSyntax s [pred, consequent, alternate] = do
  pred' <- eval s pred
  case pred' of
    Bool False -> eval s alternate
    otherwise -> eval s consequent
ifSyntax _ _ = throwError "if: Bad Syntax"

ifVal = (Syntax ifSyntax $ Left "syntax (if)")
--# this is then added to the initial scope

I would like to know why one choice might be better then the other, and what is typical in real-world implementations.

Reference:

My definition of the LispVal data type:

type LispScope = Scope LispVal

data Lambda = Lambda {params :: [String], body :: [LispVal]}

data LispVal = Atom String
             | List [LispVal]
             | Number Integer
             | Real Double
             | String String
             | Function ([LispVal] -> IOThrowsError LispVal) (Either String Lambda)
             | Syntax (LispScope -> [LispVal] -> IOThrowsError LispVal) (Either String Lambda)
             | Bool Bool
             | Port Handle

When I went through the WYAS48 I made the same decision of breaking the bits of eval off into smaller functions. I found this made testing easier since I could focus on just one function at a time.

I find that having a function be one massive bunch of logic is not helpful. In an imperative language the equivalent would be a single function with a ton of if/else or case/switch logic. Whenever I see that I tend to break things off into more manageable functions.

The issue that tends to happen is the little functions need some kind of state from the original big function. Finding this out and resolving it can be difficult at times and others just plain messy. The code is often better for it in the end.


GNU Makefile for google benchmark I've decided to write a common Makefile for Google benchmark library. You could say I could have taken generated Makefile, but it's not appropriate solution (or maybe I'm wrong?).

TARGET = libbenchmark.a

CXXFLAGS = -std=c++11 -Wall -Wextra -Wshadow -Werror -pedantic \
            -pedantic-errors -Wfloat-equal \
            -Wzero-as-null-pointer-constant -fstrict-aliasing \
            -DHAVE_STD_REGEX

LDFLAGS = -lpthread

# Define include files and directories
INCLUDES = -I./include -I./src

# Define the source files
SOURCE_FILES = src/colorprint.cc src/benchmark.cc src/commandlineflags.cc \
               src/console_reporter.cc src/csv_reporter.cc src/json_reporter.cc \
               src/log.cc src/reporter.cc src/sleep.cc src/string_util.cc \
               src/sysinfo.cc src/walltime.cc src/re_std.cc

OBJECT_FILES = $(SOURCE_FILES:.cc=.o)

CC = gcc
AR = gcc-ar

all: $(TARGET)

$(TARGET): $(OBJECT_FILES)
    $(AR) rcs $(TARGET) $(OBJECT_FILES)

%.o: %.cc
    $(CC) $(INCLUDES) $(CXXFLAGS) -c -o $@ $<

clean:
    $(RM) src/*.o $(TARGET)

install:
    mkdir -p $(DESTDIR)/usr/lib
    cp -p ./$(TARGET) $(DESTDIR)/usr/lib
    cp -r include $(DESTDIR)/usr

In a clean rule, consider removing $(OBJECT_FILES) instead of src/*.o
I don't see where LDFLAGS is ever used.
I understand that you are not likely to edit include files; however, to be on a safe side you may want to add auto dependency generation:

DEP_FILES = $(SOURCE_FILES:.cc=.d)

%.d: %.cc
    $(CC) $(INCLUDES) $(CXXFLAGS) -MM -MT -o $@ $<

-include $(DEP_FILES)

(and remove $(DEP_FILES) on clean).


MVC router class performance Can you review my code?

class Router {

    /**
     * Store the current URI [0] => Controller/ [1] => Method/ [2]=> parameter
     * @var array
     */
    private $URI = array();

    /**
     * Store an instance of configuration object
     * @var object
     */
    private $config = NULL;

    /**
     *  Store an instance of Application object
     * @var object
     */
    private $app = NULL;

    /**
     * Initialize the router
     */
    public function __construct() {
        $this->startup();
    }

    /**
     *
     * @param object $route
     * @return string
     */
    public function get($route) {
        return $this->config->getRoute($route);
    }

    /**
     * First step, to catch the url and manipulate it.
     */
    private function startup() {

        if ($url = $this->getURL()) {

            $this->app = Application::getAppInstance();
            $this->config = Application::getInstance('Configuration');

            if ($this->validateURL()) {
                $class = (isset($url[1])) ? $url[1] : $this->get('defaultController');
                unset($url[1]);
                $method = (isset($url[2])) ? $url[2] : $this->get('defaultMethod');
                unset($url[2]);
                $params = (count($url > 0)) ? $url : "";
                unset($url);

                if (class_exists($class)) {
                    $controller = $this->app->getInstance($class);
                } else {
                    exit("Class not found");
                }
                if (method_exists($controller, $method)) {
                    if ($params !== "") {
                        call_user_func_array(array($class, $method), $params);
                    } else {
                        $controller->{$method}();
                    }
                } else {
                    exit("Method not found");
                }
            } else {
                exit("URI chars not allowed");
            }
        } else {
            if ($this->get('defaultController') !== "") {
                $this->app->getInstance($this->get('defaultController'));
                call_user_func(array($this->get('defaultController'), $this->get('defaultMethod')));
            } else {
                echo "Default does not added.";
            }
        }
    }

    /**
     * Get the current url and convert into an array
     * @return array
     */
    private function getURL() {
        $currentURL = $_SERVER['QUERY_STRING'];
        if ($currentURL !== "") {
            $currentURL = rtrim($currentURL, '/');
            $currentURL = explode('/', $currentURL);
            unset($currentURL[0]);
            $this->URI = $currentURL;
            return $currentURL;
        }
        return false;
    }

    /**
     * Validate the URI characters
     * @return boolean
     */
    private function validateURL() {
        foreach ($this->URI as $uri) {
            if (!preg_match("/^[" . $this->config->get('allow_uri_chars') . "]+$/i", $uri)) {
                return false;
            }
        }
        return true;
    }

}

$params = (count($url > 0)) ? $url : "";

Is this really what you meant to say?  This looks like it should be

 $params = (count($url) > 0) ? $url : '';

The second version treats the $url variable as an array.  The previous code treats $url as an integer and then treats a Boolean expression as an array.  This is problematic because both count(false) and count(true) return 1.  Meaning that the first version is the same as $params = $url.

This was the only functional comment that I had on the code.  Everything else is just style.  It's possible that if you fleshed out a problem statement describing what the code is supposed to do that someone would have additional functional comments.

            if ($this->validateURL()) {
                $class = (isset($url[1])) ? $url[1] : $this->get('defaultController');
                unset($url[1]);
                $method = (isset($url[2])) ? $url[2] : $this->get('defaultMethod');
                unset($url[2]);
                $params = (count($url > 0)) ? $url : "";
                unset($url);

                if (class_exists($class)) {
                    $controller = $this->app->getInstance($class);
                } else {
                    exit("Class not found");
                }
                if (method_exists($controller, $method)) {
                    if ($params !== "") {
                        call_user_func_array(array($class, $method), $params);
                    } else {
                        $controller->{$method}();
                    }
                } else {
                    exit("Method not found");
                }
            } else {
                exit("URI chars not allowed");
            }

You could reduce your indentation by using early exits instead of if/else.

            if (!$this->validateURL()) {
                exit('URI chars not allowed');
            }

            switch (count($url)) {
                default:
                    $method = (isset($url[2])) ? $url[2] : $this->get('defaultMethod');
                    unset($url[2]);
                    // 3 or more fall through to 2
                case 2:
                    $class = (isset($url[1])) ? $url[1] : $this->get('defaultController');
                    unset($url[1]);
                    // 2 or more fall through to 1
                case 1:
                    $params = $url;
                    break;
                case 0:
                    $params = '';
                    break;
            }
            unset($url);

            if (!class_exists($class)) {
                exit('Class not found');
            }

            $controller = $this->app->getInstance($class);
            if (!method_exists($controller, $method)) {
                exit('Method not found');
            }

            if ('' === $params) {
                $controller->{$method}();
            } else {
                call_user_func_array(array($class, $method), $params);
            }

I also changed the order of the final if/else.  I try to avoid the if not else form.  An else is implicitly taking the logical not of the test expression.  So if the test expression is negative, this means that the else is the negative of a negative.  I often find it more readable if I reorder the clauses such that the test expression is positive.

I prefer to use single quotes if I can.  There's a slight performance benefit, but the chief advantage is that it is easy to see that no variable interpolation will occur.  With double quotes you have to examine the string to tell that.

I don't know that the switch version is better than what you had originally, but I wanted to include it as a possibility.  I find it a little clearer, but it is more code.  On average, it may give a very slight performance advantage.  Probably not enough to matter.


Improve performance for stanford-nlp in a "homemade" search engine I am working on a javaproject for the Information Retrieval subject in my graduation. What I'm trying to do is to reduce the lines of code I have to write due to the lack of time. We're currently on the second checkpoint, where we have to implement the engine collector component. What I'm trying to do is to use the Jsoup lib to crawl the web. That part works at the moment, but now I must parse the fetched HTML documents to retrive entites (people and places) and store the relevant pages on the disk. For that, I'm trying to use Stanford's NLP. What I'm doing to test it on one single page, at the moment is this:

// assuming all needed imports are done

String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) "
        + "AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
String url = "https://www.example.com";
Document htmlDocument = Jsoup.connect(url).userAgent(userAgent).get();
String text = htmlDocument.body();
String model = "english.all.3class.distsim.crf.ser.gz";
AbstractSequenceClassifier<CoreLabel> classifier = CRFClassifier.getClassifier(model);
System.out.println(classifier.classifyToString(text));

This works rather fine, it prints |word in the text/category|, but that execution is very slow (around 6 minutes, more or less). Is there a way to speed that up? Do I have to use other classes rather than CRFClassifier? Is Jsoup the real dragger and not the NLP process?

My internet connection is already a bottleneck to the project. The parser can't become another one, considering that the engine must collect and store thousand of pages.

Most of the time is going in loading the CRFClassifier model. You want to put the model loading outside the page processing:

// assuming all needed imports are done

String model = "english.all.3class.distsim.crf.ser.gz";
AbstractSequenceClassifier<CoreLabel> classifier = CRFClassifier.getClassifier(model);
String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) "
        + "AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
String[] pages = { "https://www.example.com" };

for (String url : pages) {
  Document htmlDocument = Jsoup.connect(url).userAgent(userAgent).get();
  String text = htmlDocument.body();
  System.out.println(classifier.classifyToString(text));
}


Farthest point algorithm in Python I am learning Python and I tried to do a program to find K points from a set of N points, farthest as much as possible (I'm not sure if this is the case).

I'd like to know if my code is not redundant, or if the code can be improved.

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import euclidean

def dist_ponto_cj(ponto,lista):
    return [ euclidean(ponto,lista[j]) for j in range(len(lista)) ]

def ponto_mais_longe(lista_ds):
    ds_max = max(lista_ds)
    idx = lista_ds.index(ds_max)
    return pts[idx]

N = 80
K = 40
farthest_pts = [0]*K
print( 'N = %d, K = %d' % (N, K))

#x=[ np.random.randint(1,N) for p in range(N)]
#y=[ np.random.randint(1,N) for p in range(N)]
x=np.random.random_sample((N,))
y=np.random.random_sample((N,))
pts = [ [x[i],y[i]] for i in range(N)]

P0 = pts[np.random.randint(0,N)]
farthest_pts[0]=P0
ds0 = dist_ponto_cj(P0,pts)

ds_tmp = ds0
#print ds_tmp
for i in range(1,K):
    #PML =
    farthest_pts[i] = ponto_mais_longe(ds_tmp)
    ds_tmp2 = dist_ponto_cj(farthest_pts[i],pts)
    ds_tmp = [ min(ds_tmp[j],ds_tmp2[j]) for j in range(len(ds_tmp))]
    print ('P[%d]: %s' % (i,farthest_pts[i]))

#print farthest_pts

xf=[ farthest_pts[j][0] for j in range(len(farthest_pts))]
yf=[ farthest_pts[j][1] for j in range(len(farthest_pts))]

fig, ax = plt.subplots()
plt.grid(False)
plt.scatter(x,y,c='k',s=4)
plt.scatter(xf,yf,c='r',s=4)
plt.show()

First, a style comment. On the internet, especially in programming, and in particular on this website, English is the lingua franca. So you should avoid mixing other languages and English. This way your code is the most transferable, re-usable and readable.

Second, a comment on the algorithm itself. Your algorithm (and this includes any changes I make to it down below) does not actually find the set of points furthest apart from each other (i.e. the optimal solution). What it does is generate a solution where points tend to be far apart from each other. This is similar to the common strategy for the traveling salesman problem, where you choose to always travel to the closest (unvisited) city next.

This algorithm has the advantage that it does not need to try all combinations, usually quickly leads to a good enough solution, and is very easy to implement. It has the disadvantage that it is on average about a quarter less far apart than the optimal solution and might even return the worst possible solution for some cases.

You might want to look at the other heuristic solutions in that link for different algorithms.

Finally, let's see if the code you have can be improved.

Since you are already using numpy, you should take more advantage of it. It's power lies in using its internal functions, which are implemented and executed in C, independent of the Python interpreter.

As a start, I put your code doing the actual calculations into a function, this way it is re-usable and testable:

@timeit
def op(pts, N, K):
    farthest_pts = [0] * K

    P0 = pts[np.random.randint(0, N)]
    farthest_pts[0] = P0
    ds0 = dist_ponto_cj(P0, pts)

    ds_tmp = ds0
    for i in range(1, K):
        farthest_pts[i] = ponto_mais_longe(ds_tmp)
        ds_tmp2 = dist_ponto_cj(farthest_pts[i], pts)
        ds_tmp = [min(ds_tmp[j], ds_tmp2[j]) for j in range(len(ds_tmp))]
        # print ('P[%d]: %s' % (i, farthest_pts[i]))
    return farthest_pts

if __name__ == "__main__":
    N, K = 80, 40
    pts = np.random.random_sample((N, 2))
    farthest_pts = op(pts, N, K)
    ...

I also used pts = np.random.random_sample((N, 2)) to directly calculate x and y. This means that to plot the points afterwards, you need to use array indexing: plt.scatter(pts[:, 0], pts[:, 1], c='k', s=4).

The @timeit is a decorator*, that prints out the time spent in that particular function whenever it is run. Your code takes about 0.05 seconds on my machine. This is our baseline.

Finally, I put the calling code into a if __name__ == "__main__": guard to allow importing parts of this script from other scripts.

The first thing I would change in your code is the calculation of distances. Here we can use the fact that numpy can operate on the whole array in parallel and just write:

def calc_distances(p0, points):
    return ((p0 - points)**2).sum(axis=1)

Next, here is a way to implement your algorithm using more numpy functions:

@timeit
def graipher(pts, K):
    farthest_pts = np.zeros((K, 2))
    farthest_pts[0] = pts[np.random.randint(len(pts))]
    distances = calc_distances(farthest_pts[0], pts)
    for i in range(1, K):
        farthest_pts[i] = pts[np.argmax(distances)]
        distances = np.minimum(distances, calc_distances(farthest_pts[i], pts))
    return farthest_pts

I also start with pre-assigning an empty array, but using numpy.zeros. I then choose a random point and choose the next furthest point the same way you do.I use numpy.argmax to basically do what your ponto_mais_longe function does, namely return the index of the maximal value. numpy.minimum returns the minimal value for each element in the two given sequences.

This implementation takes about 0.0004 seconds on my machine (so almost 100 times faster).

I don't think this can be sped-up further, because each iteration of the for loop depends on the previous iteration. The only way to speed it up further is to use a different algorithm.

Side note: My timeit decorator looks like this:

from time import clock

def timeit(func):
    def wrapper(*args, **kwargs):
        starting_time = clock()
        result = func(*args, **kwargs)
        ending_time = clock()
        print('Duration: {}'.format(ending_time - starting_time))
        return result
    return wrapper


Beginnings of a 2D Java game engine I've been out of working in Java for quite some time now (almost two years), so I've been working on a fun side project just to get back into the swing of things.

Essentially, in the long term, the goal of this will to be to compile a library that can be used in to create basic platform-like 2D games.

I'm never dealt with the development of engines themselves, so I was wondering if I could get some feedback on how the engine itself actually runs. I'm also just looking for overall input - is this a well-written Java library so far?

package io.code.gm;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;

import javax.swing.JFrame;

import io.code.gm.Input.GMInputHandler;

public abstract class GMEngine extends Canvas implements Runnable {

    private static final long serialVersionUID = 1L;

    public GMInputHandler inputHandler;

    private boolean executionStatus = false;

    private JFrame frame;
    private BufferedImage image;
    private int[] pixels;

    private int updateCount = 0;
    private int frameCount = 0;

    private int updates = 0;
    private int frames = 0;

    abstract void init();
    abstract void update();
    abstract void render();

    public GMEngine(String title, int width, int height) {
        super();

        this.frame = new JFrame(title);

        frame.setResizable(false);
        frame.setSize(width, height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        frame.setLayout(new BorderLayout());
        frame.add(this, BorderLayout.CENTER);

        frame.setVisible(true);

        this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        this.pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

        init();
    }

    public synchronized void start() {
        this.executionStatus = true;
        new Thread(this).start();
        init();
    }

    public synchronized void stop() {
        this.executionStatus = false;
    }

    /**
     * Implemented method run().
     */
    public void run() {
        long lastUpdate = System.nanoTime();
        double nanoPerUpdate = 1000000000D/60D;

        int updates = 0;
        int frames = 0;

        long timer = System.currentTimeMillis();
        double delta = 0D;

        while(executionStatus) {
            long currentUpdate = System.nanoTime();
            delta += (currentUpdate - lastUpdate) / nanoPerUpdate;
            lastUpdate = currentUpdate;

            boolean renderStatus = false;

            while(delta >= 1) {
                updates++;
                update();
                delta -= 1;
                renderStatus = true;
            }

            if(renderStatus) {
                frames++;
                render();
            }

            if(System.currentTimeMillis() - timer >= 1000) {
                timer += 1000;

                this.updates = updates;
                this.frames = frames;

                updates = 0;
                frames = 0;
            }
        }
    }

}

A representation of implementation as a library:

package io.code.gm;

public class FakeImplementation extends GMEngine {

    private static final long serialVersionUID = 1L;

    public FakeImplementation(String title, int width, int height) {
        super(title, width, height);
    }

    public static void main(String[] args) {
        new FakeImplementation("2D Engine", 800, 500);
    }

    void init() {
        this.start();
    }

    void update() {

    }

    void render() {

    }

}

A few abstract notes about game engines and going with the times:
Choice of UI-Framework
You have chosen Swing as your UI Framework. This is a decision I frankly cannot understand. Swing has been officially deprecated in favor of JavaFX. Not only that, Swing is slow.
It's not getting easier by virtue that I know of no way to load textures in Swing. Also there's no proper integration for OpenGL (let alone any other render engine) into Swing.
These problems could easily be remedied by instead working with JavaFX, which is the new official UI framework and has acceptable, if not good integration for OpenGL through javafx.scene.canvas.Canvas
Raw AWT
Working on raw AWT to integrate free drawing with java.awt.Canvas is a royal pain and actually just a workaround for the lack of proper support in Swing. You shouldn't have to work against your UI Framework. Instead work with it and use it to your advantage. Leverage it.
Design mistakes and OOP violations
Making your GMEngine an abstract class is probably a good move. Making the stuff I need for drawing inaccessible from subclasses probably isn't.
Note that most graphics engines are expected to work on a different basis than your "Engine". This comes back to favouring Composition over Inheritance. The point I'm trying to make is that an Engine should help a programmer get work done in significantly less steps than it needed before.
It should boil down to loading Textures, positioning them and then calling something like render() repeatedly after updating the texture positions. This is simply speaking impossible with your current design, because I as "user" of your Engine have to write the code to do that myself anyways. It would've been easier for me to just write those 200-ish lines here myself, because then I have the full control over what I render and only insignificantly more work.
I think you should revisit your motivations for this class and get a clearer idea for what it should actually do to make life easier for you (and other programmers).


Detecting a cycle in a directed graph via an adjacency list implementation and a recursive DFS Here's my attempt. I iterate through each vertex in the graph and do a DFS to see if I reach back on a vertex I already visited in this vertex's iteration. It seems to work but I am not satisfied with how I short-circuit my code when it found a cycle using if clauses, could not think of a better way to do that.
public boolean isCyclic(Map<T, List<T>> adjacencyList) {

    for (T node: adjacencyList.keySet()) {
        Set<T> visited = new HashSet<>();
        visited.add(node);
        if (isCyclic(visited, node) == true)
            return true;
    }

    return false;
}

private boolean isCyclic(Set<T> visited, T node) {
    boolean retval;
    for (T connectedNode: map.get(node)) {
        if (visited.contains(connectedNode)) {
            // We've reached back to a vertex, i.e. a back-edge
            return true;
        } else {
            visited.add(connectedNode);
            if (isCyclic(visited, connectedNode) == true)
                return true;
        }
    }

    return false;
}

I didn't find another way to do it, but I will give you some tips on the current implementation.
Always add curly braces to loop & if
In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.
Simplify the boolean conditions.
In both of the method, you can simplify the boolean validations.
Equivalence
isCyclic(visited, node) == true can be isCyclic(visited, node)
Before
if (isCyclic(visited, node) == true) {
   return true;
}

After
if (isCyclic(visited, node)) {
   return true;
}

Code reduction
In the second method, instead of using the java.util.Set#contains method, you can check the returned boolean of the java.util.Set#add directly; this will allow you to remove an instruction.
Documentation:
Returns:
true if this set did not already contain the specified element

Basic example
Set<Character> set = new java.util.HashSet<>(Set.of('A', 'B', 'C'));
System.out.println(set.add('A')); // false
System.out.println(set.add('D')); // true

This will add the element, if not already present and return true if it was not present.
Before
if (visited.contains(connectedNode)) {
   // We've reached back to a vertex, i.e. a back-edge
   return true;
} else {
   visited.add(connectedNode);
   if (isCyclic(visited, connectedNode)) {
      return true;
   }
}

After
if (!visited.add(connectedNode)) {
   // We've reached back to a vertex, i.e. a back-edge
   return true;
} else {
   if (isCyclic(visited, connectedNode)) {
      return true;
   }
}

In the second method, you can remove the retval variable, since it does nothing.


Converting money into change I am trying to figure out a more efficient way of converting money into change. The code below is what i have written so far. It works perfectly but i know the code can be improved. Is there a more efficient way of writing this code?

public class Problem2 {

    public static int quarters(int total)
    {
        return total/25;
    }

    public static int dimes(int total)
    {
        return (total - quarters(total)*25) /10;
    }

    public static int nickels(int total)
    {
        return (total - (quarters(total)*25) - (dimes(total)*10)) / 5;
    }

    public static int pennies(int total)
    {
        return total - (quarters(total)*25) - (dimes(total)*10) - (nickels(total)*5);
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String total;
        int intTotal;
        System.out.println("Hi, this application will take your number and will display the minimum amount of"
                + "coins necessary to represent the dollar amount");
        System.out.println("Please enter in the total amount of dollars and cents:");
        total = keyboard.next();

        total = total.replace(".","");
        intTotal = Integer.parseInt(total);

        System.out.println(quarters(intTotal) + " Quarters,"
                          +dimes(intTotal) + " Dimes,"
                          +nickels(intTotal) + " Nickels,"
                          +pennies(intTotal) + " Pennies");

    }

}

Minor tweak

    public static int pennies(int total)
    {
        return total - (quarters(total)*25) - (dimes(total)*10) - (nickels(total)*5);
    }

A shorter version of this would be

    public static int pennies(int total)
    {
        return total % 5;
    }

Of course, it would be reasonable to argue that the consistency of the original outweighs the terseness of this version.

Don't forget and repeat work

I would also consider making this an object rather than a static class.  Then you wouldn't have to recalculate these every time that you wanted one.

And this may be a little too much single responsibility principle.  Consider

    public void initialize(int total) {
        quartersCount = total / QUARTER_VALUE;
        total %= QUARTER_VALUE;

        dimesCount = total / DIME_VALUE;
        total %= DIME_VALUE;

        nickelsCount = total / NICKEL_VALUE;
        total %= NICKEL_VALUE;

        penniesCount = total;
    }

This is DRYer, as it puts the change breakdown in just one place rather than doing total - (quarters(total)*25) in three different methods.

A good compiler should generally be able to find the quotient and remainder in one operation, so this should simplify to three calculations even though there are seven assignments.  Your original version takes nineteen just to count pennies.  Thirty-three to calculate all four.  Even if subtractions and multiplications are lower weight than divisions, seven of those were divisions.

I added the constants, as they make it less likely that you will divide by one value and take the remainder of a different value.

I won't write out the getters or the object field declarations.

Just-in-time declarations

        String total;
        int intTotal;
        System.out.println("Hi, this application will take your number and will display the minimum amount of"
                + "coins necessary to represent the dollar amount");
        System.out.println("Please enter in the total amount of dollars and cents:");
        total = keyboard.next();

        total = total.replace(".","");
        intTotal = Integer.parseInt(total);

In Java, it's more customary to do variable declarations just in time to be used.  So

        System.out.println("Hi, this application will take your number and will display the minimum amount of"
                + "coins necessary to represent the dollar amount");
        System.out.println("Please enter in the total amount of dollars and cents:");
        String total = keyboard.next();

        total = total.replace(".","");
        int intTotal = Integer.parseInt(total);


Project Euler #3 (Largest prime factor) in Swift As mentioned in Project Euler #2 in Swift, I intend to work my way through Project Euler using Swift to make sure there aren't any tricks I'm missing.

This is the problem statement for #3:

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143?

This solution if fewer lines of code, but it is recursive (and I don't know about you, but recursion usually takes me a second to wrap my head around).

Here's my solution:

import Darwin

extension Int {
    func isMultipleOf(factor: Int) -> Bool {
        return self % factor  == 0
    }
    func largestPossibleFactor() -> Int {
        let squareRoot: Double = sqrt(Double(self))
        return Int(ceil(squareRoot))
    }
}

func findLargestPrimeFactor(let fromNumber: Int) -> Int {
    for factor in 2..<fromNumber.largestPossibleFactor() {
        if fromNumber.isMultipleOf(factor) {
            return findLargestPrimeFactor(fromNumber/factor)
        }
    }
    return fromNumber
}

let target: Int = 600_851_475_143

let answer: Int = findLargestPrimeFactor(target)

I like Flambino's tip of using extensions and can't believe I forgot about it in my last question (which is part of why I'm doing this--build muscle memory), but I did manage to implement it here.

In plain-English, here's how the findLargestPrimeFactor algorithm works.

Starting at two, we start checking numbers to see whether or not it's a factor of the starting fromNumber.  If we find one, then fromNumber obviously isn't prime, so we return the largest possible prime of fromNumber divided by possibleFactor (which we now know is an actual factor).

We're essentially just dividing the fromNumber by its factors until we get to a number that has no factors (and is therefore prime).

Naming

Your naming is misleading, and effectively broken:

fromNumber is a bad name for that variable. Something like toFactor would be better.
largestPossibleFactor is very broken. The function does not return the largestPossibleFactor, it instead returns an approximate square value. Take the number 36, the largest possible factor (other than 36 itself), is 18, yet your function returns 6. What you should call the function is something like .... actually, I don't think it needs to be a function at all.... it's over-extracted, calling a 1-liner function who's code is easier to write than describe. It's buggy code, anyway....

Bug

Your range limit is the 'half-open' range limit: 2..<Int(ceil(squareRoot))

The intention of this code is to identify where to stop the factor checking. This code will fail for values like ... 9. For 9 your code will not factor it at all, because it is a square of a prime, so your squareRoot will calculate the valeu 3, and you will do the ceil of that (3), and then exclude 3 in the range, so you will not factor the value 9 at all, and call it prime.

Instead, you should simply use the full range operator, and truncate the square-root:

for i in 2...Int(squareRoot)

Performance

A small optimization is possible if you are interested, by limiting the start of the range of the factor tests. Consider converting the recursive part of your function to include the start of the range as well as the number to factor. Something like:

func findLargestPrimeFactorFrom(let smallest: Int, let toFactor: Int) -> Int {
    for factor in smallest...Int(sqrt(Double(toFactor))) {
        if toFactor.isMultipleOf(factor) {
            return findLargestPrimeFactor(factor, toFactor/factor)
        }
    }
    return toFactor
}

The reason it will be faster is because in your recursion, you will never need to check values smaller than factors you have already eliminated higher up the stack.


Alternative to null check after DOM traversal? I have this code working, but I'm not sure if it's the best way to write it. I was watching a JS talk on Maintainable JavaScript, and saw that I probably shouldn't be comparing my element  to null, and instead should use typeof. However, regardless what is returned, it's still an object.

What my code does:

So I needed this code to determine which top-level nav the sub-menu navigations correspond too. What this example does is finds a submenu nav item and grabs it's inner text, then it gets thrown into a while loop to traverse the DOM to find the top-level nav's innerText so I can then have both a top-level nav name and sub-menu nav name. However if the top-level nav does not have a sub-menu then it returns nothing.

var element = document.getElementsByClassName('gtm_navHeader')[25];
var elementText = element.innerText
var elementClass = "menu-parent";

while(element && !((" " + element.className + " ").indexOf(" " + elementClass + " ") > -1)){
    element = element.parentNode;
}

  if (element == null){
    console.log('equals null - ' + elementText);
  }else{
    var anchor = element.querySelector("a");
    var clean = (anchor.innerText || anchor.textContent).toLowerCase() + " : " + elementText;
    console.log('does not equal - ' + clean);
}

JS FIDDLE

Let me know if you have any questions. Happy to provide more information.

Stuff I noticed:

You're missing a semi-colon:

var elementText = element.innerText

The elementClass variable could have a slightly more descriptive variable name. "targetClass" for instance, to indicate that this is the class we're going to look for.

This loop condition is overly complicated:

while(element && !((" " + element.className + " ").indexOf(" " + elementClass + " ") > -1)){

Your code says "if x is not greater than -1", which is the same as simply saying "if x is -1", i.e. x == -1 (or better yet, strict equality: x === -1), so that would clean things up.

Also, instead of all the string-concatenation, you could:

Use element.classList.contains('menu-parent') if you're targeting modern browsers (Internet Explorer 9 and below don't support classList)
Or use element.className.split(' ').indexOf(...) to look through an array of discrete class names (basically emulating classList)
Or use a regular expression like /(^|\s)menu-parent(\s|$)/i.test(element.className)
Or add the spaces in the elementClass variable, so you don't have to add them every time you want to check.

I'd use #2. This gets us:

while(element && element.className.indexOf(elementClass) === -1) {

More on this later.

Then there's this:

  if (element == null){
    console.log('equals null - ' + elementText);
  }else{
    var anchor = element.querySelector("a");
    var clean = (anchor.innerText || anchor.textContent).toLowerCase() + " : " + elementText;
    console.log('does not equal - ' + clean);
}

For one, the indentation's wrong. For another, as you yourself wrote, you don't need the == null in the condition.
In fact, you've already used the plain element in the while loop's condition. There you checked if element "was anything" which is exactly the same thing you're doing here.

Also, don't leave console.log statements in your production code. Like the 25, this is probably just a test-thing, right? Still, it's good to know that some JS runtimes don't have a console, so calling console.log will just cry "console is undefined!" and stop everything.

If you insist on using it, at least check whether console exists first:

if(console) { console.log(...); }

You could also throw that into a function, so you're sure to always have a check, and so you have 1 place in which to simply turn off logging.

Now, getting back to the loop: I'd change it up, making the "find ancestor by class name" a function:

function getAncestorByClassName(from, className) {
  while(from) {
    if(from.className.split(' ').indexOf(className) !== -1) { # or any of the other options
      return from; // found a match, return it (stops the loop, exits the function)
    }
    from = from.parentNode; // go up a level and repeat
  }
  return null; // if the loop just ended normally, we didn't find anything
}

Now we've got a generic function you can use whenever necessary. This makes the rest of the code a lot simpler:

var element = document.getElementsByClassName('gtm_navHeader')[25],
    ancestor = getAncestorByClassName(element, 'menu-parent'),
    anchor, clean; // declare all your variables up top; just good practice

if(ancestor) {
  ...
} else {
  ...
}


How do I optimize the bubble sort in Assembly8086? I tried to implement bubble sort in Assembly 8086.
datasg      SEGMENT BYTE 'data'
array       DB 1, 3, 2, 5, 4
n           DW 5
datasg      ENDS
stacksg     SEGMENT BYTE STACK 'stack'
            DW 12 DUP(?)
stacksg     ENDS
codesg      SEGMENT PARA 'code'
            ASSUME CS:codesg, DS:datasg, SS:stacksg
MAIN        PROC FAR

; Pushing the previous data segment to keep it secure.
            PUSH DS
            XOR AX, AX
            PUSH AX
            MOV AX, datasg
            MOV DS, AX
;SI = i
            XOR SI, SI
            MOV CX, n
            DEC CX
out:        PUSH CX; Pushing CX to the stack before entering the second for loop
            XOR DI, DI
            MOV CX, n
            DEC CX
            SUB CX, SI
in:         MOV AH, array[DI]
            CMP AH, array[DI+1]
            JLE if_end
            XCHG AH, array[DI+1]
            MOV array[DI], AH
if_end:     INC DI
            LOOP in
            POP CX
            INC SI
            LOOP out
            XOR SI, SI
; Some garbage code to move array elements to AL register one by one to see them while debugging.
            MOV AL, array[SI]
            INC SI
            MOV AL, array[SI]
            INC SI
            MOV AL, array[SI]
            INC SI
            MOV AL, array[SI]
            INC SI
            MOV AL, array[SI]
            RETF
MAIN        ENDP
codesg      ENDS
            END MAIN

It seems to be working for the given example in the above code. I also tried it with different arrays and they all seem to work.
I just want to learn if there is a way to improve it? Improvements like changing JMP codes to decrease the size of code or using AX with XCHG because that is faster.
I also can't comprehend the idea of pushing CX to stack for using nested-for loops. If you would give some suggestion about it I would be very happy.

On your array that has 5 elements
the 1st iteration of the outerloop (CX=4) has to do 4 compares in the innerloop
the 2nd iteration of the outerloop (CX=3) has to do 3 compares in the innerloop
the 3rd iteration of the outerloop (CX=2) has to do 2 compares in the innerloop
the 4th iteration of the outerloop (CX=1) has to do 1 compare in the innerloop
In your code you have initialized the outerloop counter correctly but you should see that the current value of the outerloop counter can serve as the initial value of the innerloop counter. You don't need to re-compute this!

When it comes to speed, XCHG with a memory operand is bad. Normally we would load 2 successive elements in 2 different registers, compare those, and if necessary write them back switched.
However because your array contains byte-sized elements, you can load 2 elements in 1 word-sized register, compare its low and high byte-sized halves, and if necessary xchg the halves and write the word register back. That's how I did it in below code.

The LOOP instruction has become infamous for being slow these days. You can easily replace it by the pair of instructions dec cx jnz ....

    mov   cx, n
    dec   cx             ; Max number of compares is (n - 1)
outerloop:
    push  cx             ; (1) Preserve outerloop counter CX

    xor   di, di
innerloop:
    mov   ax, array[di]
    cmp   al, ah
    jle   if_end
    xchg  al, ah
    mov   array[di], ax
if_end:
    inc   di
    dec   cx
    jnz   innerloop

    pop   cx             ; (1) Restore outerloop counter CX
    dec   cx
    jnz   outerloop

I also can't comprehend the idea of pushing CX to stack for using nested-for loops. If you would give some suggestion about it I would be very happy.

Pushing the outerloop counter CX is only necessary if the innerloop wants to use and change the CX register for its own purposes. We can easily re-write the above code and use e.g. BX to control the innerloop. Then we don't need to push cx or pop cx.
    mov   cx, n
    dec   cx             ; Max number of compares is (n - 1)
outerloop:

    mov   bx, cx
    xor   di, di
innerloop:
    mov   ax, array[di]
    cmp   al, ah
    jle   if_end
    xchg  al, ah
    mov   array[di], ax
if_end:
    inc   di
    dec   bx
    jnz   innerloop

    dec   cx
    jnz   outerloop

And while we're optimizing this, we can even write the innerloop without using a special loop counter. We can use the index register DI at the same time for indexing the memory and for counting. This method also speeds things up since the combo cmp di, cx jb innerloop can macro-fuse and give us some extra speed.
    mov   cx, n
    dec   cx             ; Max number of compares is (n - 1)
outerloop:

    xor   di, di
innerloop:
    mov   ax, array[di]
    cmp   al, ah
    jle   if_end
    xchg  al, ah
    mov   array[di], ax
if_end:
    inc   di
    cmp   di, cx
    jb    innerloop

    dec   cx
    jnz   outerloop

stacksg     SEGMENT BYTE STACK 'stack'
            DW 12 DUP(?)
stacksg     ENDS

Might I further suggest you set the stack to a more realistic value like 128 words?


A whole bunch of JButtons Please review this code.

  import java.awt.*;

 import javax.swing.*;
 public class Snake_Ladder  {
public static void main(String[] args) {
new Snake_Ladder();
}

public Snake_Ladder(){
int i;
JFrame frame = new JFrame();
JPanel pane = new JPanel();
GridLayout experimentLayout = new GridLayout(11,0);
        pane.setLayout(experimentLayout);
        for(i=100;i>=91;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=81;i<=90;i++){
        pane.add(new JButton(" " +i));
       }
        for(i=80;i>=71;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=61;i<=70;i++){
        pane.add(new JButton(" " +i));
        }
        for(i=60;i>=51;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=41;i<=50;i++){
        pane.add(new JButton(" " +i));
        }
        for(i=40;i>=31;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=21;i<=30;i++){
        pane.add(new JButton(" " +i));
        }
        for(i=20;i>=11;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=1;i<=10;i++){
        pane.add(new JButton(" " +i));
        }
frame.add(pane);
frame.setSize(1200,1400);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

}

 }

Unfortunately your question about "How to..." is off-topic for this site but I feel that your code really needs to be reviewed as there are some things that can be improved.

Don't import .* Only use the imports that you need. If you need to import JButton, import JButton, don't import all other classes within the same package.
Fix your indentation and spacing for (i = 100; i >= 91; i--) { is a lot more readable than what you currently have.

Also, use an extra indentation step (one tab / four spaces) after each { and go back one indentation step after each }. Applying this, your code will look like:

for (i = 61; i <= 70; i++) {
    pane.add(new JButton(" " + i));
}

To make your IDE do the indentation for you:

If you are using Eclipse, select all your code and press either Ctrl + I or Ctrl + Alt + F.
If you are using Netbeans, select all your code and press Alt + Shift + F

Update, your for-loop can be written as only one loop (even though it's quite many variables and this code possibly needs it's own review...)

int COUNT = 100;
int last10s = 0;
for (int i = 0; i < COUNT; i++) {
    int decreasing = COUNT - i;
    int even10 = i / 10;
    if (decreasing % 10 == 0)
        last10s = decreasing;
    boolean shouldDecrease = even10 % 2 == 0;
    int increasing = last10s - 9 + i % 10;
    int chosen = shouldDecrease ? decreasing : increasing;
    pane.add(new JButton(" " + chosen));
}


Responsive module and tooltip module Recently, I've noticed that my code looks so ugly because there were a bunch of functions and global variables.  So, I started reading a little bit about design patterns. Now I come with something that's working for me, but I am not sure if it's good practice.

Anyway, I would like you to take a look at the code and tell me what can I improve.  I'd also like to know a better way to start using modular pattern in JavaScript.  Finally, I'd like suggestions on material for learning about modular pattern and JavaScript.

var responsiveModule = {

    settings: {
        device: false,
        button: $(".responsive-btn"),
        target: $("nav ul"),
        mobileClass: "toggle-menu",
        bgImage: '<img class="background-image" src="img/background.jpg" alt="">',
        bgImageSelector: $(".background-image"),
        windowWidth: $(window).width(),

    },

    init: function(){
        responsiveModule.checkDevice();
        responsiveModule.replaceImages();
        responsiveModule.bindFunctions();
        responsiveModule.listenResize();
    },

    checkDevice: function(){
        if(this.settings.windowWidth > 992){
            this.settings.device = "desktop";

        } else {
            this.settings.device = "mobile";
        }
    },

    bindFunctions: function(){
        var buton = this.settings.button,
            muelleBtn = this.settings.muelleBtn;
        buton.on("click touchstart", function(e){
            e.preventDefault();
            responsiveModule.animateMenu(responsiveModule.settings);
        });
    },

    animateMenu: function(settings){
        var device = settings.device,
            target = settings.target,
            mobileAnimation = settings. mobileClass;

        if(device == "mobile"){
            target.toggleClass(mobileAnimation);
        }
    },

    replaceImages: function(){
        var bgContainer = $("#main-content"),
            bgImage = responsiveModule.settings.bgImage,
            device = responsiveModule.settings.device,
            backgroundSelector = $(".background-image");

        if(device == "desktop" && backgroundSelector.length == 0){
            bgContainer.append(bgImage);
        }else if(device == "mobile" && backgroundSelector.length == 1){
            backgroundSelector.remove();
        }
    },

    listenResize: function(){
        $(window).on("resize", function(){
            responsiveModule.checkDevice();
            responsiveModule.replaceImages();
            responsiveModule.settings.windowWidth = $(window).width();
        });
    }

}

var tooltipModule = {

    settings: {
        tooltipState: false
    },

    init: function(){
        tooltipModule.bindUIfunctions();
    },

    bindUIfunctions: function(){
        var device = responsiveModule.settings.device;
        if(device == "mobile"){
            $(".ship").on("click", function(e){
                e.preventDefault();
                tooltipModule.manageTooltip(e);
            });
        }else{
            $(".muelle-item").addClass("desktop");
        }
    },

    manageTooltip: function(e){
        var tooltip = $(e.currentTarget).next(),
            tooltips = $(".tooltip");

        tooltips.removeClass("display");
        tooltip.addClass("display");
    }

}

$(document).on("ready", function(){
    responsiveModule.init();
    tooltipModule.init();
});

The best pattern to start "OOP" in JavaScript is the Revealing Pattern:

var revealed = function(){
   var a = [1,2,3];
   var abc = function(){
     return (a[0]*a[1])+a[2];
   }

   return {
      name: 'revealed',
      abcfn: abc
   }
}();

From here.

Then read this book.

And learn RequireJS, which will increase the modularity of your code and will load your JS files on demand.

I see you are using JS for create HTML elements.  To help you with this, take a look at UnderscoreJS templates and Mustache.


Fetch nearby chat users using Firebase and nested completion handlers I have a method that calls three functions that each make a request to Firebase and pass back data in a completion handler. Once the data from 2 of the completion handlers is sent back, I call another method to pass in the data and send back a valid result. Is nesting blocks like this a sign of poor design?

func fetchNearbyUsers(for user: User, completionHandler: usersCompletionHandler?) {

    self.fetchAllUsers(completionHandler: { (users: [User]) in

        ChatProvider.sharedInstance.fetchAllChatrooms(completionHandler: { (chatrooms: [Chatroom]) in

            self.validateNewUsers(currentUser: user, users: users, chatrooms: chatrooms, completionHandler: { (validUsers: [User]) in
                guard validUsers.isEmpty == false else {
                    completionHandler?([])
                    return
                }
                completionHandler?(validUsers)
            })
        })
    })
}

Nesting
In general, I find it harder to read nested closures. I think it's even worse when calling APIs that run the closures asynchronously because it makes it harder to understand what's happening when. That said, these 3 aren't that bad. (And despite my dislike of nesting them, I've done it myself!)
You can use the various shorthands to make this slightly easier to read by inferring types and using the rules for trailing closures. I think your code could be rewritten like this:
func fetchNearbyUsers(for user: User, completionHandler: userCompletionHandler?) {
    fetchAllUsers() { users in
        ChatProvider.sharedInstance.fetchAllChatrooms() { chatrooms in
            validateNewUsers(currentUser:user, users:users, chatrooms:chatrooms) { validUsers in
                guard validUsers.isEmpty == false else {
                    completionHandler?([])
                    return
                }
                completionHandler?(validUsers)
            }
        }
    }
}

I've used type inference on users, chatrooms and validUsers to shorten the closures' code. And I used trailing closure notation to further reduce the number of characters needed. Whether it's more or less readable is a judgement call, but it looks cleaner to me without being too sparse.
Naming
If it were me, I'd change the name of the function to fetchUsers(nearby user: User, completionHandler: usersCompletionHandler?). I say that because for is a keyword, and even if the compiler doesn't mind it, it looks weird to me to have it there naked. If it was forUser: it would be less weird to me. Also, I think fetchUsers(nearby:, completionHandler:) flows better.
Is That guard Needed?
Why guard if validUsers.isEmpty? Inside of it you simply call the completionHandler with an empty array. But if validUsers.isEmpty is true and the guard isn't there, you'd still just be calling the completionHandler with an empty array. So you might be able to further shorten it to:
func fetchNearbyUsers(for user: User, completionHandler: userCompletionHandler?) {
    fetchAllUsers() { users in
        ChatProvider.sharedInstance.fetchAllChatrooms() { chatrooms in
            validateNewUsers(currentUser:user, users:users, chatrooms:chatrooms) { validUsers in
                completionHandler?(validUsers)
            }
        }
    }
}


A selection pattern for C++11 In simulating physical equations (such as fluid dynamics) it is common to write an application that deals with 1, 2, and 3 dimensions. A common C/Fortran approach is to make all vectors (for example) have a size of 3, and then to carry around a global constant to say how many elements are valid.

We have tried to use C++11 templating to serve the same purpose and the majority of our application is now templated by int DIM.

There are times that the difference between API for different dimensions requires entirely new classes. For this, we have come up with the following selector pattern -- it seems to be working well, but I was wondering if we have reinvented the wheel and missed something along the way?

In order to construct the pattern, we need several files:

ClassName_fwd.h:

This allows the user to reference the specific implementation of the dimension specific classes in a way that is consistent for all dimensions.

// forward decs
class ClassName_1;
class ClassName_2;
class ClassName_3;
template<int DIM>
struct ClassNameSelector { };
// 1D
template<>
struct ClassNameSelector<1> {
using ClassName = ClassName_1;
};
// 2D
template<>
struct ClassNameSelector<2> {
using ClassName = ClassName_2;
};
// 3D
template<>
struct ClassNameSelector<3> {
using ClassName = ClassName_3;
};
// typedef
template<int DIM>
using ClassName = typename ClassNameSelector<DIM>::ClassName;

ClassName.h

#include <path/to/ClassName_fwd.h>
#include <path/to/ClassName_1.h>
#include <path/to/ClassName_2.h>
#include <path/to/ClassName_3.h>

ClassName.cpp

// explicit instantiations
template struct ClassNameSelector<1>;
template struct ClassNameSelector<2>;
template struct ClassNameSelector<3>;

ClassName_N.h/cpp [optional]

Holds all of the functionality that can be implemented without care for dimension, in addition to pure virtual methods that should be overridden by the dimension-specific implementations. This class sets the dimensionless API for ClassName. In the cpp file, there should be explicit instantiations of this class. This class might be excluded to avoid pure virtual function calls.

/**
* All of the functions that have a constant implementation
* for all dimensions
*/
template<int DIM>
class ClassName_N {
    // non-dimensional functions, i.e.
    void somethingDimensionless(
        const std::array<double, DIM>& dblArray
    ) const;
};

ClassName_[1,2,3].h/cpp

Implements the [1,2,3] dimension version of the class. This should implement the pure virtual functions of ClassName_N in addition to any functions specific to the particular dimension. These addition functions can only be called from other dimensionally specific implementations, otherwise the compiler will complain.

/**
* The dimensionally specific API's
*/
class ClassName_1 : public ClassName_N<1> {
    // dimensional functions, i.e.
    void somethingIn1D() const;
};

Usage

#include <path/to/ClassName.h>

template<int DIM>
void useAnyDimension(const ClassName<DIM>& c) {
    std::array<double, DIM> arr;
    c.somethingDimensionless(arr);
}

void doSomethingIn1D(const ClassName<1>& c) {
    c.somethingIn1D();
}

int main (int argc, char *argv[]) {
    ClassName<1> oneD;
    ClassName<2> twoD;

    // dimension-less
    useAnyDimension(oneD);
    oneD.somethingDimensionless({0.1});
    twoD.somethingDimensionless({0.1, 0.5});

    // dimension specific
    doSomethingIn1D(oneD);
    oneD.somethingIn1D();

    // the following would give compile-time errors
    //doSomethingIn1D(twoD);
    //twoD.somethingIn1D();

    return 0;
}

This seems unnecessary complicated. Why not just have one simple class template:

template <int DIM>
class ClassName {
public:
    using array = std::array<double, DIM>;

    void somethingDimensionless(const array& dblArray) const;

    template <int D = DIM,
              typename = std::enable_if_t<(D == 1)>>
    void somethingIn1D() const {
        ...
    }
};

And use it directly:

ClassName<1> oneD;
ClassName<2> twoD;

We use SFINAE instead of a static_assert in case you want to write a type trait to check for the existence of somethingIn1D. With a static_assert, ClassName<2>{}.somethingIn1D() wouldn't compile but overload resultion would still find it.


Bash Script - batch rename files in current directory with preview I have written the following script to automate my frequent usage of rename.
This saves me from always typing the whole command to the command line as well as doing a dry run with -n for testing before applying the pattern.

#!/bin/bash

 if [ ! -d ~/.script-history ]; then
     echo -e "Folder .script-history does not exist and gets created... \n";
     mkdir ~/.script-history\
      && { echo -e "created folder: ~/.script-history \n"; }\
      || { echo -e "could not create folder: ~/.script-history \n"; }
 fi

 history -r ~/.script-history/rename
 set -o vi
 search=""
 replace=""

 echo -e "Please enter token to be replaced: "
 read -e -r search
 history -s "$search"
 echo -e "Please enter replacement: "
 read -e -r replace
 history -s "$replace"
 history -w ~/.script-history/rename

 value=$(rename -n "s/$search/$replace/g" ./*)

 echo -e "$value"

 lines=$(echo -en "$value" | wc -m)

 if [ "$lines" -gt 0 ]; then
     read -p "Do you want to apply changes? [Y]es [n]o " yn
     case $yn in
         [yY]* ) echo "renaming files...";\
                 rename "s/$search/$replace/g" ./*\
                 && { echo "success :-)"; }\
                 || { echo "failed :-("; };;
         [nN]* ) echo "no changes have been made."; exit;;
         * ) echo "Are you kidding me???";;
     esac
 elif [ "$lines" -eq 0 ]; then
     echo -e "No matches found for <$search> !"
 fi

For making it easier to adjust or reuse the changes done with the script, I added a history, while the first part checks if the folder exists where I save my histories for script files. I do not quite understand this line set -o vi but it is working.
For me as a beginner it was quite tricky to get the script recognizing whether there are changes to be applied or not. My workaround here is the $lines variable, where I count the output of chars and then process with
"$lines" -gt 0 or "$lines" -eq 0.

One of the questions I have is about the usage of the A && B || C pipe. I use it quite frequently in my scripts, where ShellCheck reports the following:

  SC2015: Note that A && B || C is not if-then-else. C may run when A is true.

The other output of ShellCheck is:

  SC2162: read without -r will mangle backslashes.

I think it is ok, since the user is only expected to input YyNn. While I use the script on a daily basis, is the coding sufficient or where can it be improved?

The disadvantage of the script is that you have to type in both search and replacement before it checks if there are matches. An improvement could be to add a function that checks for that and returns to the search input when there are no matches.

Checking if a value is not empty

This is a very complicated way to check that value is not empty:

lines=$(echo -en "$value" | wc -m)

if [ "$lines" -gt 0 ]; then

This is equivalent:

if [ "$value" ]; then

Avoid echo -e

It's good to avoid all flags of echo, such as -e,
because they are not portable.
Instead of this:

 echo -e "Folder .script-history does not exist and gets created... \n";

I recommend to add a second empty echo:

echo "Folder .script-history does not exist and gets created..."
echo

The concern about A && B || C

Shellcheck raised an issue here:

 rename "s/$search/$replace/g" ./*\
 && { echo "success :-)"; }\
 || { echo "failed :-("; };;

The issue is that if rename succeeds but then echo success fails,
the || will get executed.
You can ignore this issue, because in the unlikely event that the first echo fails, the second (after the ||) is likely to fail too, so it won't matter.
If you want to be pedantic/bullet-proof, then you have to spell out a proper if-else statement instead of the && ... || chaining.

In any case, the command can be simplified without the grouping:

rename "s/$search/$replace/g" ./* \
&& echo "success :-)" \
|| echo "failed :-(" ;;

I also added spaces in front of the \ before the line breaks,
to make it perfectly clear that the argument before the \ is not being continued on the next line.
Without that, this point would be ambiguous, making the script a bit harder to read.

The concern about read without -r

If the user input contains \, it may not get preserved.
That's hardly ever intended,
and probably you would not want that either.
As a rule of thumb,
it's good to always use read -r.