texts: Implementation of resizable array (Vector or ArrayList) in C

texts:
I've implemented a very simple resizable integer array in C, only including functionality to add and remove elements at various indexes.

I haven't looked at using void pointers to handle any type of data yet. I'm mainly wondering if my structure of the code is okay, with the header file containing external API details and the source file hiding away implementation detail.

vector.h

#ifndef VECTOR_H
#define VECTOR_H

typedef struct vector_struct* Vector;

extern Vector vector_create();
extern void vector_destroy(Vector vector);
extern void vector_add(Vector vector, int* element);
extern void vector_add_index(Vector vector, int* element, int index);
extern void vector_remove(Vector vector, int index);
extern void vector_pop(Vector vector);
extern void vector_print(Vector vector);

#endif

vector.c file:

#include "vector.h"
#include <stdlib.h>
#include <stdio.h>

struct vector_struct {
  int capacity;
  int number_of_elements;
  int* elements;
};

/*
Private function to allocate memory for vector creation
*/
static void* get_memory(size_t size) {
  void* memory;
  if ((memory = malloc(size)) == NULL) {
    exit(EXIT_FAILURE);
  }
  return memory;
}

/*
Private function to resize the amount of memory allocated for the given vector
*/
static void resize_vector(Vector vector, size_t size) {
  if ((vector->elements = realloc(vector->elements, size)) == NULL) {
    exit(EXIT_FAILURE);
  }
  vector->capacity = size / sizeof(int);
}

/*
Create and initialize a vector for use
*/
extern Vector vector_create() {
  Vector vector = get_memory(sizeof(Vector));

  vector->capacity = 10;
  vector->number_of_elements = 0;
  vector->elements = get_memory(sizeof(int) * 10);

  return vector;
}

/*
Free memory allocated for vector
*/
extern void vector_destroy(Vector vector) {
  free(vector->elements);
  free(vector);
}

/*
Add given element to the end of the vector
*/
extern void vector_add(Vector vector, int* element) {
  if (vector->number_of_elements+1 > vector->capacity) {
    resize_vector(vector, (vector->capacity * 2) * sizeof(int));
  }

  vector->elements[vector->number_of_elements] = *element;
  vector->number_of_elements++;
}

/*
Add given element at the given index in the vector
*/
extern void vector_add_index(Vector vector, int* element, int index) {
  if (index < 0 || index >= vector->number_of_elements) {
    exit(EXIT_FAILURE);
  }

  if (vector->number_of_elements+1 > vector->capacity) {
    resize_vector(vector, (vector->capacity * 2) * sizeof(int));
  }

  for(int i=vector->number_of_elements; i>index; i--) {
    vector->elements[i] = vector->elements[i-1];
  }

  vector->elements[index] = *element;
  vector->number_of_elements++;
}

/*
Removes element at given index, shifting all elements after that index
to the left once in order to fill in the empty index
*/
extern void vector_remove(Vector vector, int index) {
  if (index < 0 || index >= vector->number_of_elements) {
    exit(EXIT_FAILURE);
  }

  for(int i=index; i<vector->number_of_elements-1; i++) {
    vector->elements[i] = vector->elements[i+1];
  }
  vector->number_of_elements--;

  if (vector->number_of_elements < (vector->capacity / 2)) {
    resize_vector(vector, (vector->capacity / 2) * sizeof(int));
  }
}

/*
Removes the last element in the vector
*/
extern void vector_pop(Vector vector) {
  if (vector->number_of_elements < 1) {
    exit(EXIT_FAILURE);
  }

  vector->number_of_elements--;
}

/*
Prints the vector's contents
*/
extern void vector_print(Vector vector) {
  printf("Capacity of vector: %d\nContents:\n", vector->capacity);
  printf("[");
  for (int i=0; i<vector->number_of_elements; i++) {
    printf((i == vector->number_of_elements-1) ? " %d " : " %d,", vector->elements[i]);
  }
  printf("]\n");
}


texts: Using a destructuring assignment on a style object to extract two members

texts:
Recently, one of my colleague decided to destructure the React-Native styles object this way:

const { header, headerHint, bodyContainer, body, normalText, buttonWrapper, button, footer, footerLinks } = styles;

And then used the variables in the React code:

<View style={header}>
  <Text style={headerHint}hint</Text>
 ...
</View>

This felt quite wrong to me as it doesn't provide much value to the code, destructuring an object to grab more than 5-6 variables makes the code more difficult to read in my opinion.
Also, keeping the styles in the styles object let you know your styles comes from the StyleSheet. In some cases we might want to create variables to merge several styles, they become much easier to spot.

He argues destructuring reduces areas that you need to change - if you need to change them like if the styles object changes to something else, you don't have to remove all the references to styles.

I'm wondering what is your opinion on this point and if you follow any style guide about destructuring object like this one?


texts: Serialize C# objects of unknown type to bytes using generics

texts:
Usage example

var qm = new QueueMessage("foo", 99);
var ba = ByteArraySerializer<QueueMessage>.Serialize(qm));

Class that performs the serialization / deserialization

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Codingoutloud
{
   public static class ByteArraySerializer<T>
   {
      public static byte[] Serialize(T m)
      {
         var ms = new MemoryStream();
         try
         {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, m);
            return ms.ToArray();
         }
         finally
         {
            ms.Close();
         }
      }

      public static T Deserialize(byte[] byteArray)
      {
         var ms = new MemoryStream(byteArray);
         try
         {
            var formatter = new BinaryFormatter();
            return (T)formatter.Deserialize(ms);
         }
         finally
         {
            ms.Close();
         }
      }
   }
}

Example of an object we would serialize

using System;

namespace Codingoutloud
{
   [Serializable]
   public class QueueMessage
   {
      public QueueMessage() {}
      public QueueMessage(string name, int id)
      {
         Name = name;
         Id = id;
      }

      public string Name { get;  set; }
      public int Id { get; set; }
   }
}


texts: Shift an element in a circular container

texts:
I implemented a function to shift an element after another in a logical circular array. Shifting in this case simply means moving element at position i to in front of element at position j. Of course I can't simply swap the elements at position i and next(j), because I would alter the positions of two elements in this circular array.

Here's the code I came up with:

std::vector<SomeType> circular_container;

/*
 * Move node at index i in front of node j
 * by shifting all nodes by 1 behind until j.
 * */
void shift(int i, const int j) {

    if (circular_container.size() < 2) {
        return;
    }

    int n = next(i);
    while(i != j) {
        std::swap(circular_container[i], circular_container[n]);
        i = n;
        n = next(i);
    }

}

And the next function looks like:

/*
 * Returns the index of the node after the node at index i.
 * */
int next(const int i) {
    return (i + 1) % circular_container.size();
}

Is the shift operation correct? If it is, any way to improve it?


texts: performing SQL SELECT query inside the loop

texts:
I have a table leave_muster inside which I have to update all the records of the previous month on every start of the new month.

My Code

public function sync()
    {
        $pre_month = (int)date('m') - 1;

        $data = $this->Leave_muster_model->get_by_month($pre_month);

        $updated_data = [];

        foreach ($data as $key => $value) {

            // Fetch each employee details to perform some check
            // Then update the array and

            $updated_data[$key] = [
                'emp_id'                   => $value->emp_id,
                'accumulated_leaves'       => 0.0,
                'total_accumulated_leaves' => 0.0,
                'leave_taken'              => 0.0,
                'salary_deducted_days'     => 0.0,
                'leave_balance'            => 0.0,
                'month'                    => date('m'),
                'year'                     => date('Y'),
                'created_date'             => date('Y-m-d')
            ];
        }

    }
}

In the above code, I have to fetch the employee details before updating the leaves to perform some checks, So I have two ways

Fetch the employee details inside the loop before any update to
perform checks.
Fetch all the employee details outside the loop into
an array then get the employee by employee id the perform checks

I want to know which would be a better approach as I know that in any given point of time in the future there won't be any millions of employees in the table.

Lang: PHP
Framework: Codeigniter


texts:
I have made a class what uploads an image to imgur (a service with an API where you can upload images). And then I read the response of the API what contains the URL and the HTTP status code (200 if succeeded).

And I'd like some feedback, since the runtime is pretty long for a 50kb image. The current runtime is around 2,5 seconds. Isn't that a little too much or am I overestimating?

    public boolean connect() {
    try {
        final URL url = new URL(getApi());
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        final ScreenedImage image = new ScreenedImage();
        image.create();
        final String data = image.getData();

        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.setRequestMethod(RequestMethod.POST);
        connection.setRequestProperty("Authorization", String.format("%s %s", request, clientId));
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.connect();

        final OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
        osw.write(data);
        osw.flush();

        int bytesRead;
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        final InputStream is = connection.getInputStream();
        final byte[] bytes = new byte[1024];
        while ((bytesRead = is.read(bytes, 0, bytes.length)) > 0) {
            buffer.write(bytes, 0, bytesRead);
        }

        buffer.flush();

        final StringReader sr = new StringReader(buffer.toString());

        final Gson gson = new GsonBuilder().create();
        final JsonReader reader = new JsonReader(sr);

        response = gson.fromJson(reader, Response.class);

        osw.close();

        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

ScreenedImage:

private BufferedImage image = null;
private File file = null;
private String data = null;

public void create() {
    try {
        file = new File("placeholder.jpg");
        image = ImageIO.read(file);

        final ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
        ImageIO.write(image, "png", byteArray);
        final byte[] imageByte = byteArray.toByteArray();
        final String dataImage = Base64.encodeBase64String(imageByte);
        final URLCodec codec = new URLCodec("UTF-8"); //apache codec library
        data = String.format("%s=%s", codec.encode("image"), codec.encode(dataImage));
    } catch (IOException | EncoderException e) {
        e.printStackTrace();
    }
}


texts:
I am doing a website for an association and I have never done the server side before. Here I made a very simple routing system:

app.set('port',(process.env.PORT || 5000));

app.use(express.static(__dirname + '/public' ));
app.use(express.static(__dirname + '/views' ));

app.get('/',function(req,res,next) {
    res.redirect('/en/insa');
})

.get('/:language/:page?',function(req, res, next){

    var path = __dirname+'/views/'+req.params.language+'/'+req.params.page+'.ejs';

    fs.access(path,function(err) {
        if (err) {
            res.status(404);
            console.error('404 : /' + req.params.page);
            res.render('404.ejs', {
                page: req.params.page
            });
            return;
        }
        res.charset = "utf-8";

        res.render(path ,{language: req.params.language});
    });
})

.listen(app.get('port'),function() {
    console.log('Server is running, server is listening on port ',app.get('port'));
})

I just redirect automatically the client if he hits the main www.site.com/ page and then I just check for the language and page in the URL like www.site.com/en/description for instance. The fs.access function checks if the EJS (that's a template generator for HTML pages) page actually exists in the folder before rendering it.

Is there anything that could go wrong with this code, or something that could be done better?


texts:
I'm relatively new to jQuery and am trying to learn best practices/design patterns with JavaScript. Came across this link and decided to try and put it to something useful.

So far I've made a notifications menu dropdown using TinyScrollBar where the user can remove an individual notification. Once removed, the height of the dropdown updates until there are no more.

Here is a demo of what I have so far.

I would like to know ways on how I can improve my JavaScript.

JS

var TEST = TEST || {};

/* Notifications */
TEST.notif = {};
TEST.notif._notifOpen = false;
TEST.notif._el = null;
TEST.notif._sum = 0;
TEST.notif._defaultVPHeight = 350;

TEST.notif.init = function(){

this._el = $('#notifications');

$('.notif-trigger').on('click',function(e){
    TEST.notif.toggleNotifications();
    return false;
});

// when you click outside the notification menu
// hide the notifications
$('html').on('click',function(e){
    if( TEST.notif._notifOpen ) {
        TEST.notif.hideNotifications();
    }
});

// set initial notifications scrollbar height
this._el.tinyscrollbar( {size: TEST.notif._defaultVPHeight} );
};

TEST.notif.showNotifications = function(){
var $el = this._el,
    $close = $('.notif-close'),
    $li = $('.notif-list li a');

// show notificatoins and update scrollbar position
$el.show().tinyscrollbar_update();

// stop propagation
$li.on('click',function(e){ e.stopPropagation(); });

// remove list-item
$close.on('click', function(e){

    // store
    var liHeight, newH, overviewH;

    // store individual list-item height
    liHeight = $(this).parent().height();

    // remove the list-item you clicked
    $(this).parent().remove();

    // store the new height TEST the viewport
    newH = TEST.notif._defaultVPHeight - liHeight;

    // get height TEST actual contents
    overviewH = $('.overview').height();

    // set new defaultH
    TEST.notif._defaultVPHeight = newH;

    // update scrollbar
    $el.tinyscrollbar_update();

    // once scrollbar is disabled, start changing the viewport height
    if( $('#notifications .scrollbar').hasClass('disable') && $('.notif-list li').length > 1 ){
        $('#notifications .viewport').height( overviewH );
    } else if( $('.notif-list li').length == 1 ) {
        $('.notif-list li.empty').show();
    }

    return false;
});

this._notifOpen = true;
};

TEST.notif.hideNotifications = function(){
this._el.hide();
this._notifOpen = false;
};

TEST.notif.toggleNotifications = function(){
this._notifOpen ? this.hideNotifications() : this.showNotifications();
};

/* init */
$(document).ready(function(){
    TEST.notif.init();
});


texts: Simplify double AJAX request for jQueryUI's autocomplete widget

texts:
I'm using jQueryUI's Autocomplete widget for a product search. The data is in a database, so as the souce I passed it an AJAX request. My problem is, that I need some data about the currently focused option, so in the autocomplete's focus method, I'm calling another AJAX request to the same PHP file, to get some other data.

Here's the jQuery code I'm currently using:

$('.termeknev.ujtermek').autocomplete({
    autoFocus: true,
    minLength: 1,
    source: function (request, response) {
        $.ajax({
            url: "/backend/termekek-query.php",
            type: "POST",
            data: {
                "term": request.term
            },
            success: function (data) {
                response($.map(JSON.parse(data), function (items) {
                    return {
                        value: items.nev,
                        label: items.nev
                    }
                }));
            },
            error: function (error) {}
        });
    },
    focus: function (event, ui) {
        var $elem = event.target,
            $egysegar;
        $.ajax({
            url: "/backend/termekek-query.php",
            type: "POST",
            data: {
                "term": ui.item.value
            },
            success: function (data) {
                $egysegar = data.egysegar;
                $($elem).parent().parent('.ujtermek_wrapper').find('td.egysegar').text($egysegar);
            }
        });

    }
});

And here's the pretty simple PHP file it sends the request to:

<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    if(isset($_POST["term"]) && !empty($_POST["term"])) {
        require_once "../includes/constants.php";
        require '../includes/class.db.php';
        $searchTerm = trim($_POST["term"]);

        $db = new db(CONNECTION_STRING, DATABASE_USERNAME, DATABASE_PASSWORD);

        $bind = array(
            ":term" => "%$searchTerm%"
        );

        $results = $db->select(TERMEKEK_TABLE, "nev LIKE :term", $bind, "nev, egysegar");

        echo json_encode($results);
    }
}
?>

Note that I'm also using a PDO wrapper class, but that's irrelevant right now.

Anyway, is there any way to make this cleaner?


texts:
This is the batch file I have created which zips the particular month logs and deletes those logs from the source folder after successful zipping. If it does not find the zip file, then it again starts to zip the logs.

Please suggest any changes to be done.

@echo off

set zip="C:\Program Files\7-Zip\7z.exe"
rem Findout Month, Year and Date
FOR /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do set year=%%D
FOR /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do set month=%%B
FOR /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do set day=%%C

rem Solve problem Year start and adding 0 in month
if %month% EQU 01 (
    set month=12
    set /a year=%year%-1
) else (
    set /a month=%month%-1
)
if %month% LSS 10 set month=0%month%

rem Set file names for last month file.
set lastmonthfiles=server.log.%year%-%month%-
rem To compress the file.
:compress
%zip% -tzip  a -y "bkp-%lastmonthfiles%.zip" %lastmonthfiles%*
ping -n 5 192.168.100.44 > nul
if Not exist bkp-%lastmonthfiles%.zip (
    echo zipping failed
    pause
) else (
 DEL %lastmonthfiles%*

 )
pause


texts: Refactoring the legacy code which is using '§' char in the code

texts:
I have a legacy code (might be 20 years old) as shown below. Where they are using the non ASCII '§' char in the code.
First they are preparing a SELECT query and the SELECT query looks like this...

SELECT 'ERROR_ID=§' || ERROR_ID ||  '§'  || ' AND ' ||  'DAT=:' || ...

They are using below code while preparing the SELECT query.
    strcat(query, "§" );

From the SELECT query result which still contains the '§', they are doing comparision as shown below and if '§' char is present in the char array, they are replacing it with single quotes.
Since they are using the non ASCII char '§' in the code, I have been repoted an issue where the '§' is not getting replaced with single quotes and they
are appearing as question marks '?' in the log file. Below is the code where they are doing the replace

len_before=strlen(file_str);
k=l=end=0;
while(end==0)
{
    if(file_str[k] == '\'')
    {
        strcpy( result,(char*)&file_str[k]);
        file_str[k] = '\'';
        strcpy((char*)&file_str[k+1],result);
        k++;
    }
    else
    {
        if((char)file_str[k]=='§') // Replace '§' by single quotes.
        {
            strncpy((char*)&file_str[k],"'",1);
        }
    }
    k++;
    l++;
    if(l>len_before)
        end=1;
};

So I am refactoring the code to not to use the non ASCII char '§' with sequence of chars as say ("!-!") for preparing the SELECT query as shown.

strcat(query, "!-!" );

And the result from the SELECT query I have to replace this sequence of chars ("!-!") with single quotes. Below is the refactored code...

string replaceAll(string inputString, string stringToFind, string stringToReplace)
{
    int found = inputString.find(stringToFind);
    while (found != string::npos)
    {
        inputString.replace(found, stringToFind.length(), stringToReplace);
        found = inputString.find(stringToFind, found + stringToReplace.length());
    }
    return inputString;
}

{
    // First replace every occurance of single quotes with double single quotes.
    string myString(file_str);
    myString = replaceAll(myString, "\'", "\'\'");

    // Replace the sequence of chars "!-!" with single quotes.
    myString = replaceAll(myString, "!-!", "\'");
}

Questions:

I would like to know if there are any pit falls which I need to look after?
Which sequence of chars can be used instead of "!-!"?
Is there any significane of char '§' (I believe that code is using '§' as a delimiter)in the code since they are connecting to the DB and fetching the data?


texts: Implement a boto3 RDS generator in Python

texts:
Boto3 does not seem to implement a generator for RDS instances, instead offering a marker and pagination feature. This code does work for my use case and I have been using it for the entire day without any problems; however, to me, not returning anything in a while True loop seems magically dangerous, it works but leaving it here for general criticism, it is also the first time I implement a generator in python and feel a little insecure about it.

def all_rds_instances(config):
    """
    Gets all the RDS instances in a generator (lazy iterator) so you can implement it as:
    `for instance in all_rds_instances(config):`
    """
    marker = ""
    client = boto3.client('rds', region_name=config["region"])
    pool = []

    # min 20, max 100
    page_size = 20
    while True:
        if len(pool) < 1:
            if marker is None:
                break
            # populate a local pool of instances
            result = client.describe_db_instances(MaxRecords=page_size, Marker=marker)
            marker = result.get("Marker")
            pool = result.get("DBInstances")

        if len(pool) > 0:
            this_instance = pool.pop()
            yield this_instance

A sample implementation follows:

for instance in all_rds_instances({"region": "eu-west-1"}):
    print instance["Endpoint"]["Address"]


texts: What should I do to reduce run time of my code?

texts:
This is a URI online judge problem (problem no: 1973).
Link : https://www.urionlinejudge.com.br/judge/en/problems/view/1973

  After buying many adjacent farms at the west region of Santa Catarina,
  the Star family built a single road which passes by all farms in
  sequence. The first farm of the sequence was named Star 1, the second
  Star 2, and so on. However, the brother who lives in Star 1 has got
  mad and decided to make a Star Trek in order to steal sheep from the
  proprieties of his siblings. But he is definitely crazy. When passes
  by the farm Star i, he steals only one sheep (if there is any) from
  that farm and moves on either to Star i + 1 or Star i - 1, depending
  on whether the number of sheep in Star i was, respectively, odd or
  even. If there is not the Star to which he wants to go, he halts his
  trek. The mad brother starts his Star Trek in Star 1, stealing a sheep
  from his own farm.

  Input

  The first input line consists of a single integer N (1 ≤ N ≤ 10⁶),
  which represents the number of Stars. The second input line consists
  of N integers, such that the ith integer, Xi (1 ≤ Xi ≤ 10⁶),
  represents the initial number of sheep in Star i.

  Output

  Output a line containing two integers, so that the first represents
  the number of Stars attacked by the mad brother and the second
  represents the total number of non-stolen sheep.

Sample Input          Sample Output
8                     8 68
1 3 5 7 11 13 17 19

8                     7 63
1 3 5 7 11 13 16 19

I have solved the problem with two ways and they also give the desired output, but every time I submitted it it says time limit exceeded.

#1st solution:
num_star = int(input())
sheep = list(map(int, input().split()))
star = set()
index = 0

while index != num_star:
    if sheep[index] == 0:
        break
    elif sheep[index] % 2 == 1:
        star.add(index)
        sheep[index] -= 1
        index += 1
    else:
        star.add(index)
        sheep[index] -= 1
        index -= 1
        if index == -1:
            break

print(len(star), sum(sheep))

#2nd solution
n = int(input())
x = list(map(int, input().split()))
i = 0
farm_visited = 0
while i in range(n):
    if x[i] == 0:
        if i >= farm_visited: farm_visited = i+1
        break
    elif (x[i]) % 2 == 1:
        if i >= farm_visited: farm_visited = i + 1
        x[i] -= 1
        i += 1
    else:
        if i >= farm_visited: farm_visited = i + 1
        x[i] -= 1
        i -= 1
print(farm_visited, sum(x))


texts: Move last node of the linked list to the front

texts:
Description:

Given a linked list move the last node to the front.

For example:

  10 20 30 40 -> 40 10 20 30

Code:

class Main {
  static class Node {
    private int data;
    private Node next;

    Node(int data, Node next) {
      this.data = data;
      this.next = next;
    }

    Node append(int data) {
      Node newNode = new Node(data, null);
      Node current = this;

      while (current.next != null) {
        current = current.next;
      }
      current.next = newNode;
      return this;
    }

    public String toString() {
      Node current = this;
      StringBuilder sb = new StringBuilder();

      while (current != null) {
        // do something here
        sb.append(current.data);
        sb.append(" ");
        current = current.next;
      }
      return sb.toString();
    }
  }

  public static Node moveTailToHead(Node head) {
    if (head == null || head.next == null) {
      throw new IllegalStateException(
          "List should have atleast two elements");
    }

    Node current = head;
    Node prev = null;

    while (current.next != null) {
      prev = current;
      current = current.next;
    }
    prev.next = null;
    current.next = head;
    head = current;

    return head;
  }

  public static void main(String[] args) {
    Node head = new Node(10, null);
    head.append(20)
        .append(30)
        .append(40);
    System.out.println(head); // 10 20 30 40

    Node newHead = moveTailToHead(head);
    System.out.println(newHead); // 40 10 20 30

    try {
      System.out.println(
        "Should not happen: " + moveTailToHead(null));
    } catch (IllegalStateException e) {
      System.out.println(
        "Got expected exception for null node");
    }

    try {
      System.out.println(
        "Should not happen: " + moveTailToHead(new Node(10, null)));
    } catch (IllegalStateException e) {
      System.out.println(
        "Got expected exception for single node");
    }
  }
}

Question:

I am writing code in Java after a long time and would like to know if I am making any mistake or abusing any feature of Java.


texts: jQuery-like library for learning purposes

texts:
I am attempting to build a small JavaScript library (similar to jQuery)

The purpose behind this is mostly a learning exercise, so asking why I don't just use an existing library is moot.

So far I have just got my basic constructor, a 'caller' function to invoke a new object, and some basic functions for an example.

var lemon = function() {
    var prop = {
        collection: []
    };
    var fn = {
        init: function(selector, context) {
            context = context || document;
            if (!selector) {
                return;
            } else if (typeof selector == "string") {
                prop.collection = fn.toArray(context.querySelectorAll(selector));
            } else if (selector instanceof Array || selector instanceof NodeList) {
                fn.toArray(selector).forEach(function(obj) {
                    prop.collection.push(obj);
                });
            } else if (selector instanceof Element) {
                prop.collection.push(selector);
            }
            prop.length = prop.collection.length;
            fn.extend.apply(this, [this, prop, fn]);
        },
        toArray: function(target) {
            var array = [];
            for (var i = target.length >>> 0; i--;) {
                array[i] = target[i];
            }
            return array;
        },
        extend: function(target) {
            var objects = Array.prototype.slice.call(arguments, 1);
            objects.forEach(function(obj) {
                var props = Object.getOwnPropertyNames(obj);
                props.forEach(function(key) {
                    target[key] = obj[key];
                });
            });
            return target;
        },
        addClass: function(klass) {
            for (var i = 0, l = this.length; i < l; i++) {
                this.collection[i].className += " " + klass;
            }
            return this;
        }
    };
    fn.init.apply(this, fn.toArray(arguments));
};
var $ = function(selector, context) {
    return new lemon(selector, context);
};


texts: How can I optimize this Java 2D Array BFS?

texts:
This is a Google foobar question. The gist of it is that I have to find the shortest path from top left to bottom right in a 2d array of 1's and 0's, where I can only traverse on 0's. However, the twist is that I can change one 1 to a 0. My code works for the first three test cases, but it fails the final two (not sure if it's an edge case or it's pure inefficiency).
My current solution is to test every possible array (switch every possible 1 to a 0) and then run BFS on each one.
How can I optimize my code further? Thanks! If you want, here's the full text of the problem.
import java.lang.Integer;
import java.lang.String;
import java.util.Arrays;
import java.lang.Math;
import java.util.LinkedList;
import java.util.Queue;

public class Solution {

    public static void main (String[] args)
    {
        int[][]x = {{0, 1, 1, 0}, {0, 0, 0, 1}, {1, 1, 0, 0}, {1, 1, 1, 0}};
        System.out.println(solution(x));
    }

    public static int solution(int[][] map) {
        int w = map[0].length;
        int h = map.length;
        if(w==1&h==1)
            return 1;
        int[][] m = map;
        int min = minPath(m,w,h);
        //System.out.println(min);
        for (int i = 0; i<w; i++)
        {
            for (int j = 0; j<h;j++)
            {
                if(m[j][i]==1)
                {
                    m[j][i] = 0;
                    min = Math.min(min, minPath(m,w,h));
                    if(min==w+h-1)
                        return min;
                    m[j][i] = 1;
                }

            }
        }
        return min;
    }

    public static int minPath(int[][]m, int w, int h)
    {
        int[][] d = new int[h][w];
        d[0][0] = 1;
        Queue<String> q = new LinkedList<>();
        q.add(0 + "," + 0);

        while(!q.isEmpty())
        {
            String x = q.remove();
            int i = Integer.parseInt(x.split(",")[0]);
            int j = Integer.parseInt(x.split(",")[1]);
            if (i==h-2&&j==w-1 || i==h-1&&j==w-2)
                return ++d[i][j];
            if(i>1&&d[i-1][j]==0&&m[i-1][j]==0)
            {
                d[i-1][j] = d[i][j] + 1;
                q.add(i-1+","+j);
            }
            if(j>1&&d[i][j-1]==0&&m[i][j-1]==0)
            {
                d[i][j-1] = d[i][j] + 1;
                q.add(i+","+(j-1));
            }
            if(i<h-1&&d[i+1][j]==0&&m[i+1][j]==0)
            {
                d[i+1][j] = d[i][j] + 1;
                q.add(i+1+","+j);
            }
            if(j<w-1&&d[i][j+1]==0&&m[i][j+1]==0)
            {
                d[i][j+1] = d[i][j] + 1;
                q.add(i+","+(j+1));
            }
        }
        return 1600;

    }

}


texts: Unit testing extension for equality testing

texts:
I have created an extension for unit-testing my own equality implementations.
Is it a good approach in general to have such extensions for unit testing?
What unit-testing extensions do you use?

public static class EqualityExtensions
    {
        /// <summary>
        /// Checks that all variations Equals method conforms to equality by properties
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="variations"></param>
        /// <param name="propertyAccessors">Property accessors specifying which properties contribute to equality</param>
        /// <returns>True, if all instances from a set conform to property equality</returns>
        /// <example>
        /// Assert.IsTrue(from name in new[] {"foo","bar"} from count in new[] {1,2} select new MyClass{Name=name,Count=count}).ConformToPropertyEquality(x=>x.Name,x=>x.Count))
        /// </example>
        public static bool ConformToPropertyEquality<T>(this IEnumerable<T> variations, params Func<T, object>[] propertyAccessors)
        {
            var propertyComparisions =
                from lhs in variations
                from rhs in variations
                select
                    Equals(
                        (from comparator in propertyAccessors select Equals(comparator(lhs), comparator(rhs))).All(c => c),
                        Equals(lhs, rhs)
                    );

            return propertyComparisions.All(p => p);
        }
    }


texts: Calling Eigen library to do the linear operation of the matrix

texts:
I am a rookie of coding and I have written a c++ procedure which calls the Eigen library to do the linear operation of the matrix. Please help me to improve the efficiency of the loop.

#include <iostream>
#include <fstream>
#include <Eigen/Dense>
#include <time.h>
using namespace std;

int main()
{
    // Weight coefficient matrix
    Eigen::MatrixXd wi_1,wi_2,wi_3,wi_4;
    wi_1.resize(100,2);
    wi_2.resize(100,100);
    wi_3.resize(100,100);
    wi_4.resize(5,100);
    wi_1.setOnes();
    wi_2.setOnes();
    wi_3.setOnes();
    wi_4.setOnes();

    // Bias vector
    Eigen::VectorXd bias_1,bias_2,bias_3,bias_4,Y;
    bias_1.resize(100);
    bias_2.resize(100);
    bias_3.resize(100);
    bias_4.resize(5);
    bias_1.setOnes();
    bias_2.setOnes();
    bias_3.setOnes();
    bias_4.setOnes();
    Eigen::Matrix<double,5,1> y_mean;
    Eigen::Matrix<double,5,1> y_scale;
    Eigen::Matrix<double,2,1> x_mean;
    Eigen::Matrix<double,2,1> x_scale;

    y_mean.setOnes();
    y_scale.setOnes();
    y_mean.setOnes();
    x_scale.setOnes();

    int n = 0;
    int layer;
    clock_t start,finish;
    double totaltime;
    start=clock();
    while (n<10000)
    {
        Y.resize(2);
        layer = 0;
        Y << 0.185, 0.285;//inputx[1], x[0];
        Y = (Y.array() - x_mean.array()) / x_scale.array();

        //ANN forward
        while (layer < 4)
        {
            layer++;
            switch (layer) {
            case 1:{
                Y = wi_1 * Y + bias_1;
                //                                        Info << "ANN forward layer1" << endl;
                break;
            }
            case 2:{
                Y = wi_2 * Y + bias_2;
                //                                        Info << "ANN forward layer2" << endl;
                break;
            }
            case 3:{
                Y = wi_3 * Y + bias_3;
                //                                        Info << "ANN forward layer3" << endl;
                break;
            }
            case 4:{
                Y = wi_4 * Y + bias_4;
                //                                        Info << "ANN forward layer4" << endl;
                break;
            }
            default:{
                cout<<"error"<<endl;
                break;
            }
            }

            //Relu activation function
            if (layer < 4)
            {
                for (int i = 0; i < Y.size(); i++)
                {
                    Y(i) = ((Y(i) > 0) ? Y(i) : 0);
                }
            }
        }
        //inverse standardization
        Y = Y.array() * y_scale.array() + y_mean.array();
        n++;
    }
    finish=clock();
    totaltime=(double)(finish-start)/CLOCKS_PER_SEC*1000;
    cout<<"\n Running time is "<<totaltime<<"ms！"<<endl;
}


texts:
For my current project, I have elected to represent database rows as objects.

So an individual comment can be retrieved as a class like so:

$comment = new Comment(1);

Here is the Comment class code:

<?php
class Comment
{

    private $userid, $postid, $content, $date, $name, $ip, $legacy;

    public function __construct($comment_id)
    {
            $sql = new mysqli(REGISTRY_DBVALUES_SERVER, REGISTRY_DBVALUES_USERNAME, REGISTRY_DBVALUES_PASSWORD, REGISTRY_DBVALUES_DATABASE);

            $stmt = $sql->prepare("SELECT id, userid, postid, content, date, name, ip, legacy
                                   FROM ".SITE_TABLE_COMMENTS."
                                   WHERE id = ?");

            $stmt->bind_param("i", $comment_id);
            $stmt->bind_result($id, $userid, $postid, $content, $date, $name, $ip, $legacy);

            $stmt->execute();

            while($row = $stmt->fetch())
            {
                    $this->userid = $userid;
                    $this->postid = $postid;
                    $this->content = $content;
                    $this->date = $date;
                    $this->name = $name;
                    $this->ip = $ip;
                    $this->legacy = $legacy;
            }

            $stmt->free_result();
            $sql->close();
    }

    public function getUserID()
    {
            return $this->userid;
    }

    public function getPostID()
    {
            return $this->postid;
    }

    public function getContent()
    {
            return $this->content;
    }

    public function getDate()
    {
            return $this->date;
    }

    public function getName()
    {
            return $this->name;
    }

    public function getIP()
    {
            return $this->ip;
    }

    public function getLegacy()
    {
            return $this->legacy;
    }
}
?>

This allows you to retrieve the different attribute values for an individual comment using methods.

I am open to criticism on all aspects of the design, but was particularly curious if this is an accepted way of handling retrieval of individual data records?


texts: Hashing 2 strings to an int and adding to HashMap

texts:
I am trying to use an algorithm similar to the Apriori algorithm for discovering frequent itemsets. This program hashes 2 strings to an int and maps them in the HashMap. I'm not concerned with how good the hashing algorithm is but whether or not it is a good attempt at my own implementation of counting frequent item sets using the Triples counting method.

package hashTest;
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
public class TriplesCount {
public static void main(String[] args)
{
    String testSentence = "Facebook is looking good. Facebook is looking horrible.";

    Map<Integer, Integer> triplesCount = new HashMap<Integer, Integer>();

      String stripPunctuation = testSentence.replaceAll("\\.", "");
      //out.println(stripPunctuation);

      String[] wordArray = stripPunctuation.split(" ");
    List<String> wordList = new ArrayList<String>();
      for(int a=0; a<wordArray.length; a++)
          wordList.add(wordArray[a]);

      //Lists of "good" and "bad" words. If a word in testSentence matches one of these, it will be added to the
      List<String> goodWords = new ArrayList<String>();
      List<String> badWords = new ArrayList<String>();

      goodWords.add("good");goodWords.add("increase");goodWords.add("excellent");goodWords.add("partnering");goodWords.add("bullish");goodWords.add("better");
      badWords.add("bad");badWords.add("problem");badWords.add("drop");badWords.add("bearish");badWords.add("worse");badWords.add("horrible");

      for(int i=0; i<wordList.size(); i++)
      {
          System.out.println("Checking: " + wordList.get(i));

          for(int i2=0; i2< goodWords.size(); i2++)
          {
              if(goodWords.get(i2).equals(wordList.get(i)))
                  triplesCount = addToMap("facebook", goodWords.get(i2), triplesCount);

              if(badWords.get(i2).equals(wordList.get(i)))
                  triplesCount = addToMap("facebook", badWords.get(i2), triplesCount);

              System.out.println(triplesCount);
          }

      }

}

  public static Map<Integer,Integer> addToMap(String stock, String adjective, Map<Integer,Integer> triplesCount)
  {
      int hash=11;
      String key = (stock+":"+adjective).toLowerCase();
      char[] charsArray = key.toCharArray();
      for(int a=0; a<charsArray.length; a++)
          hash = hash*31 + a-charsArray[a]; //multiplies 2 prime #s and adds an int value for the character

      //now have to set the stock + adjective string to the index of hash, and set the value to the count of how many times that combo has occurred
      if(triplesCount.get(hash) == null)
          triplesCount.put(hash, 1);
      else
          triplesCount.put(hash, triplesCount.get(hash)+1);
      return triplesCount;
  }
}


texts: Time table where workers overstay past midnight

texts:
My input data comes in the following tabular table:

With this, I make a basic time table where I record arrival hour, leaving hour and total work hours.

Problem is, I can't do it with a simple pivot table because sometimes people will stay past midnight, so if I just get the MIN(Time) I'll sometimes get that the employee arrived at 1am. Another issue is I need to use the STATE to determine if it's a user arriving or leaving (denoted by "* Entrada" for arrivals and "* Salida" for leavers).

To work with this, I arbitrarily decided that the corresponding work day starts at 6am, so first I defined the following named ranges:

tblState: =OFFSET(data!$A$1,1,MATCH("STATE",data!$1:$1,0)-1,COUNTA(data!$A:$A)-1)
tblDate: =OFFSET(data!$A$2,0,0,COUNTA(data!$A:$A)-1)
tblName: =OFFSET(data!$A$1,1,MATCH("NAME",data!$1:$1,0)-1,COUNTA(data!$A:$A)-1)

And then my working formulas are

Arrived:

{=MAX((MIN(IF(((tblName=$B10)*(tblDate>(D$8+0.25))*(RIGHT(tblState,7)="Entrada")*(WEEKDAY(D$8,2)<6)*(tblDate<(D$8+1)))>0,tblDate))-D$8),0)}

Left:

{=MAX((MAX(IF(((tblName=$B10)*(tblDate<(D$8+1.25))*(tblDate>(D$8+0.25))*(RIGHT(tblState,6)="Salida"))>0,tblDate))-D$8),0)}

Hours (I do this to take care of negatives and to substract the lunch hour from the working hours if the employee worked more than a half shift):

=MAX((IF(OR(D10=0,D11=0),0,IF((D11-D10)<(4/24),D11-D10,MAX(D11-D10-(1/24),0)))),0)

It is incredibly inelegant and inefficient — it takes about 5 mins to calculate with ~25k records on my data table.

Another issue is that for the next month, I have to manually check for new records on the data table (add new employees to the time table) and missing records (remove employees who no longer work for the company), though I figure I could easily take care of this with a macro.

What would be a more efficient alternative?


texts:
I've the following scenario, I've got some viewmodel that need to persist their  state on disk.

I've defined a custom attribute as:

[AttributeUsage(AttributeTargets.Property)]
public class FilterPesistableAttribute : Attribute
{
    public string NestedProperty { get; set; }
}

This attribute is put on the properties as you can see in the following Nunit test (you can copy and try it if you want):

  public class SavingFilterAttributeTests
  {
    [Test]
    public void TestSaveState()
    {
        var dummy = new Dummy();

        dummy.ID = 4;
        dummy.Nested = new Nested
        {NestedPropery = "Test", Inner = new Inner() {ID = 69}};
        Stopwatch sw = Stopwatch.StartNew();

        var result =  ViewModelStatePersistenceHelper.SaveState(dummy);

        sw.Stop();

        Console.WriteLine(sw.Elapsed);
    }

}

public class Dummy
{
    [FilterPesistable]
    public  int ID { get; set; }
    [FilterPesistable(NestedProperty = "Inner.ID")]
    public Nested Nested { get; set; }

    public Dummy()
    {
        Nested = new Nested();
    }
}

public class Nested
{
    public string NestedPropery
    {
        get; set;
    }

    public Inner Inner { get; set; }

    public Nested()
    {
        Inner = new Inner();
    }
}

public class Inner
{
    public  int ID { get; set; }
}

The method I need help on is the following:

  public static Dictionary<string, object> SaveState(object viewmodel)
    {
        if (viewmodel == null) return null;
        var res = new Dictionary<string, object>();

        var attributes = viewmodel.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(FilterPesistableAttribute)));

        var propertyInfos = attributes as IList<PropertyInfo> ?? attributes.ToList();

        if (propertyInfos.Any())
        {
            propertyInfos.ForEach(x =>
            {
                var value = x.GetValue(viewmodel, null);

                if (value == null) return;
                if (value.GetType().IsPrimitive)
                {
                    res.Add(x.Name, value);
                }
                else
                {
                    var attributes2 =
                        x.GetCustomAttributes(typeof(FilterPesistableAttribute), true) as
                            IList<FilterPesistableAttribute>;

                    var attribute = attributes2.FirstOrDefault();

                    if (attribute == null) return;
                    var a = GetPropertyValue(value, attribute.NestedProperty);
                    res.Add(attribute.NestedProperty, a);
                }
            });
        }
        return res;
    }

 public static class IEnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
    {
        foreach (T item in collection)
        {
            action(item);
        }
    }
}

I wish to make this more performant and elegant.


texts: Algorithm optimisation to get first parent with specific kind of class

texts:
I am writing an extension for UIViewController to search all the parents and return a specific parent which is a kind of specific class. here is my try :

extension UIViewController {

    var rootViewController : RootViewController? {
        var parentController: UIViewController? = parent
        while let currentParent = parentController {
            if (currentParent is RootViewController) {
                return (currentParent as? RootViewController)!
            }
            else if let parentOfParent = currentParent.parent, parentOfParent != currentParent {
                parentController = parentOfParent
            }
            else {
                parentController = nil
            }
        }
        return nil
    }

}

Is there a better approach to solve the issue, maybe a recursive way to handle that. And if it's better in term of performance.


texts: Haskell Listing Directories in Working Directory

texts:
I've got this fairly simple program to print out each subdirectory of the working dir.

import System.Directory (listDirectory, doesDirectoryExist)

main = do
    dirs <- getDirectories
    mapM_ putStrLn dirs

-- Get a list of directories within the working directory
getDirectories :: IO [FilePath]
getDirectories = do
    contents <- listDirectory "."
    fIO doesDirectoryExist contents

-- Filter a list with an IO predicate.
-- (In this use case, queries file system for directory status.)
fIO :: (a -> IO Bool) -> [a] -> IO [a]
fIO f [] = return []
fIO f (x:xs) = do
    matches <- f x
    rest <- fIO f xs
    return $ (if matches then [x] else []) ++ rest

I also attempted this implementation of the fIO function, and I'm not sure if it's legitimately less clear or if it only appears that way to me because I'm not used to reading Haskell-style syntax yet.

fIO f (x:xs) = do
    matches <- f x
    fIO f xs >>= return . ((if matches then [x] else []) ++)

Critique Request

Being a Haskell newbie, I'm sure a professional would change some things about this implementation. I'm curious what sticks out as awkward, non-idiomatic, or opaque. I'm also curious which implementation of the two fIOs (if either) you would select, and why.


texts: Prime Number Generator Time Limit Exceeded

texts:
PRIME1- Prime Generator
The code is working fine and it's generating a prime number from  M to N but the only problem is I'm getting TLE when I submit my answer. How do I optimise my code to pass the time limit?

  number-theory

  Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given
  numbers!

  Input

  The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1
  <= m <= n <= 1000000000, n-m<=100000) separated by a space.

  Output

  For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

  Example

  Input:
   2

  1 10

  3 5

  Output:

  2
  3
  5
  7

  3
  5

  Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed)

Time limit:  6s

Source limit:    50000B

Memory limit:    1536MB

#include <iostream>
#include <math.h>
#include <vector>

int main() {
int T;
uint64_t m, n;
std::scanf("%d", &T);
while (T--) {
    std::scanf("%llu %llu", &m, &n);

    std::vector<bool> flags(n+1);
    std::fill(flags.begin(),flags.end(),true);

    if (m == 1) {
        m++;
    }
    double halfMax = ceil(sqrt(n));
    for (uint64_t i = 2; i <= halfMax; ++i) {

        if (flags[i]) {
            for (uint64_t j = i * 2; j <= n; j += i) {
                flags[j] = false;
            }

        }
    }

    for (uint64_t k = m ; k <= n; ++k) {
        if (flags[k]) {
            printf("%lld", k);
            printf(" ");
        }

     }
     printf("\n");
   }
}


texts: DFS on a binary tree: marking nodes as visited

texts:
I wanted to write depth first search reversal iteratively in Java. Can someone review my code? I'm not that much interested in naming of the variables, but in the structure of the code, i.e. I don't need to mark the nodes as visited when I traverse binary tree, right?

public static void dfs(TreeNode root){
        if(root == null)    return;
        Stack<TreeNode> res = new Stack<TreeNode>();
        res.push(root);
        while(!res.isEmpty()){
            TreeNode top = res.pop();
            System.out.print(top.val + " ");
            if(top.right != null)
                res.push(top.right);
            if(top.left!= null)
                res.push(top.left);
        }
    }

Recursive version:

public static void dfs(TreeNode root){
        if(root == null)    return;
        System.out.print(root.val + " ");
        dfs(root.left);
        dfs(root.right);
    }


texts: Random String Generator using OpenSSL in PHP

texts:
function GenerateRandomString($Length) {
 $Length /= 2;
 $cstrong = false;
 while ($cstrong != TRUE){
    $bytes = openssl_random_pseudo_bytes($Length, $cstrong);
 }
 $hex = bin2hex($bytes);
 return $hex;
}

Is this a good function for generating a cryptographically secure random string? Is there a chance, that it'll get into an infinite loop, because $cstrong stays 'False'?


texts: Makefile for C++ project - dependency generation

texts:
I would like some input on the Makefile I'm using for my C++ project. It is my first Makefile and I learned how to do what I want through various readings on the web. The directory structure is as follows :

project directory
|___ src/ (source files)
|___ include/ (header files)
|___ tests/ (source files each containing "int main(int argc, char **argv)"
|___ build/ (object files and dependency files)
|___ bin/ (compiled programs)
|___ Makefile

The main reason I'm asking for input is that recently I did some changes, including adding a member to one of my classes and this caused my program to crash with segfaults ; it turns out that doing a make clean and recompiling from scratch resolved the problem as explained in this answer.

Apparently the automatic dependency generation failed in some way and some parts of my program were not recompiled when I changed the header... At least that is what I understand. So if the dependency generation (g++ -MMD) is not done right I would like to know how to improve it. Here is the Makefile :

# Makefile

# Compiler
CXX      := -g++
# Compiler flags
CXXFLAGS := -pedantic-errors -Wall -Wextra -std=c++17 -g -O0

# Library flags
LDFLAGS  := -L/usr/lib -lstdc++ -lm
# Librairy flags for petsc
LDFLAGS_PETSC = ... # long list of library flags
LDFLAGS += $(LDFLAGS_PETSC)

# List of include directories
# use -isystem to supress warnings for this folder
INCLUDE := -Iinclude/ -isysteminclude/lepton/ -Iinclude/gauss-legendre-quadrature/
INCLUDE_PETSC := -I/home/intendant/software/petsc/include \
                 -I/home/intendant/software/petsc/arch-linux2-cxx-debug/include
INCLUDE += $(INCLUDE_PETSC)
# Include boost if downloaded from boost.org instead of installed through apt-get
# INCLUDE_BOOST := -I/opt/boost_1_67_0/
# INCLUDE += $(INCLUDE_BOOST)

# List of source files
SRC_DIR := src
SOURCES := $(wildcard $(SRC_DIR)/*.cpp) \
           $(wildcard $(SRC_DIR)/lepton/*.cpp) \
           $(wildcard $(SRC_DIR)/gauss-legendre-quadrature/*.cpp)
# NOTE: gauss_legendre renamed from .c to .cpp after download

# List of source files for tests and mains
MAIN_DIR := tests
MAIN_SOURCES = $(wildcard $(MAIN_DIR)/*.cpp)

# List of executables
TARGET_DIR := bin
TARGETS = $(MAIN_SOURCES:$(MAIN_DIR)/%.cpp=$(TARGET_DIR)/%.out)
TARGET_NAMES = $(MAIN_SOURCES:$(MAIN_DIR)/%.cpp=%)

# List of objects files for src/ and tests/ files
OBJ_DIR  := build
OBJECTS  := $(SOURCES:$(SRC_DIR)/%.cpp=$(OBJ_DIR)/%.o)
MAIN_OBJECTS := $(MAIN_SOURCES:$(MAIN_DIR)/%.cpp=$(OBJ_DIR)/%.o)

# Create variable containing list of dependencies (generated by gcc)
DEP = $(OBJECTS:%.o=%.d)

# Remove warnings when building lepton library
build/lepton/%.o: CXXFLAGS += -w

# Default target should be cfm
main: build $(TARGET_DIR)/cfm.out
# Build all executables
all: build $(TARGETS)

# Include all .d files
-include $(DEP)

# Make object files from source files (-MMD generates dependencies .d files)
$(OBJECTS): $(OBJ_DIR)/%.o : $(SRC_DIR)/%.cpp
    @mkdir -p $(@D)
    $(CXX) $(CXXFLAGS) $(INCLUDE) -MMD -o $@ -c $<

# Make object files from main source files (-MMD generates dependencies .d files)
$(MAIN_OBJECTS): $(OBJ_DIR)/%.o : $(MAIN_DIR)/%.cpp
    @mkdir -p $(@D)
    $(CXX) $(CXXFLAGS) $(INCLUDE) -MMD -o $@ -c $<

# Link object files with appropriate main to create app
$(TARGETS): $(TARGET_DIR)/%.out: $(OBJ_DIR)/%.o $(OBJECTS)
    @mkdir -p $(@D)
    @echo "Linking "$@"..."
    @$(CXX) $(CXXFLAGS) $(INCLUDE) -o $@ $^ $(LDFLAGS)

# Convenience rule to type "make program" instead of "make bin/program.out"
$(TARGET_NAMES): %: $(TARGET_DIR)/%.out

.PHONY: all build clean debug release main $(TARGET_NAMES)

build:
    @mkdir -p $(TARGET_DIR)
    @mkdir -p $(OBJ_DIR)

debug: CXXFLAGS += -DDEBUG -g  -O0
debug: all

release: CXXFLAGS += -O2
release: all

clean:
    -@rm -rf $(OBJ_DIR)/*
    -@rm -rf $(TARGET_DIR)/*


texts: Creating a grid to the specified size using lists

texts:
My code creates a "grid" of empty places, where 0 is used as the place holder, in a size specified by the user.

I was wondering if there were more efficient ways of doing this,or perhaps ways that make more aesthetically pleasing grids with less code.

My code is in working order and does as it says on the label, I also implemented a system that does not allow for incorrect inputs.

def gridSize_def():
    global gridSize
    while True:
        try:
            gridSize = int(input("input grid length and width\n"))
            if gridSize<2:
                print ("invalid int")
            else:
                break
        except ValueError:
            print ("invalid input")
    grids = [[] for _ in range (gridSize)]
    for i in range(0,gridSize):
        grids[i-1]=[0 for _ in range(gridSize)]
    return grids

def grid_def():
    for i in range (0,gridSize):
        print (grids[i-1])

grids = gridSize_def()
grid_def()

All feedback welcome!


texts: Dynamically changing autocomplete source option jQuery

texts:
In this scenario I've got a textbox to which I have added autocomplete functionality.  The kicker is that I want to dynamically change the source option of the AJAX call based on the value of a dropdown list.  To do this I encapsulated the differences between the AJAX calls in an object of type Resolver. The name property of the Resolver object is the same as the text value coming from the dropdown list.  I was looking for a way to make this a little cleaner.  The code works, just looking for more extensible options as the project grows.

$(document).ready(function ()
    {
        //encapsulate the URL of the AJAX call
        //the name property maps to a dropdown list value
        //so if Drugs is chosen from the dropdown menu we look for the name property which = drugs
        Resolver = function (name, url)
        {
            this.name = name;
            this.url = url;

        }
        Resolver.prototype.resolve = function (request, response)
        {
            $.ajax(
            {
                type: "POST",
                url: "Service.asmx/" + this.url,
                data: JSON.stringify({ 'param': $('#auto').val() }),
                dataType: "json",
                contentType: "application/json",
                success: function (data)
                {
                    response(data.d);
                },
                error: function (xhr)
                {
                    console.log(xhr.status);
                }
            });
        }
        //in the future I expect the Resolver object to have more properties
        //this is the simplest example I could think of
        var drugs = new Resolver('drugs', 'GetDrugNames');
        var hospitals = new Resolver('hospitals', 'GetHospitalNames');
        var resolverArray = [];
        resolverArray.push(drugs);
        resolverArray.push(hospitals);
        //on the change even of the ddl we're looking for the index of the resolverArray
        //which has the name name property as the value selected in the ddl.
        $('#ddl').change(function ()
        {
            var target = $(this).val().toLowerCase();
            var index = 0;
            $.each(resolverArray, function (ix, val)
            {
                if (resolverArray[ix].name == target)
                {
                    index = ix;
                }
            });
            $('#auto').autocomplete(
            {
                source: function (request, response)
                {
                    resolverArray[index].resolve(request, response);
                }
            });

        });
    });


texts:
I have written a script using Beautiful Soup to scrape some HTML and do some stuff and produce HTML back. However, I am not convinced with my code and I am looking for some improvements.

Structure of my source HTML file:

<!DOCTYPE html>

...

...

                    Some Heading 1

                    This section can have p, img, or even div tags

...
...

                    Some Heading

                    This section can have p, img, or even div tags

...

My code:

import re
from bs4 import BeautifulSoup
soup = BeautifulSoup(myhtml)
all_sections = soup.find_all('section',id=re.compile("article-section-[0-9]"))
for section in all_sections:
    heading = str(section.find_all('div',class_="heading")[0].text).strip()
    contents_list = section.find_all('div',class_="content")[0].contents
    content = ''
    for i in contents_list:
        if i != '\n':
            content = content+str(i)
    print '
'+heading+'

'+content+''

My code works perfectly without any issues so far, however, I don't find it pythonic. I believe that it could be done in a much better/simpler way.

Content_list is a list which has items like '\n'. With a loop running over this list, I am removing it.  Is there any better way?
I am not interested in article icon, so I am ignoring it in my script.
I am using strip method to remove extra white spaces in the heading.  Is there any better way?
Other than new lines, the div element within content can have anything, even nested divs. So far, I have run my script over a few pages I have and it seems to work. Anything here I need to take care of?
Lastly, is there any better way to generate HTML files? Once I scraped data, I will work on generating HTML files. These files will have same structure (CSS, JavaScript, etc) and I have to do is put scraped data into it. Can the above method I used (build a string and put content and headings) be improved in any way?

I am not looking for full code in answers; just give me subtle hints or point me in some direction.


texts: removeClass and addClass optimization in a scoring system

texts:
I have scoring system where I want to change icon color by changing CSS classes.

How can I optimize this jQuery? After testing, I found this the only alternative, but I trust there is a more simplified method.

// Count scores
$('#bodyScore').text((90 / myarray.length) * bodyScore + '/90');

// Change icon color
var bodyPercent  = bodyScore / myarray.length;
var successRatio = 0.9;
var warningRatio = 0.5;

if (bodyPercent >= successRatio) {
    $(".bkf").removeClass("label-success");
    $(".bkf").removeClass("label-warning");
    $(".bkf").removeClass("label-important");
    $(".bkf").addClass("label-success");
}

else if (bodyPercent >= warningRatio) {
    $(".bkf").removeClass("label-success");
    $(".bkf").removeClass("label-warning");
    $(".bkf").removeClass("label-important");
    $(".bkf").addClass("label-warning");
}

else {
    $(".bkf").removeClass("label-success");
    $(".bkf").removeClass("label-warning");
    $(".bkf").removeClass("label-important");
    $(".bkf").addClass("label-important");
}


texts:
I've just wrote a program in C# for counting sort.

space complexity is O(N+K)
time complexity is O(N+K)

I want reviews on my code and any better ways to implement this.

namespace SortingSelfCoded
{
    public static class CountingSorter
    {
        public static int[] CountingSort(int [] input)
        {
            // O(1)
           int max = input[0];

            // O(N)
            for (int i = 0; i < input.Length; i++)
            {
               if (input[i] > max)
                {
                    max = input[i];
                }
            }

            // Space complexity O(N+K)
            int[] counts = new int[max + 1];
            int[] output = new int[input.Length];

            // O(N)
            for (int i = 0; i < input.Length; i++)
            {
                counts[input[i]]++;
            }

            int j=0;
            // O(N+K)
            for (int i = 0; i < counts.Length; i++)
            {
                while (counts[i] > 0)
                {
                    output[j] = i;
                    j++;
                    counts[i]--;
                }
            }

            return output;
        }
    }
}


texts:
In this code, I am creating a COM object to programatically access internet explorer. In order to access this object's properties and methods, I am writing wrapper functions like navigate or setVisible.

Is there a cleaner or easier way to use COM objects from C? Moreover, can you point out things that I could have done better?

#include <stdio.h>
#include <windows.h>

HRESULT createIE(LPVOID *pDisp)
{
    CLSID clsid;
    HRESULT hr;
    hr = CLSIDFromProgID(L"InternetExplorer.Application", &clsid);
    if(FAILED(hr)) {
       MessageBox(NULL, "Internet Explorer not registered.", "Error",
                  MB_SETFOREGROUND);
       return hr;
    }

    hr = CoCreateInstance(&clsid, NULL, CLSCTX_LOCAL_SERVER,
                          &IID_IDispatch, pDisp);

    if(FAILED(hr)) {
       MessageBox(NULL, "Couldn't start Internet Explorer.", "Error",
                  MB_SETFOREGROUND);
       return hr;
    }

    return S_OK;
}

HRESULT navigate(IDispatch *pDisp, BSTR *url)
{
    HRESULT hr;
    DISPID dispID;
    VARIANT parm1;

    DISPPARAMS dispParams = { NULL, NULL, 0, 0 };

    LPOLESTR rgszNames[1] = {L"Navigate"};

    pDisp->lpVtbl->GetIDsOfNames(pDisp, &IID_NULL, rgszNames, 1, LOCALE_USER_DEFAULT, &dispID);

    VariantInit(&parm1);
    parm1.vt = VT_BSTR;
    parm1.pbstrVal = url;

    // One argument.
    dispParams.cArgs = 1;
    dispParams.rgvarg = &parm1;

    // Navigate to url
    hr = pDisp->lpVtbl->Invoke(pDisp,
       dispID, &IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD,
       &dispParams, NULL, NULL, NULL
    );

    if (FAILED(hr)) {
       char buf[8192];
       sprintf(buf, "IDispatch::Invoke() failed with %08lx", hr);
       MessageBox(NULL, buf, "Debug Notice", MB_SETFOREGROUND);
       return hr;
    }

    return S_OK;
}

HRESULT setVisible(IDispatch *pDisp, BOOL visibility)
{
    HRESULT hr;
    DISPID dispID;

    DISPPARAMS dispParams = { NULL, NULL, 0, 0 };
    VARIANT parm1;
    DISPID dispidNamed = DISPID_PROPERTYPUT;

    LPOLESTR rgszNames[1] = {L"Visible"};

    pDisp->lpVtbl->GetIDsOfNames(pDisp, &IID_NULL, rgszNames, 1, LOCALE_USER_DEFAULT, &dispID);

    VariantInit(&parm1);
    parm1.vt = VT_I4;
    parm1.lVal = visibility;

    // One argument.
    dispParams.cArgs = 1;
    dispParams.rgvarg = &parm1;

    // Handle special-case for property-puts!
    dispParams.cNamedArgs = 1;
    dispParams.rgdispidNamedArgs = &dispidNamed;

    // Set 'visible' property
    hr = pDisp->lpVtbl->Invoke(pDisp,
       dispID, &IID_NULL, LOCALE_SYSTEM_DEFAULT,
       DISPATCH_PROPERTYPUT | DISPATCH_METHOD,
       &dispParams, NULL, NULL, NULL
    );

    if(FAILED(hr)) {
        char buf[8192];
       sprintf(buf, "IDispatch::Invoke() failed with %08lx", hr);
       MessageBox(NULL, buf, "Debug Notice", MB_SETFOREGROUND);
       return hr;
    }

    return S_OK;
}

void main(void) {
     IDispatch *pDisp; // Main IDispatch pointer.
     HRESULT hr; // General error/result holder.

    // Initialize OLE Libraries.
    OleInitialize(NULL);

    hr = createIE((void **)&pDisp);

    if (FAILED(hr)) {
            return;
    }

    hr = setVisible(pDisp, TRUE);

    if (FAILED(hr)) {
        return;
    }

    BSTR url = SysAllocString(L"www.google.com");
    hr = navigate(pDisp, url);

    if (FAILED(hr)) {
        return;
    }

     // Uninitialize OLE Libraries.
     OleUninitialize();

}


texts:
I am writing a copy paste detector using esprima.js and Hmm.

This particular function checks a number of sequences and reduces them.
Due to the parsing I might have 2 sequences with the same piece of text, if so I need to merge the 2 sequences and add the start/ends ( both are source token indexes ) and occurrences ( contains location of the dupes in the original source ).

Obviously I could apply some DRY to this code, but I feel that every time I start I actually make the code less readable. Also I am not too happy with the naming, is there some good vocabulary out there for comparing sequences what is a good name for sequences[inner] and sequences[outer].

Anyway, all feedback is welcome, though I know that I am on a lonely crusade that ~ is so superior to -1 that I am sticking it to it indefinitely.

  Tokens.prototype.reduceSequences = function()
  {
    var sequences = this.sequences,
        tokens = this.raw();

    if( sequences.length < 2 )
      return;

    for( var outer = 1 ; outer < sequences.length ; outer++)
    {
      for( var inner = 0 ; inner < outer ; inner ++)
      {
        if( sequences[inner].content == sequences[outer].content )
        {

          if( !~sequences[inner].starts.indexOf( sequences[outer].starts[0] ) )
          {
            sequences[inner].starts.push( sequences[outer].starts[0] );
            sequences[inner].ends.push( sequences[outer].starts[0] + sequences[inner].tokenCount );
            sequences[inner].occurences.push( sequences[outer].occurences[0] );
          }

          if( !~sequences[inner].starts.indexOf( sequences[outer].starts[1] ) )
          {
            sequences[inner].starts.push( sequences[outer].starts[1] );
            sequences[inner].ends.push( sequences[outer].starts[1] + sequences[inner].tokenCount );
            sequences[inner].occurences.push( sequences[outer].occurences[1] );
          }

          sequences.splice(outer, 1);
          outer = 0;
          break;
        }
        if( ~sequences[inner].content.indexOf( sequences[outer].content )  )
        {
          sequences.splice(outer, 1);
          outer = 0;
          break;
        }
      }
    }
  }

A use case would be having 5 sequences ( sequences come in sorted by length )

[ 'I'm a sequence'(found on line 1&7) ,
  'I'm a sequence'(found on line 1&9) ,
  'I'm a sequence'(found on line 7&9) ,
  'I'm also a sequence'(found on line 2&3)
  'a sequence'(found on line 1&7) ,
  'a sequence'(found on line 1&9) ,
  'a sequence'(found on line 2&3) ,
]

The outcome would be

[ 'I'm a sequence'(found on line 1&7&9) ,   <-- Note how 9 got added
  'I'm also a sequence'(found on line 2&3)
   <- No more 'a sequence' , it is a substring of the first sequence
]

The algorithm starts taken sequence 1 till the end, and compares to all the prior sequences for dupes and larger sequences.


texts:
The GetDropdownList() function is being called on a couple of controllers based on this example and it may be called in many other controllers, so this code is being repeated. I was thinking of encapsulating this portion of code to the base class and call that base class in these controllers, but I got stuck and don't know how to implement it. Can you please show me a way using SOLID principles?

public interface IDropdownListEntity
{
    string Value { get; set; }
    string Text { get; set; }
}

public sealed class DropdownListEntity: IDropdownListEntity
{
    public string Value { get; set; }
    public string Text { get; set; }
}

public class CountryController : ApiController
{
    //Returns the list of countries
    public IEnumerable<IDropdownListEntity> GetDropdownList()
    {
        CountryStore store = new CountryStore();

        return store.SimpleSortedListByName<DropdownListEntity>();
    }
}

public class CityController : ApiController
{
    //Returns the list of cities
    public IEnumerable<IDropdownListEntity> SortedListForDropdown()
    {
        CityStore store = new CityStore();

        return store.SimpleSortedListByName<DropdownListEntity>();
    }
}


texts: SQL query to classify and count logged messages

texts:
I have an SQL query that fetches some stats, and those stats are displayed on a dashboard. The dashboard runs this query every 15 seconds to fetch the most up-to-date data.

The query is very CPU-heavy for the database server (according to the stats provided by Azure SQL Server), and eats 15% of the available CPU capacity of the server.

The query runs on a log (which records messages received from user and the answers returned by a chatbot). It returns four pieces of information, namely conversations, messages, licenses and failed:

SELECT
    -- Total unique `conversationId`s:
    COUNT (DISTINCT conversationId) AS conversations,

    -- Total records in table:
    COUNT (*) AS messages,

    -- Total unique `licenseId`s:
    COUNT (DISTINCT licenseId) AS licenses,

    -- Total messages where `intent` meets certain criteria:
    (
        SELECT COUNT (*)
        FROM MessageLog
        WHERE intent LIKE 'None' OR intent IS NULL OR intent LIKE ''
      ) AS failed
    FROM MessageLog

What do you think is the most CPU intensive part of that query, and what are the possible ways to consume less CPU?

Update: Here's the DB schema:

CREATE TABLE [dbo].[MessageLog](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [licenseId] [int] NOT NULL,
    [message] [nvarchar](1000) NOT NULL,
    [timestamp] [datetime] NOT NULL,
    [intent] [nvarchar](70) NULL,
    [entities] [nvarchar](3000) NULL,
    [conversationId] [nvarchar](100) NULL,
    [confidence] [float] NULL,
    [failed] [bit] NOT NULL,
    [ipAddress] [varchar](25) NULL,
    [userAgent] [varchar](256) NULL,
    [nlpExecutionTime] [int] NULL,
    [answer] [nvarchar](1000) NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[MessageLog] ADD  CONSTRAINT [DF_MessageLog_failed]  DEFAULT ((0)) FOR [failed]
GO

There are non-clustered indexes on id, intent, conversationId, licenseId, but it doesn't seem to improve the performance.


texts:
I am trying to see how I can speed up the below script that reports disk usage.

The timed find command towards the end is the problematic line that I am trying to speed up. This script is run on directories that have over 6-7TB of data and it takes 16-18hrs. However I want it to run in under 8hrs. Can someone please suggest alternate ways to modify this script?

# -disk_check.csh takes dir name as a mandatory argument and an options <num> or -verbose as a second argument.
#  Ex1: disk_check <dir_name> - Reports out the disk usage per user and the total disk consumption
#  Ex2: disk_check <dir_name> -verbose -Along with the above, it also lists all files by size in the given directory
#  Ex3: disk_check <dir_name> -<num> -Similar to Ex2, But here it reports out the top <num> files by size in the given directory

if ($#argv == 0) then
    echo " Error : Dir path missing"
    echo " Syntax : disk_check <dir-name> <verbose>"
    echo "          verbose gives a list of all files per individual sorted by size"
    exit 0
endif

set cwd = $argv[1]
if ($cwd =~ "-help") then
    echo " Error : Dir path missing"
    echo " Syntax : disk_check <dir-name> <-verbose>"
    echo "          -verbose gives a list of all files per individual sorted by size"
    exit 0
endif

if ($#argv > 1) then
    set opt = $argv[2]
#echo "opt : $opt"
endif

if ( -d $cwd ) then

set ava = `df -h $cwd | tail -1 | awk '{print $1'}`
set tot = `df -h $cwd | tail -1 | awk '{print $2'}`
set ad = `df -h $cwd | tail -1 | awk '{print $3'}`
set pcu = `df -h $cwd | tail -1 | awk '{print $4'}`

echo ""
echo "Summary for dir ${cwd}: $tot Used (${pcu})"
echo "-----------------------------------------------------------------------------"
echo " Total Volume $ava"
echo " Available on disk $ad "
echo " Percentage used $pcu"
echo ""
echo "Summary by User:"
printf "%sUser%15sSize%10sCount\n" ""
echo "---------------------------------------------"

# This is the command that takes a long time:
time find $cwd -type f -printf "%u %s\n" | awk '{user[$1]+=$2;count[$1]++}; END{ for( i in user) printf "%s%-13s%5s%-0.2f%s%5s%7s\n","", i, "", user[i]/1024**3,"GB", "", count[i]}'| sort -nk2 -r

if ($#argv > 1) then
    if ($opt =~ "-verbose") then
        echo "\nDetail, Sorted by size"
        printf " User%15sFile%15sSize\n" ""
        echo "---------------------------------------------------"
        find $cwd -type f -not -path '*/\.*'  -printf "%-13u | %-50p | %-10s \n" | sort -nk5 -r
endif


texts: Generate every possible single word of three letters

texts:
I was asked to generate every possible single word of three letters, so I wrote this script. How good is my code? Would it be better doing it using recursion or would that be over-engineering?

const getAllPossibleThreeLetterWords = () => {
      const chars = 'abcdefghijklmnopqrstuvwxyz'
      const arr = [];
      let text = '';
      for (let i = 0; i < chars.length; i++) {
            for (let x = 0; x < chars.length; x++) {
                  for (let j = 0; j < chars.length; j++) {
                        text += chars[i]
                        text += chars[x]
                        text += chars[j]
                        arr.push(text)
                        text = ''
                  }
            }
      }
      return arr
}
console.log(getAllPossibleThreeLetterWords());


texts: Add one to integer represented as an array

texts:
I am practicing interview questions and have written the following
 code for the given task.

Task : Given a non-negative number represented as an array of digits, add 1 to the number (increment the number represented by the digits). The digits are stored such that the most significant digit is at the head.

Code:

class Solution:
# @param A : list of integers
# @return a list of integers
    def plusOne(self, A):
        Rev_A = A[::-1]
        i = 0
        while i <= len(A)-1:
            if Rev_A[i] != 9:
                Rev_A[i] +=1
                carry = 0
                break
            else:
                Rev_A[i] = 0
                carry = 1
            i += 1
        if carry == 1:
            Rev_A.append(1)
        while True:
            if Rev_A[-1]==0:
                Rev_A.pop()
            else:
                break
        return Rev_A[::-1]

    def __init__(self):
        self.list = []

Test cases:

if __name__ == "__main__":

    A = Solution()
    ## Test Cases
    print A.plusOne([0])
    print A.plusOne([9,0,0])
    print A.plusOne([6,9,9])
    print A.plusOne([9,9,9])
    print A.plusOne([0,9,9,9])
    print A.plusOne([0,0,0,1,2,3])

How can this code be better?


texts: Modern HTTP-Requests for login/register system

texts:
I am working on a login/register system and want the register and log in process as smooth as possible. One way of making it smoother is in my opinion to make a multi-step login/register.

What I mean: If a user want's to log in, he first have to type in his username and if this username exists, he can type in a password and log in. The user has more feedback, especially in the register process. Since I started to learn OOP and know that es6 was introduces a while ago, I want to improve in JS aswell.

I only have one button that does everything. That's why I have a switch case in my button event listener that compares the value of it to select the right method in my form class.

The code at the bottom is what I have came up with. It works but I don't think it is how it's done normally.

Is this code 'advanced' or does it look like it's from a noob.

I am aware that doing a login like that leaks information, but I have already setup a robust protection against it. So that attackers don't have a lot of tries, while users can login wihtout a DoS.

class Form {
    content = document.getElementById('content');
    username = document.getElementById('username');
    password = document.getElementById('password');
    submit_btn = document.getElementById('right');
    loader = document.getElementById('loader');
    request;

    constructor () {
        this.request = new XMLHttpRequest();
    }

    execute(type, path, Data) {
        this.loading();
        this.request.open(type, path);
        this.request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        this.request.send(Data);
    }

    loading() {
        this.loader.style.opacity = 1;
    }

    loaded() {
        this.loader.style.opacity = 0;
    }

    submit_username () {
        this.request.onload = () => {
            this.loaded();

            //If response value is true than
            //Switch Input field to password
            //Change button value to login_two
            //else show error messages

        }

        let Data = `username=${this.username.value}`

        this.execute('post', '/login/step_one', Data);
    }

    submit_login() {
        this.request.onload = () => {
            this.loaded();

            //If response value is true than
            //Redirect the user to home
            //else show error messages

        }

        let Data = `password=${this.password.value}`

        this.execute('post', '/login/step_two', Data);

    }

}

const form = new Form();

form.submit_btn.addEventListener("click", () => {
    let method = form.submit_btn.value;
    switch (method) {
        case 'login_one':
            form.submit_username();
        break;
        case 'login_two':
            form.submit_login();
        break;
    }
});

Maybe someone can provide an example of a better way.

Codepen


texts:
I'm currently trying to brush up on my assembly skills and, being at the FPU section of the tutorial, I implemented a very basic version of a Monte-Carlo-Algorithm to compute pi. I deliberately use the x87 instruction set instead of SSE because that's what I'm learning at the moment. What would be the pros and cons of SSE vs x87 for that particular case?

; Monte - Carlo PI

.686
.model flat, c
.stack 4096
.mmx
.xmm

.data
align 16
rand DWORD 0
maxu DWORD 07fffffffh
one DWORD 1.0
four DWORD 4.0
maxn DWORD 50000000
count DWORD 0
result REAL8 0.

.code
includelib MSVCRT
extrn exit : near

main proc

; ecx is loop counter
xor eax, eax
mov ecx, maxn

; init FPU and store const
; values 1 and 2^-32
finit
fild dword ptr [maxu]
fld dword ptr [one]
fdivr st(1), st(0)

lp:
; load two random numbers x and y
rdrand ebx
mov dword ptr[rand], ebx
rdrand ebx
mov dword ptr[rand + 4], ebx
fild dword ptr[rand]
fild dword ptr[rand + 4]

; normalize to[0, 1] and square
fmul st(0), st(3)
fmul st(0), st(0)
fxch st(1)
fmul st(0), st(3)
fmul st(0), st(0)
fadd st(0), st(1)

; if point is inside the circle increase counter
fcomi st(0), st(2)
ja greater
inc eax
greater:
fstp result
fstp result
loop lp

; pi/4 = #points inside/#all tries
mov count, eax
fild dword ptr [count]
fidiv dword ptr [maxn]
fmul four
fstp result

push 0
call exit

main endp
end main


texts: Nginx rewrite optimization for PHP execution

texts:
I've posted an excerpt from my Nginx configuration with the hope that someone can give me advice on anything I've done wrong or could do better. Please note that the below config works, but has been edited for brevity.

The area I'd like you to focus on is TEST1 and TEST2.

TEST1 is redirecting any requests to /folder/downloads/ to  /usr/share/nginx/downloads/redirected.php

Example:

When I visit http://192.168.1.100/folder/downloads/imaginary-file.pdf
I am being redirected to /usr/share/nginx/downloads/redirected.php

TEST2 is allowing PHP to be executed in /usr/share/nginx/downloads/
Previously it was being redirected to /usr/share/nginx/html/ because of the root directive in the server block.

server {
    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    #TEST1
    location /folder/downloads/ {
            root /usr/share/nginx/downloads;
            rewrite ^/(.*)$ /redirected.php last;
    }
    #TEST2 ALLOW PHP TO EXECUTE FOR #TEST1
    location ~* ^/redirected(.*\.php)$ {
        root /usr/share/nginx/downloads;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

Miscellaneous information: In the future, I may want PHP files other than redirected.php to execute.


texts:
The  task was:

  You’re given A/B and C/D. You will have to calculate A/B + C/D and answer it as E/F.

  Input specification
  On the first line you’re given the test case number N. Then there will be N line following. Each line consist of 4 integers with two “/” in the middle. For example: the each line will be “A/B C/D”.

  Output specification
  For every test case, print out the sum of the given two fractions in the format: "numerator/denominator".

My code

#include <stdio.h>

int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b%a, a);
}

int main()
{
    int T;
    scanf("%d", &T);

    for (int i=1; i<=T; i++)
    {
        int num1, den1;
        int num2, den2;
        scanf("%d%*c%d %d%*c%d", &num1,&den1,&num2,&den2);

        int num3, den3;
        den3 = gcd(den1,den2);
        den3 = (den1*den2)/den3;
        num3 = (num1)*(den3/den1) + (num2)*(den3/den2);
        printf("Case %d: %d/%d\n", i, num3, den3);
    }

    return 0;
}


texts: Find plane (walls, floor, ceiling) that a falling car will land on

texts:
I have a function that takes a falling car's location & velocity as well as the world gravity. The world has a floor, ceiling, and walls that are in fixed positions. The car's x & y velocity can't change once it's airborne, but gravity does force the car down. I'm trying to find exactly which plane the car will land on first.
This is my current solution, which actually works just fine:
#include <math.h>

// Vector stuff

typedef struct vector
{
    double x;
    double y;
    double z;
} Vector;

static inline Vector add(Vector vec1, Vector vec2)
{
    return (Vector){vec1.x + vec2.x, vec1.y + vec2.y, vec1.z + vec2.z};
}

static inline Vector multiply(Vector vec1, Vector vec2)
{
    return (Vector){vec1.x * vec2.x, vec1.y * vec2.y, vec1.z * vec2.z};
}

static inline double dot(Vector vec1, Vector vec2)
{
    return vec1.x * vec2.x + vec1.y * vec2.y + vec1.z * vec2.z;
}

static inline double magnitude(Vector vec)
{
    return sqrt(dot(vec, vec));
}

static inline Vector double_to_vector(double num)
{
    return (Vector){num, num, num};
}

// find the falling car's landing plane

int find_landing_plane(Vector car_location, Vector *car_velocity, double *gravity)
{
    Vector l = car_location;
    Vector v = *car_velocity;
    Vector V_simulation_dt = double_to_vector(simulation_dt);
    double g = *gravity * simulation_dt;

    if (fabs(l.y) >= 5120)
        return 5; // this is a special exception

    while (1)
    {
        if (magnitude(v) < 2300) // 2300 = terminal velocity
            v.z = v.z + g;
        l = add(l, multiply(v, V_simulation_dt));

        // there must be a better way to do this...
        if (l.x >= 4080)
            return 0; // wall
        if (l.x <= -4080)
            return 1; // wall
        if (l.y >= 5110)
            return 2; // wall
        if (l.y <= -5110)
            return 3; // wall
        if (l.z >= 2030)
            return 4; // ceiling
        if (l.z <= 20)
            return 5; // floor
    }
}

I'm new to C, but I do have a few years of programming experience... SURELY there's a better way to do this? I was thinking perhaps something to do with the trajectory formula, or just a way to make the if statements nicer to look at would also be great.


texts:
I decided to play with F# and found simple task on Codewars.
The task is sounds like "Calculate Sum/Mean/Avarage for selected City".
I decided to calculate only Sum. My solution is horrific. I would be grateful for your advice's how to do this in a right way. Thank you!

let d0 =
        "Rome:Jan 81.2,Feb 63.2,Mar 70.3,Apr 55.7,May 53.0,Jun 36.4,Jul 17.5,Aug 27.5,Sep 60.9,Oct 117.7,Nov 111.0,Dec 97.9\n\
        London:Jan 48.0,Feb 38.9,Mar 39.9,Apr 42.2,May 47.3,Jun 52.1,Jul 59.5,Aug 57.2,Sep 55.4,Oct 62.0,Nov 59.0,Dec 52.9\n\
        Paris:Jan 182.3,Feb 120.6,Mar 158.1,Apr 204.9,May 323.1,Jun 300.5,Jul 236.8,Aug 192.9,Sep 66.3,Oct 63.3,Nov 83.2,Dec 154.7\n\
        NY:Jan 108.7,Feb 101.8,Mar 131.9,Apr 93.5,May 98.8,Jun 93.6,Jul 102.2,Aug 131.8,Sep 92.0,Oct 82.3,Nov 107.8,Dec 94.2\n\
        Vancouver:Jan 145.7,Feb 121.4,Mar 102.3,Apr 69.2,May 55.8,Jun 47.1,Jul 31.3,Aug 37.0,Sep 59.6,Oct 116.3,Nov 154.6,Dec 171.5\n\
        Sydney:Jan 103.4,Feb 111.0,Mar 131.3,Apr 129.7,May 123.0,Jun 129.2,Jul 102.8,Aug 80.3,Sep 69.3,Oct 82.6,Nov 81.4,Dec 78.2\n\
        Bangkok:Jan 10.6,Feb 28.2,Mar 30.7,Apr 71.8,May 189.4,Jun 151.7,Jul 158.2,Aug 187.0,Sep 319.9,Oct 230.8,Nov 57.3,Dec 9.4\n\
        Tokyo:Jan 49.9,Feb 71.5,Mar 106.4,Apr 129.2,May 144.0,Jun 176.0,Jul 135.6,Aug 148.5,Sep 216.4,Oct 194.1,Nov 95.6,Dec 54.4\n\
        Beijing:Jan 3.9,Feb 4.7,Mar 8.2,Apr 18.4,May 33.0,Jun 78.1,Jul 224.3,Aug 170.0,Sep 58.4,Oct 18.0,Nov 9.3,Dec 2.7\n\
        Lima:Jan 1.2,Feb 0.9,Mar 0.7,Apr 0.4,May 0.6,Jun 1.8,Jul 4.4,Aug 3.1,Sep 3.3,Oct 1.7,Nov 0.5,Dec 0.7"

module CalculatorHelper =
    let SumByTown (town:string) (input:string) =
        let rows = input.Split('\n')
        for i in rows do
            if (i.Contains(town))
            then
                let monthes = i.Replace(town + ":","").Split(",")
                let sequence = seq { for j in monthes do yield j.Remove(0,4) |> double } |> Seq.sum
                printf "%f" sequence

let result = CalculatorHelper.SumByTown "Rome" d0


texts: Convert Sorted Array to Height Balanced Binary Search Tree

texts:
Algorithm

This is my code to convert a sorted vector of integers to a balanced binary tree of the same content.

The binary tree is made of these nodes:

 struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };

Here's my first attempt:

class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.empty()) return NULL;
        if(nums.size()==1){
            TreeNode* root = new TreeNode(nums[0]);
            return root;
        }

        int mid = nums.size() / 2;
        TreeNode* root = new TreeNode(nums[mid]);

        vector<int> left(nums.begin(),nums.begin()+mid);
        vector<int> right(nums.begin()+mid+1,nums.end());

        root->left = sortedArrayToBST(left);
        root->right = sortedArrayToBST(right);

        return root;
    }
};

I was making new vectors and copying contents twice in every recursive call, So this is the optimized version by directly passing iterator instead of passing index and copying sub arrays every time:

class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
      return makeBST(nums.begin(),nums.end());
    }

    TreeNode* makeBST(vector<int>::iterator start,vector<int>::iterator end){
        if( start >= end ) return NULL;
        vector<int>::iterator mid = start + (end - start) / 2;
        TreeNode* root = new TreeNode(*mid);
        root -> left = makeBST( start , mid );
        root -> right = makeBST( mid + 1 , end );
        return root;
    }
};

The second code has much faster run time than first one.

Is there a better way to pass iterators to function?

Any other improvements?


texts: Refactoring class methods to helper class?

texts:
I have an abstract class that represents data request. The request is in XML format. There are a few classes that derive from abstract class and they do similar things.

Some basic XML operations such as create XML document, write the elements and attributes of XML document and so on are implemented as methods of abstract class and they can be used from derived classes as well.

I should refactor the abstract class. I think I could write some kind of XML helper class outside of request-based classes, but I'm not sure if it's right way.

The code looks as following:

public abstract class MWRequest
{
    public static string WebServiceURL = "url";
    protected XmlDocument xmlDoc = new XmlDocument();

    protected MWRequest()
    {
        xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><request/>");
    }

    public XmlDocument XmlDocument
    {
        get { return xmlDoc; }
    }

    protected void PrepareRequest(string requestType)
    {
        LoadElement("protocol-version", "4.00");
        LoadElement("request-type", requestType);
        LoadExtraElement("password", password);
        LoadElement("terminal-id", terminalId);
    }

    protected void LoadElement(string elemName, string val)
    {
        XmlElement elem = xmlDoc.CreateElement(elemName);
        elem.InnerText = val;
        xmlDoc.DocumentElement.AppendChild(elem);
    }

    protected void LoadExtraElement(string name, string val)
    {
        // <extra name="ltime">60</extra>
        XmlElement elem = xmlDoc.CreateElement("extra");

        XmlAttribute attrName = xmlDoc.CreateAttribute("name");
        attrName.Value = name;
        elem.Attributes.Append(attrName);

        elem.InnerText = val;

        xmlDoc.DocumentElement.AppendChild(elem);
    }

    ...
}


texts: An R function for checking whether a variable is binary or continuous

texts:
This function takes a numeric vector and returns "con" if it's continous and "bin" if it's binary.

It does not take the multinomial case into account, i.e. if a variable y has three possible values 0, 1, 2, it's treated like a continuous variable.

Code:

checkBinaryTrait = function(v, naVal="NA") {
    if(!is.numeric(v)) stop("Only numeric vectors are accepted.")
    vSet = unique(v)
    if(!missing(naVal)) vSet[which(vSet == naVal)] = NA
    vSet = vSet[which(!is.na(vSet))]
    if(any(as.integer(vSet) != vSet)) return("con")
    if(length(vSet) > 2) return("con")
    "bin"
}

Tests:

v = c(1, 1.1, 1, 1.1, NA)
checkBinaryTrait(v)
v = c(1, 2, 1, 2, NA)
checkBinaryTrait(v)
v = c(-9, 2.3, 4.1, -9, -9)
checkBinaryTrait(v, -9)
v = c(-9, 2, 4, -9, -9)
checkBinaryTrait(v, -9)


texts: Implement Scala-like Trampoline to gain tail call optimization in Rust

texts:
On the topic of tail call optimization, I found two RFCS: 271 and 1888.

Until this gets implemented, I wanted to do something inspired from Scala's Trampoline functionality.

The actual implementation is far from a full-fledged tail call optimization in that it replaces recursive function calls with iterative ones, but it has its use for keeping the stack depth low. My actual state of work is as follows:

enum Trampoline<A, R> {
    Continue(A, R),
    End(R),
}

impl<A, R> Trampoline<A, R> {
    fn start(function: &Fn(A, R) -> Trampoline<A, R>, mut arg: A, mut sum: R) -> R
    {
        loop {
            match function(arg, sum) {
                Trampoline::Continue(r_arg, r_sum) => {
                    arg = r_arg;
                    sum = r_sum;
                },
                Trampoline::End(result) => return result,
            }
        }
    }
}

fn recurse_trampolin(arg: i32, sum: i32) -> Trampoline<i32, i32> {
    if arg == 0 {
        Trampoline::End(sum)
    } else {
        Trampoline::Continue(arg - 1, sum + arg)
    }
}

fn recurse_normal(arg: i32, sum: i32) -> i32 {
    if arg == 0 {
        sum
    } else {
        recurse_normal(arg - 1, sum + arg)
    }
}

fn main() {
    println!("{}", recurse_normal(5, 0));
    println!("{}", Trampoline::start(&recurse_trampolin, 5, 0));
}

Apart from using references for compatibility with non-Copy types, can this construction be further optimized or the code simplified/beautified?


texts:
Requirements:

There are two columns. The left column is fixed width.
The height of two Column should be the same.
Left column contain a title (can be multi-line) and an Image (limit max width to left column's width, but can be any height)
Right column contains rich text content.
If the height of left column is higher than right column, content of right should remain vertical center.
If the height of right column is higher than left column, the Title should stay top and the Image should stay vertical center in the rest of the space.

Edit:
Oh, sorry. I found that I can't do 5 & 6 in the same time...  Is it possible make it work on IE 7 in pure CSS?

.row-Item{
    border: 3px solid #F9BE00;
    position: relative;
}

.left-column{
    position: absolute;
    width:200px;
    background : #F9BE00;
    top: 0;
    left: 0;
    bottom: 0;
}

.right-column{
    margin-left:200px;
    vertical-align: middle;
    background: #FEF2CC;
}

.warpper{
    display:table;
    min-height: 100%;
}

.left-column .text-container{
    display:table-row;
    height:1px;
    font-size:20px;
    font-weight:bold;
}

.left-column .img-container{
    display:table-row;
    height:100%;
    text-align:center;
}

    <meta charset="utf-8">
    <title>JS Bin</title>

                                Some Title Here

                                May be multi-line

            Content text go heres. Content text go heres. Content text go heres.    Content text go heres. Content text go heres. Content text go heres.

some list item..

some list item..

some list item..

some list item..

             Content text go heres. Content text go heres. Content text go heres.Content text go heres. Content text go heres. Content text go heres.Content text go heres. Content text go heres. Content text go heres.Content text go heres. Content text go heres. Content text go heres.   Content text go heres. Content text go heres. Content text go heres.

Live


texts:
It is a usual pattern when creating a new component, to load references to other components of the same GameObject. Here is an extreme case:

    [RequireComponent(typeof(Animator))]
    [RequireComponent(typeof(SpriteRenderer))]
    [RequireComponent(typeof(Stats))]
    [RequireComponent(typeof(Hunger))]
    [RequireComponent(typeof(Thirst))]
    [RequireComponent(typeof(Navigator))]
    [RequireComponent(typeof(LocationDevice))]
    [RequireComponent(typeof(AttacksManager))]
    [RequireComponent(typeof(ShieldEffect))]
    public class EnemyController : MonoBehaviour
    {
        Animator animator;
        SpriteRenderer spriteRenderer;
        Stats stats;
        Hunger hunger;
        Thirst thirst;
        Navigator navigator;
        LocationDevice locationDevice;
        AttacksManager attacksManager;
        ShieldEffect shieldEffect;

        void Awake()
        {
            animator = GetComponent<Animator>();
            spriteRenderer = GetComponent<SpriteRenderer>();
            stats = GetComponent<Stats>();
            hunger = GetComponent<Hunger>();
            thirst = GetComponent<Thirst>();
            navigator = GetComponent<Navigator>();
            locationDevice = GetComponent<LocationDevice>();
            attacksManager = GetComponent<AttacksManager>();
            shieldEffect = GetComponent<ShieldEffect>();
        }
    }

Is there a way to write this better?