texts: Writing null-safe code to set form values

texts:
I will ask my question using the following example:

HTML

<div>
    <input id="ABC" placeholder="abc"></input>
    <textarea id="XYZ" placeholder="xyz"></textarea>
</div>

JS Code

var valArray = [{id: "ABC", value: "INPUT"}, {id: "UNKNOWN", value: ""}, {id: "XYZ", value: "TEXTAREA"}]

function process(arr) {
    for(var i=0; i<arr.length; i++) {
        var elem = document.getElementById(arr[i].id);
        if (elem != null) {
            elem.value = arr[i].value;
        }
    }
}

process(valArray);

It works fine, but now I want to do it without an explicit if statement.

How about the following code? Is it a proper JavaScript way to handle such situations?

function process(arr) {
    for(var i=0; i<arr.length; i++) {
        (document.getElementById(arr[i].id) || 0).value = arr[i].value;
    }
}

From Programming JavaScript Applications by Eric Elliott- Chapter 3. Objects:

  Even primitive types get the object treatment when you refer to them
  with the property access notations. They get automatically wrapped
  with an object so that you can call their prototype methods.

  Primitive types behave like objects when you use the property access
  notations, but you can't assign new properties to them. Primitives get
  wrapped with an object temporarily, and then that object is
  immediately thrown away. Any attempt to assign values to properties
  will seem to succeed, but subsequent attempts to access that new
  property will fail.

In general I saw a lot of JavaScript code where || <default or alternative value> construct was used to protect against null.

So I thought, that the above described behavior would make primitives ideal candidates for "throw-away" objects.

If this is so convoluted, what about using Object:

        (document.getElementById(arr[i].id) || Object).value = arr[i].value;

That was my original idea but it seems to pollute the environment.


texts:
How should I approach refactoring this code?

def separate_comma(number)
  a = number.to_s.split('')
  b = a.size/3.0
  if a.size < 4
    p number.to_s
  elsif a.size%3 == 0
    n = -4
    (b.to_i-1).times do |i|
      a.insert(n, ',')
      n -= 4
    end
    p a.join("")
  else
      n = -4
    b.to_i.times do |i|
      a.insert(n, ',')
      n -= 4
    end
  p a.join("")
  end
end

separate_comma(97425)    # => "97,425"
separate_comma(89552600) # => "895,926,600"
separate_comma(0)       # => "0"
separate_comma(100)     # => "100"


texts: I'm still fairly new with JavaScript, and wrote something to generate some social media links on my page.  The idea was to have that script grab the necessary URL info and feed it to the social media APIs.


texts:
I tried to implement following class which should handle connecting to a server, as well as sending and receiving data.

Your feedback is welcome. Please note I am beginner in .NET and don't give too advanced feedback. I tested it and it seems to work. So in case you see some major problems please let me know, otherwise this class seems to fulfill my needs. I may add some small functionalities though.

Also can I better release resources than I am doing now? (maybe automatically close all resources I am using if that's possible?)

 class DppTCPClient
    {
        public TcpClient m_client = new TcpClient();

        public void Connect(string address, int port)
        {
            if (m_client.Connected)
                throw new Exception("Connect: Already connected");

            m_client.Connect(address, port);
        }

        public void WriteBytes(byte[] data, int length)
        {
            if (data.Length != length)
                throw new Exception("WriteBytes: Length should be same");

            // Get access to network stream
            Stream stm = m_client.GetStream();
            stm.Write(data, 0, data.Length);

        }

        public void ReadAllBytes(byte[] buffer, int length)
        {
            if (buffer.Length != length)
                throw new Exception("ReadAllBytes: Length should be same");

            Stream stm = m_client.GetStream();

            // Start reading
            int offset = 0;
            int remaining = length;
            while (remaining > 0)
            {
                int read = stm.Read(buffer, offset, remaining);
                if (read <= 0)
                    throw new EndOfStreamException
                        (String.Format("ReadAllBytes: End of stream reached with {0} bytes left to read", remaining));
                remaining -= read;
                offset += read;
            }

        }

        public void CloseDppClient()
        {
            if (m_client.Connected)
            {
                m_client.GetStream().Close();
                m_client.Close();
            }
        }
    }


texts:
I'm writing a simple xHTML parser which parses a data without nested tags.

Example input code will look like:

Header

 atsatat

asdsaad</2>
s32532235

I've wrote the following code:

#include <node.h>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>

using namespace v8;

enum Tags {
    Closing = 0,
    Paragraph,
    Heading
};

int tagDetect(char *ptr){
    if (*ptr == '/') {
        return Tags::Closing;
    }

    if (*ptr == 'p') {
        return Tags::Paragraph;
    }

    if (*(ptr + 1) == '2' || *(ptr + 1) == '3')
        return Tags::Heading;

    return -1;
}

Handle<Value> Callback(const Arguments& args) {
    HandleScope scope;

    if (!args[0]->IsString() || !args[1]->IsFunction()) {
        return ThrowException(Exception::TypeError(
            String::New("Invalid arguments! First parameter must be [string], second must be a callback [function].")));
    }

    Local<Function> callback = Local<Function>::Cast(args[1]);
    String::Utf8Value param1(args[0]->ToString());
    std::string input = std::string(*param1);

    static Persistent<String> data_symbol = NODE_PSYMBOL("data");
    static Persistent<String> tag_symbol = NODE_PSYMBOL("tag");

    std::string::size_type pos = 0, closePos = 0;

    int openPos;
    int tagID, lastTag, id = 0, lastAppended = 0, clearStartPos;

    Local<Array> nodes = Array::New();
    Local<Object> node_obj;

    while ((pos = input.find('<', pos)) != std::string::npos) {
        pos++;
        switch (tagID = tagDetect(&input[pos])) {
        case Tags::Closing:
            tagID = tagDetect(&input[pos + 1]);
            if (tagID == lastTag && (pos - openPos > 10 || lastTag != Tags::Paragraph)) {
                /* Concat tags */
                if (lastAppended == lastTag) {
                    if (lastTag == Tags::Heading) { /* Dont concat heading tags */
                        continue;
                    }

                    node_obj = nodes->Get(id - 1)->ToObject();
                    node_obj->Set(data_symbol, String::Concat(node_obj->Get(data_symbol)->ToString(), String::New(input.substr(openPos + (lastTag > 1 ? 3 : 2), pos - openPos - (lastTag > 1 ? 3 : 2) - 1).c_str())));
                    continue;
                }

                node_obj = Object::New();
                node_obj->Set(data_symbol, String::New(input.substr(openPos + (lastTag > 1 ? 3 : 2), pos - openPos - (lastTag > 1 ? 3 : 2) - 1).c_str()));
                node_obj->Set(tag_symbol, Integer::New(lastTag));
                nodes->Set(id, node_obj);
                id++;
                lastAppended = lastTag;
                continue;
            }

            /* Clear useless tags */
            input.erase(pos - 1, input.find('>', pos - 1) - pos + 2);
            break;
        case Tags::Paragraph:
        case Tags::Heading:
            openPos = pos;
            lastTag = tagID;
            break;
        default:

            /* Clear useless tags */
            input.erase(pos - 1, input.find('>', pos - 1) - pos + 2);
            break;
        }
    }

    /* Remove last element from array if its heading */

    if (lastTag == Tags::Heading) {
        nodes->Delete(id - 1);
    }

    const unsigned argc = 2;
    Local<Value> argv[argc] = {
        Local<Value>::New(Null()),
        nodes
    };

    callback->Call(Context::GetCurrent()->Global(), argc, argv);

    return Undefined();
}

void RegisterModule(Handle<Object> target) {
    target->Set(String::NewSymbol("parse"),
        FunctionTemplate::New(Callback)->GetFunction());
}

NODE_MODULE(smartparser, RegisterModule);

I'm using this as Native NodeJS module. Since I'm really new in the C++ world, any tips on how to optimize/improve my code will be greatly appreciated.


texts:
About 2 months ago I started studying python and then 3 days ago sat and began to write a program (found the dumbest & simplest thought I could: a pyglatin translator). I finally got it working 100%. Being a beginner I would love to hear some constructive criticism on my program; I know I have probably written more then was needed on some stuff and taken a long way around on others.
another_word = " "
sentence1 = " "
new_list = []
another = " "

def trans_one_word (i):
    global another_word
    pyg = 'ay'

    original = (i)

    if len(original) > 0 and original.isalpha():
        word = original.lower()
        first = word[0]
        new_word = word + first + pyg
        another_word = new_word[1:len(new_word)]
        return another_word
    else:
        print('empty')

def input_state():

    sentence = input("enter a word to be translated: ")
    list = sentence.split()
    for i in list:
        trans_one_word(i)
        new_list.append(another_word)
    s = " "
    print (s.join( new_list ))

input_state()

another = input("Would you like to enter another sentence to be     translated? \n Y/N")

if (another == 'y') or (another == 'Y'):
    input_state()

All in all I am proud of myself for actually writing it without any help, or all of it except the last "if" statement (I had minor problems with it).


texts: Most efficient way to find an entry in a C++ vector

texts:
I'm trying to construct an output table containing 80 rows of table status, that could be EMPTY or USED as below

+-------+-------+
| TABLE | STATE |
+-------+-------+
|  00   | USED  |
|  01   | EMPTY |
|  02   | EMPTY |
..
..
|  79   | EMPTY |
+-------+-------+

I have a vector m_availTableNums which contains a list of available table numbers. In the below example, I'm putting 20 random table numbers into the above vector such that all the remaining 60 would be empty. My logic below works fine.

Is there a scope for improvement here on the find logic?

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string.h>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <ctime>

using namespace std;

int main(int argc, const char * argv[]) {
    std::vector<uint8_t> m_availTableNums;
    char tmpStr[50];

    uint8_t tableNum;
    uint8_t randomCount;
    srand(time(NULL));
    for( tableNum=0; tableNum < 20; tableNum++ )
    {
        randomCount = ( rand() % 80 );
        m_availTableNums.push_back( randomCount );
    }

    sprintf(tmpStr, "+-------+-------+");
    printf("%s\n", tmpStr);
    tmpStr[0]='\0';

    sprintf(tmpStr, "| TABLE | STATE |");
    printf("%s\n", tmpStr);
    tmpStr[0]='\0';

    sprintf(tmpStr, "+-------+-------+");
    printf("%s\n", tmpStr);

    tableNum = 0;
    for( tableNum=0; tableNum < 80 ; tableNum++ )
    {
        tmpStr[0]='\0';
        if ( std::find(m_availTableNums.begin(), m_availTableNums.end(), tableNum) != m_availTableNums.end() )
        {
            sprintf(tmpStr, "|  %02d   | EMPTY |", tableNum );
        } else {
            sprintf(tmpStr, "|  %02d   | USED  |", tableNum );
        }

        printf("%s\n", tmpStr);
    }

    tmpStr[0]='\0';
    sprintf(tmpStr, "+-------+-------+");
    printf("%s\n", tmpStr);

    return 0;
}


texts: Replacing MySQL's AUTO_INCREMENT with Postgres' SERIAL

texts:
I am making changes to a Python script that converts MySQL scripts to PostgreSQL, and I want to replace strings such as id INTEGER NOT NULL AUTO_INCREMENT with id SERIAL NOT NULL.

This is the code I got to work:

import re

line = 'id INTEGER(11) NOT NULL AUTO_INCREMENT,'

numeric_types = ['(BIG|MEDIUM|SMALL|TINY)*INT(EGER)*(\(.*?\))*',
'DEC(IMAL)*(\(.*?\))*', 'NUMERIC(\(.*\))*', 'FIXED(\(.*\))*',
'FLOAT(\(.*\))*', 'DOUBLE( PRECISION)*(\(.*?\))*', 'REAL(\(.*\))*',
'BIT', 'BOOL(EAN)*']

for i in range(len(numeric_types)):
    type = numeric_types[i]
    if (re.search(type, line)):
        line = re.sub(type, "SERIAL", line).replace(" AUTO_INCREMENT", "")
        print line
        break

Notes:

line will be a column from a CREATE TABLE statement inputted by the user
I could probably join all regular expressions into one using ORs, but I do not know if that would be a good practice or not


texts: Laravel 5 controller to list appointments by date range and by label

texts:
I am starting to get into OOP using PHP and MVC. I just want to know if this code is good practice. Is this how I should be using my controller and model, in its simplest form?

AppointmentsController:

public function index()
{
    $appointmentsByLabel        = Appointment::findAppointmentsByLabel('2');
    $appointmentsBetweenDates   = Appointment::findAppointmentsBetweenDates('2016-02-01', '2016-03-31');

    return view('appointments', compact('appointmentsBetweenDates', 'appointmentsByLabel'));
}

Model (Appointment):

public static function findAppointmentsBetweenDates($start, $end)
{
    $appointments = Appointment::whereBetween('start',array($start,$end))->get();

    return $appointments;
}

public static function findAppointmentsByLabel($value)
{
    $appointments = Appointment::where('label_id', '=', $value)->get();

    return $appointments;
}


texts:
I followed the tutorial Build a PHP MVC Application and have implemented a database connection. I made a seperate database connection class and I call it in the controller.

It works, but now I have to inject it whenever I call a method from the user model. Is this considered good (dependency injection) or bad (repeating same variable over and over again seems useless)?

I was thinking about moving the db_con method to the user  model itself, but then I'd have to include it in every other future model as well, which is repeating code. Perhaps I should inject it in the first controller method:return new $model(); would become return new $model($this->db_con());? I don't know anymore. So many possibilities, but where would it fit best?

    <?php
      class Controller
      {
        private $db_con = false;

        public function model($model)
        {
          require_once '../app/models/' .$model .'.php';
          return new $model();
        }

        public function view($view, $data)
        {
          require_once '../app/views/' .$view .'.php';
        }

        public function db_con()
        {
          if($this->db_con == false)
          {
            $database = new Database();
            $this->db_con = $database->db_con;
          }

          return $this->db_con;
        }

Now, in my register controller I connect to the user model and inject the database connection like this:

<?php
  class Register extends Controller
  {
    protected $user;

    public function __construct()
    {
      $this->user = $this->model('User');
      $this->db_con = $this->db_con();
    }

    public function form()
    {
      $this->view('register/form', ['notice' => ""]);
    }

    public function submit()
    {
      //Lots of if/elses, then I connect:
      elseif($this->user->create_user($this->db_con, $_POST['username'], $_POST['password'], $_POST['email'], $_SERVER['REMOTE_ADDR']))
      {
        $this->view('register/submit', ['notice' => "You have been registered."]);
      }

And to be complete, the database connection class itself:

<?php
  class Database
  {
    public $db_con = false;
    public function __construct()
    {
      try
      {
        $this->db_con = new PDO('mysql:host='. DB_HOST .';dbname=' . DB_NAME .';charset=utf8', DB_USER, DB_PASS);
      }
      catch (PDOException $e)
      {
        error_log($e->getMessage(), 0);
      }
    }
  }
?>


texts: Assigning a numerical value to each alphabet in corresponding order and then summing any inputted word

texts:
I made a function that outputs the sum of the value of each letter in a word. For example if I input hello my function would output 52.

def words_to_marks(s):
    import string
    values = {}             # dictionary to store value of each alphabet
    values_of_words = []    # to store final value of words
    for index, letters in enumerate(string.ascii_lowercase, 1):     # creates the dictionary
        values[letters] = index
    final = []              # stores value of each number before adding
    for letter in s:
        letter_lower = letter.lower
        final.append(values[letter])    # appends the value of each letter into the list
    values_of_words.append(sum(final))  # sums all the values in the list
    submit = str(values_of_words)       # converts into string so I can remove the brackets around the list
    return submit[1:-1]

test = words_to_marks("friends")
print(test)

I would really appreciate it if someone could point me to the right direction for how I should condense or improve my code.


texts:
Here is my code for implementing an adjacency list from scratch. I would like to get feedback from the experts for optimization.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

 /*a single node of an adjacency list*/
typedef struct adjList{

    int dest;
    struct adjList *next;

} adjList;

/*Image of a graph...*/

typedef struct Image{

    int source;
    adjList *head;

} Image;

void initialize_graph(Image *graph, int vertices);

void print_graph(Image graph[], int vertices);

void add_adj_node(Image *graph, int source, int destiny, bool directed);

void free_graph(Image graph[], int vertices);

int main() {

    int vertices;
    scanf("%d", &vertices);

    Image graph[vertices];

    printf("size of graph: %d bytes\n", sizeof graph);

    initialize_graph(graph, vertices);

    printf("initialized image of graph\n");

    print_graph(graph, vertices);

    printf("                          \n");
    //is the graph directed ? ans: false

    add_adj_node(graph, 1, 7, false);
    add_adj_node(graph, 1, 3, false);
    add_adj_node(graph, 4, 6, false);
    add_adj_node(graph, 4, 1, false);
    add_adj_node(graph, 5, 2, false);
    add_adj_node(graph, 1, 5, false);
    add_adj_node(graph, 1, 2, false);

    print_graph(graph, vertices);

    free_graph(graph, vertices);

    /*if this print produces segmentation fault then the memory is fully freed*/
    printf("graph[1].head->dest%d\n", graph[1].head->dest);

    return 0;
}

void initialize_graph(Image graph[], int vertices) {

        for(int i = 1; i<= vertices; i++){
                graph[i].source = i;
                graph[i].head = NULL;
        }

        return;
}

void add_adj_node(Image *graph, int src, int dest, bool directed){

    adjList *cache = malloc(sizeof(adjList));
    /*create a single node*/
    cache->dest = dest;
    cache->next = NULL;

    if(graph[src].head == NULL){
            graph[src].head = cache;

    }

    else{
            /*put the head address on the crawler*/
            adjList *crawler = graph[src].head;

            while( crawler->next != NULL){
                crawler = crawler->next;
            }

            /*update head value and address. head will point to new adj node
             this will also link src -> dest*/

            crawler->next = cache;
    }

    if (directed == false) {
          directed = true;

          /*notice we've changed the sequence. dest and src*/
          add_adj_node( graph, dest, src, directed);
    }

    return;
}

void print_graph(Image *graph, int vertices){

    for(int i = 1; i<= vertices; i++){

                adjList *crawl = graph[i].head;
                printf("node: %d    ", graph[i].source);

                while(crawl){

                      printf("%d ", crawl->dest);
                      crawl = crawl->next;
                }

                printf("\n");
        }

    return;
}

/*just a reverse version of crawling a graph*/

void free_graph(Image *graph, int vertices){

    for(int i = 1; i<= vertices; i++){

                adjList *cache;
                printf("releasing elements of node: %d    ", graph[i].source);

                while(graph[i].head){

                      /*put the next adjacency node in the cache*/
                      cache = graph[i].head->next;
                      /*free the present adjacencey node*/
                      free(graph[i].head);
                      graph[i].head = cache;
                }

                printf("\n");
        }

    return;
}


texts: Python script to clean out old files from a repository

texts:
I wrote the script below as my first python program that will be running in a production environment. Essentially this program looks at a source location and moves all the files to a destination location if the file is older than 14 days old and does not exists in the destination. I had a user on stack overflow suggest some variable name changes and I am in the process of doing that. I would love if someone could review this code and let me know if anyone sees any potential bugs or errors that I might run into.

import os
import shutil
import time
import errno
import time
import sys
import logging
import logging.config

source = r'C:\Users\Desktop\BetaSource'
dest = r'C:\Users\Desktop\BetaDest'
#Gets the current time from the time module
now = time.time()
#Timer of when to purge files
cutoff = now - (14 * 86400)
source_list = []
all_sources = []
all_dest_dirty = []
logging.basicConfig(level = logging.INFO, filename = time.strftime("main-%Y-%m-%d.log"))

def main():
    dest_files()
    purge_files()
#I used the dess_files function to get all of the destination files
def dest_files():
    for dest_root, dest_subdirs, dest_files in os.walk(dest):
        for f in dest_files:
            global All_dest_dirty
            all_dest_dirty.append(f)

def purge_files():
    logging.info('invoke purge_files method')
    #I removed all duplicates from dest because cleaning up duplicates in dest is out of the scope
    all_dest_clean = list(dict.fromkeys(all_dest_dirty))
    #os.walk used to get all files in the source location
    for source_root, source_subdirs, source_files in os.walk(source):
        #looped through every file in source_files
        for f in source_files:
            #appending all_sources to get the application name from the file path
            all_sources.append(os.path.abspath(f).split('\\')[-1])
            #looping through each element of all_source
            for i in all_sources:
                #logical check to see if file in the source folder exists in the destination folder
                if i not in all_dest_clean:
                    #src is used to get the path of the source file this will be needed to move the file in shutil.move
                    src =  os.path.abspath(os.path.join(source_root, i))
                    #the two variables used below are to get the creation time of the files
                    t = os.stat(src)
                    c = t.st_ctime
                    #logical check to see if the file is older than the cutoff
                    if c<cutoff:
                        logging.info(f'File has been succesfully moved: {i}')
                        print(f'File has been succesfully moved: {i}')
                        shutil.move(src,dest)
                        #removing the allready checked source files for the list this is also used in other spots within the loop
                        all_sources.remove(i)
                    else:
                        logging.info(f'File is not older than 14 days: {i}')
                        print(f'File is not older than 14 days: {i}')
                        all_sources.remove(i)
                else:
                    all_sources.remove(i)
                    logging.info(f'File: {i} allready exists in the destination')
                    print(f'File: {i} allready exists in the destination')
if __name__ == '__main__':
    main()


texts: How to properly get values from multidimensional object

texts:
Output should be an object ({cal: val}), with soonest possible time throughout all calendars recommended times from the data.

My question is: is this approach over complicated and if so, what should be the proper way to solve that task?

Incoming data is an object:

let data = [
  {
    name: "A",
    calendars: {
      "1_A@group.calendar.google.com": {
        busy: ["2019-08-19T14:30:00.000Z"],
        free: [
          {
            start: "2019-08-19T08:00:00.000Z",
            end: "2019-08-19T09:30:00.000Z"
          }
        ],
        recommended: "2019-08-19T01:00:00.000Z"
      },
      "2_A@group.calendar.google.com": {
        busy: ["2019-08-19T14:30:00.000Z"],
        free: [
          {
            start: "2019-08-19T12:30:00.000Z",
            end: "2019-08-19T14:00:00.000Z"
          }
        ],
        recommended: "2019-08-19T04:00:00.000Z"
      }
    }
  },
  {
    name: "B",
    calendars: {
      "1_B@group.calendar.google.com": {
        busy: ["2019-08-19T14:30:00.000Z"],
        free: [
          {
            start: "2019-08-19T12:30:00.000Z",
            end: "2019-08-19T14:00:00.000Z"
          }
        ],
        recommended: "2019-08-19T05:00:00.000Z"
      },
      "2_B@group.calendar.google.com": {
        busy: ["2019-08-19T14:30:00.000Z"],
        free: [
          {
            start: "2019-08-19T12:30:00.000Z",
            end: "2019-08-19T14:00:00.000Z"
          }
        ],
        recommended: "2019-08-19T02:00:00.000Z"
      }
    }
  }
];

Here is how I solved it:  https://codesandbox.io/s/purple-rain-ecmcu?fontsize=14

function reduce(data) {
  return data.reduce((acc, cur, i) => {
    if (!acc.length || cur[1] < acc[1]) {
      return [cur[0], new Date(cur[1])];
    } else {
      return acc;
    }
  }, []);
}

data = Object.fromEntries([
  reduce(
    data.map(provider => {
      let providerCalendars = Object.keys(provider.calendars);
      let providerRecommended = Object.values(provider.calendars).map(
        (calendar, i) => [
          providerCalendars[i],
          new Date(calendar.recommended).getTime()
        ]
      );
      return reduce(providerRecommended);
    })
  )
]);


texts: WCF using TAP without worrying about timeouts

texts:
I really like using the new TAP pattern in .Net 4.5. and I am updating some of my older projects to use it.

One of my old patterns was to use EAP with WCF so I could have functions that could take longer than 60 seconds (the default timeout for WCF) to complete without doing custom setup on the client side App.Conifg.

Here is a simple example of what I would do.

[ServiceContract(CallbackContract = typeof(ICallback))]
public interface IService1
{
    [OperationContract(IsOneWay = true)]
    void Test(int arg);
}

[ServiceContract]
interface ICallback
{
    [OperationContract(IsOneWay=true)]
    void Callback(int arg);
}

public class Service1 : IService1
{
    public void Test(int arg)
    {
        var callback = OperationContext.Current.GetCallbackChannel<ICallback>();
        Thread.Sleep(61000); //Sleep for 61 sec.
        callback.Callback(arg + 1);
    }
}

Now I want to put a wrapper around my EAP pattern and turn it in to a TAP pattern (as an aside, just returning a TAP pattern like public Task<int> Test(int arg) will still have the 60 second time limit but it does work)

Here is the solution I came up with, this code would be run on the client.

static class ProxyClient
{
    private delegate void CallbackDelegate(int arg);

    private class CallbackClass : IService1Callback
    {
        public event CallbackDelegate CallbackEvent;

        void IService1Callback.Callback(int arg)
        {
            var tmp = CallbackEvent;
            if (tmp != null)
                tmp(arg);
        }
    }

    public static async Task<int> Test(int arg)
    {
        var callback = new CallbackClass();
        var client = new Service1Client(new InstanceContext(callback));
        TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();

        //start listening for the completion event
        callback.CallbackEvent += (resultArg) => tcs.TrySetResult(resultArg);

        client.Test(arg);

        //wait for the result
        var result = await tcs.Task;

        //close the connection
        client.Close();

        return result;
    }
}

The main concern I had was receiving the completion callback for another invocation if a connection was used more than once. So I create and breakdown the connection from inside the function entirely.

I would love to hear input if this is a good idea, or is there a better way to accomplish long running tasks in WCF without having to modify timeout values client-side at the time of proxy creation.


texts: Print element in a linked list in reverse

texts:
I solved this problem in C++ and was looking for feedback on my code. I'm not sure if storing the data in an array and looping through it in reverse and printing was the right approach since this challenge was to use linked lists, but I didn't know how else to do it:

  You are given the pointer to the head node of a linked list and you
  need to print all its elements in reverse order from tail to head, one
  element per line. The head pointer may be null meaning that the list
  is empty - in that case, do not print anything!

/*
 Print elements of a linked list in reverse order as standard output
 head pointer could be NULL as well for empty list
 Node is defined as
 struct Node
 {
 int data;
 struct Node *next;
 }
 */
void ReversePrint(Node *head)
{
    // creates nodes named current, prev, next
    struct Node *current, *prev, *next;
    // sets current and previous to their respective values. current is head because it is starting position while previous is where we want the head to be pointing, which is null, since we are reverse a linked list
    current = head;
    prev = NULL;
    // allocate memory to an array and initialize i=0
    int array[100], i=0;
    while (current != NULL) {
        // store data into an array to print out later
        array[i] = current->data;
        i+=1;
        // updates next [current, link] -> [int, link] = next
        next = current->next;
        // updates link of current.next to value of previous
        current->next = prev;
        // updates previous value
        prev = current;
        // updates current value
        current = next;
    }
    // at the end of list, sets head to the last value in linked list which is previous
    head = prev;
    // goes through array in reverse order and prints
    for(int j=i-1; j>=0; j--) {
        cout<<array[j]<<endl;
    }
}


texts:
This is an answer to this question on Code-Golf.SE (but obviously not golfed). How can I shorten the runtime of my program? It is taking far too long to run some of the test cases. Can I utilise Python map() or lambda?

def main():

    # Store number of test cases
    T = int(input())

    # Loop for each test case:
    for testCase in range(0, T):

        # Store number of members each team can have
        N = int(input())

        # Store power of beyblades of Team G-Revolution members
        teamG_beybladePowers = [int(x) for x in input().split()]

        # Store power of beyblades of opponent team members
        opponentBeybladePowers = [int(x) for x in input().split()]

        # Store the calculated order of our team members as a list
        teamG_calculatedOrder = []
        # Store the caclulated order of opponent team members as a list
        opponentCalculatedOrder = []

        # Loop through each of the team members and opponent team members, and match them
        for index in range(0, N):

            # Check if Team G's highest beyblade power is lower than or equal to opponent's highest
            if max(teamG_beybladePowers) <= max(opponentBeybladePowers):

                # Team G's highest beyblade power is weaker than opponent's highest.
                # We need not waste our best player on their best player, when we will lose.
                # Match our lowest player against their highest player.
                teamG_calculatedOrder.append(min(teamG_beybladePowers))
                opponentCalculatedOrder.append(max(opponentBeybladePowers))

                # Remove these members from original list
                teamG_beybladePowers.remove(min(teamG_beybladePowers))
                opponentBeybladePowers.remove(max(opponentBeybladePowers))

            else:
                # Team G's highest beyblade power is more than opponent's highest.
                # We can use our best player to beat the opponent's best player.
                # Match them up:
                teamG_calculatedOrder.append(max(teamG_beybladePowers))
                opponentCalculatedOrder.append(max(opponentBeybladePowers))

                # Remove these members from the original list
                teamG_beybladePowers.remove(max(teamG_beybladePowers))
                opponentBeybladePowers.remove(max(opponentBeybladePowers))

        # Store total number of wins
        totalWins = 0

        # Calculate number of wins
        for index in range(0, N):

            # Check if current match was won
            if teamG_calculatedOrder[index] > opponentCalculatedOrder[index]:
                # This match was won
                # Increment total wins:
                totalWins += 1

            else:
                # This match was lost
                pass

        # Print total number of wins
        print(totalWins)

main()


texts:
I am writing a program to implement the Red-Black Tree data structure in java. Below is the beginning of my implementation, namely the left and right rotate functions. I want to know if these functions are correct, and if not, any tips on correcting them. I am basing my functions off of pseudocode I found. Here is a link to the pseudocode I used. If you need to see the node class let me know however I think it is self explanatory for the most part.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package rbtree;

/**
 *
 * @author williamnewman
 */
public class RBTree {
    node root;

   RBTree(int val){
       node r = new node();

       r.setVal(val);
       this.root = r;
   }

   void leftRotate(node x){
     node y = x.rightChild;
     x.rightChild = y.leftChild;
     if(y.leftChild != null){
         y.leftChild.parent = x;
     }
     y.parent = x.parent;
     if(x.parent == null)
         this.root = y;
     else if(x == x.parent.leftChild){
         x.parent.leftChild = y;
     }
     else{
         x.parent.rightChild = y;
     }
     y.leftChild = x;
     x.parent = y;
    }

   void rightRotate(node x){
       node y = x.leftChild;
       x.leftChild = y.rightChild;
       if(y.rightChild != null){
           y.rightChild.parent = x;
       }
       y.parent = x.parent;
       if(x.parent == null){
           this.root = y;
       }
       else if(x == x.parent.rightChild){
           x.parent.rightChild = y;
       }
       else{
           x.parent.leftChild = y;
       }
       y.rightChild = x;
       x.parent = y;
   }

}


texts: Universal OpenGL object RAII wrapper class

texts:
I created a universal OpenGL object RAII wrapper class, that only takes care of object creation and destruction. Here's my code and reasoning behind it:
I first wrote a class that would take glCreate/Delete*() function pointers as constructor arguments, but I quickly realized that's not the right way to go. I'd have to store the glDelete*() function pointer in each object (waste of memory + dereference overhead). Additionally, OpenGL functions have three different forms (see specializations section, further in my code), so that would require 3 different pointer types - ugly. I decided to change my approach.
So, here I am with this template code. As far as I'm concerned, there should be no unnecessary OpenGL call overhead. The class is standard layout, only contains the object ID and there's no virtual stuff involved, so that seems pretty nice. Also, classes wrapping different OpenGL object types cannot be assigned to each other, because template arguments differ.
I'd like to hear your remarks according my code, the class design and the reasoning behind it. Improvement ideas are also welcome.
This is the main code:
/**
    \brief Serves as a RAII wrapper for OpenGL objects
    \note This class provides no OpenGL error checking - this is up to derived classes.
    \template T is object type as in glObjectLabel
*/
template <GLenum T>
class gl_object
{
    public:
        //! Object type used for labeling
        const static GLenum object_type = T;

        inline gl_object( );
        inline explicit gl_object( GLenum target );

        inline ~gl_object( );

        // Deleted copy constructor and copy assignment operator
        gl_object( const gl_object &src ) = delete;
        gl_object &operator=( const gl_object &rhs ) = delete;

        // Move semantics with source invalidation
        gl_object( gl_object &&src );
        gl_object &operator=( gl_object &&rhs );

        //! Allows casting to object's ID (GLuint)
        inline operator GLuint( ) const noexcept;

        //! Returns object's ID
        inline GLuint id( ) const noexcept;

    protected:
        //! The object ID
        GLuint m_id;
};

//! Move constructor with source invalidation
template <GLenum T>
gl_object<T>::gl_object( gl_object<T> &&src ) :
    m_id( src.m_id )
{
    src.m_id = 0;
}

//! Move assignment operator with source invalidation
template <GLenum T>
gl_object<T> &gl_object<T>::operator=( gl_object<T> &&rhs )
{
    // Prevent self-move
    if ( this != &rhs )
    {
        m_id = rhs.m_id;
        rhs.m_id = 0;
    }

    return *this;
}

// Allows cast to GLuint
template <GLenum T>
gl_object<T>::operator GLuint( ) const noexcept
{
    return m_id;
}

// Used for acquiring object's ID
template <GLenum T>
GLuint gl_object<T>::id( ) const noexcept
{
    return m_id;
}

Then, there are many very similar template specializations. Here are the most interesting ones:
// Specializations for GL_BUFFER
template <>
gl_object<GL_BUFFER>::gl_object( )
{
    glCreateBuffers( 1, &m_id );
}

template <>
gl_object<GL_BUFFER>::~gl_object( )
{
    glDeleteBuffers( 1, &m_id );
}

// Specializations for GL_TEXTURE
template <>
gl_object<GL_TEXTURE>::gl_object( GLenum target )
{
    glCreateTextures( target, 1, &m_id );
}

template <>
gl_object<GL_TEXTURE>::~gl_object( )
{
    glDeleteTextures( 1, &m_id );
}

// Specializations for GL_SHADER
template <>
gl_object<GL_SHADER>::gl_object( GLenum type )
{
    m_id = glCreateShader( type );
}

template <>
gl_object<GL_SHADER>::~gl_object( )
{
    glDeleteShader( m_id );
}

// Specializations for GL_PROGRAM
template <>
gl_object<GL_PROGRAM>::gl_object( )
{
    m_id = glCreateProgram( );
}

template <>
gl_object<GL_PROGRAM>::~gl_object( )
{
    glDeleteProgram( m_id );
}


texts: How can I ascertain and test SQL injection vunerabilities on this login code?

texts:
I know about the "little bobby tables" scenario and was just wondering if this code is vulnerable to such SQL injections.

I am fairly new to PHP and am curious about this.

My code for a login script:

<?php
  # session
  session_start();

  # get the variables from login.php
  $userid = $_POST["userid"];
  $pword = $_POST["pword"];

  mysql_real_escape_string($userid);
  mysql_real_escape_string($pword);

  # query the DB
  $query = mysql_query ("
    SELECT username
    FROM login
    WHERE username = '$userid'
    AND pword = '$pword';
  ");

  if ($query === FALSE) {
    die('There has been an error.

 Please re-enter your Login Details on the Login Page.

');
  }

  $result = mysql_fetch_assoc($query);
  $record = $result['username'] ;

  # valid login
  # check if session is operational, if so redirect the user
  # to the correct page
  if ($record != null) {
    $_SESSION['login'] = true;
    header( 'Location: index.php' ) ;
  }

  # invalid login
  else if ($record == null) {
    echo "
    We cant find you on the system.

    Please return to the Login page and ensure that

    you have entered your details correctly.

    Warning: You willl be redirected  back to the Login Page

 in  10 Second(s)";
  }
?>

The main reason for asking this is that when I login inputting:

'user'); DROP TABLE Login;--'

it doesn’t drop the table.

My question is: Am I typing in the right SQL injection?


texts: Determining orthogonal polygons in a 3D integer lattice

texts:
The last couple of days I've been trying to get a simple algorithm for uniquely determining orthogonal polygons in 3D integer space, having already determined coplanar points.
By the time we got here we know each point is unique and there are no collinear points.
For example, given the coplanar points pts (lists or tuples)
    pts = [
        [0, 0, 0], [4, 0, 0],
        [1, 1, 0], [2, 1, 0], [3, 1, 0], [4, 1, 0],
        [1, 2, 0], [2, 2, 0], [3, 2, 0], [4, 2, 0],
        [0, 3, 0], [4, 3, 0]
    ]

# Generate orthogonal polygons
# 3 +-----------+
#   |           |
# 2 |  +__+  +--+
#   |  |  |  |
# 1 |  +--+  +__+
#   |           |
# 0 +-----------+
#   0  1  2  3  4

#    result = [
#       [
#         [0, 0, 0], [0, 3, 0], [4, 3, 0], [4, 2, 0],
#         [3, 2, 0], [3, 1, 0], [4, 1, 0], [4, 0, 0]
#       ], [
#         [1, 1, 0], [1, 2, 0], [2, 2, 0], [2, 1, 0]
#       ]
#    ]

I found the basis of an algorithm for this in a paper as authored by Joseph O'Rourke
The following seems to work for the few tests I set up (however it doesn't deal with orientation).

def polygonise(pts: list) -> list:
    # axes gives us the varying columns (we can ignore z for this)
    axes = {i:set(c) for i,c in enumerate(zip(*pts)) if len(set(c))!=1}
    a, b = axes.keys()

    # construct dicts of axis-columns
    pts_by_axis = {axis: {col: [] for col in cols} for axis,cols in axes.items()}
    for pt in pts:
        for axis in axes:
            pts_by_axis[axis][pt[axis]].append(pt)

    # each axis-column (sorted by the other dimension)
    # will now be paired off into edges, and constructed into axis-edge-dicts
    edges = {}
    for axis in axes:
        other = a if axis != a else b
        for col,pt_list in pts_by_axis[axis].items():
            pt_list.sort(key=lambda p:p[other])
            for i in range(0,len(pt_list),2):
                v1 = tuple(pt_list[i])
                v2 = tuple(pt_list[i + 1])
                edges[tuple((axis,v1))] = other, v2
                edges[tuple((axis,v2))] = other, v1

    # now derive the polygons, starting at any point.
    axis, edge = next(iter(edges.keys()))
    result, poly = [], [edge]

    while edges:
        if (axis, edge) not in edges:
            # This polygon is now closed. keep it, and move to the next one.
            result.append(poly[:-1])  # if wanted looped, don't slice
            poly = []
            axis, edge = next(iter(edges.keys()))
        else:
            # Get the next edge. change the axis (edge is on a different axis)
            axis, new_edge = edges.pop((axis,edge))
            # delete any old reversed edge.
            del edges[(axis, edge)]
            edge = new_edge

        # add the edge to the existing polygon
        poly.append(edge)
    # capture the final polygon.
    result.append(poly[:-1]) # if wanted looped, don't slice.
    return result

if __name__ == "__main__":
    from mpl_toolkits.mplot3d.art3d import Poly3DCollection
    import matplotlib.pyplot as plt
    from random import shuffle
    pts = [
        (0, 0, 0), (4, 0, 0),
        (1, 1, 0), (2, 1, 0), (3, 1, 0), (4, 1, 0),
        (1, 2, 0), (2, 2, 0), (3, 2, 0), (4, 2, 0),
        (0, 3, 0), (4, 3, 0)
    ]
    # shuffle just to make it different.
    shuffle(pts)
    result = polygonise(pts)
    # all the below is just to show the result
    fig = plt.figure()
    subplot = fig.add_subplot(111, projection='3d')
    subplot.axis('off')
    subplot.scatter([0.6, 3.1], [0.7, 3.3], [0, 0], alpha=0.0)
    subplot.add_collection3d(Poly3DCollection(result, edgecolors='k', facecolors='b', linewidths=1, alpha=0.2))
    fig.tight_layout()
    plt.show()

I think that the loops could be easier, and I'm not convinced that I need to store edges twice, (which means I have to delete the unused one).
Any ideas for tidying the polygonise() method would be welcome.
J. O'Rourke, "Uniqueness of orthogonal connect-the-dots", Computational Morphology, G.T. Toussaint (editor), Elsevier Science Publishers, B.V.(North-Holland), 1988, 99-104. found here


texts: What would be a correct C++ style for function loading file contents?

texts:
bool loadFileContents(const std::string& fileName, std::string &out) {
    bool res = false;
    FILE* file = fopen(fileName.c_str(), "r");
    char buf[128] = { 0 };
    if (file) {
        while (fread(buf, 1, sizeof(buf), file))
            out += std::string(buf);
        res = true;
    }
    fclose(file);
    return res;
}

The rationale behind using std::string for the out parameter is that it handles the buffer underneath. However, I feel like it's a move from C-style, but not quite a C++ one.

Should I consider using some kind of stream for the out param?


texts:
I'm working on a function that extracts information from an XML document and compares to what the user has typed in. Can you suggest any ways in which I can improve it? The variables in the XML file are compared against txtSearch.

function checkXML() {
    var s = "";
    var albumPages = [];

    for (var i = 0; i < xmlalbums.length; i++) {
        var xmlalbum = xmlalbums[i];
        var album_title = dataFromTag(xmlalbum, 'title');
        var artist = dataFromTag(xmlalbum, 'artist');
        var xmltracks = xmlalbum.getElementsByTagName('track');
        for (var t = 0; t < xmltracks.length; t++) {
            var track = xmltracks[t];
            song_title = dataFromTag(track, 'title')
            albumPages[albumPages.length] = artist.toUpperCase() + ':' + album_title.toUpperCase() + ':' + song_title.toUpperCase();
        }
    }

    var resultList = '';
    var resultCount = [];

    for (var i = 0; i < albumPages.length; i++) {
        var searchArtist = albumPages[i].substring(0, albumPages[i].indexOf(":"));
        var searchAlbum = albumPages[i].substring(albumPages[i].indexOf(":") + 1, albumPages[i].lastIndexOf(":"));
        var searchSong = albumPages[i].substring(albumPages[i].lastIndexOf(":") + 1, albumPages[i].length);
        if (searchArtist.indexOf(txtSearch) != -1 || searchAlbum.indexOf(txtSearch) != -1 || searchSong.indexOf(txtSearch) != -1) {
            resultList += "<option>" + searchSong + "</option>"
            resultCount[resultCount.length] = i;
        }
    }

    if (resultList.length == 0) {
        s += "No result found!"
    }
    else if (resultList.length > 0) {
        s += '<select size="' + (resultCount.length + 1) + '" onclick="parent.col3(value);">';
        s += resultList;
        s += '</select>';
    }
    else {
        s += "Awaiting search query..."
    }

    with(document.getElementById('col2').contentDocument) {
        open();
        write(s);
        close();
    }
}


texts: An implementation of parallel workers in Ruby

texts:
Much in the spirit of this question, I have implemented a simple class for parallel workers and wanted to get some feedback on it. Can I make the code even more concise or readable? Are there any hidden problems that I should be aware of?

Worker class

class Worker

    def initialize queue
        @queue = queue

        # Set the "idle state" (returned by the idle? method)
        # and a mutex for accessing it
        @idle_state = false
        @idle_mutex = Mutex.new

        # Set the "exit state" (returned by the done? method)
        # and a mutex for accessing it
        @exit_state = false
        @exit_mutex = Mutex.new

        poll
    end

    # Poll a queue for Proc objects to process
    def poll
        @thread = Thread.new do
            loop do
                while @queue.empty?
                    set_idle true
                    exit 0 if done?
                    sleep 1
                end
                set_idle false
                job = @queue.pop
                job.call
            end
        end
    end

    def done?
        @exit_mutex.synchronize { @exit_state }
    end

    def shut_down
        @exit_mutex.synchronize { @exit_state = true }
        @thread.join
    end

    def idle?
        @idle_mutex.synchronize { @idle_state }
    end

    def set_idle state
        @idle_mutex.synchronize { @idle_state = state }
    end

end

Usage

# Set up a job queue
queue = Queue.new

# Spin up a few workers
workers = []
(1..5).each do
    workers << Worker.new(queue)
end

# Add some jobs to the queue
(1..50).each do |i|
    queue << Proc.new { $stdout.print "Job ##{i}\n" }
end

# Shut down each of the workers once the queue is empty
sleep 0.1 until queue.empty?
workers.each { |worker| worker.shut_down }

References:

Correctness of a minimal parallel workers queue in Ruby


texts: Writing image pixel data to printer code

texts:
I've been trying to take image pixel data and write it out into printer code and my results are rather slow.

Here is a simplified version of what I have so far (image is a PIL Image object of 1200 x 1800 pixels):

# ~36 seconds on beaglebone
f.write(pclhead)
pix = image.getdata()
for y in xrange(1800):
  row = '\xff'*72
  ### vvv slow code vvv ###
  for x in xrange(1200):
    (r,g,b) = pix[y*1200+x]
    row += chr(g)+chr(b)+chr(r)
  ### ^^^ slow code ^^^ ###
  row += '\xff'*72
  f.write(row)
f.write(pclfoot)

I know the loop can be optimized way better, but how?

My code is running on a beaglebone so speed is slower than you'd expect, but composing the complex images takes about 5 seconds. I wouldn't expect my printer code function (which just reorders the data) to take much longer than about 2 or 3 seconds. My first attempt (with getpixel) took 90 seconds. Now I have it down to 36 seconds.  Surely I can make this quite a bit faster yet.

For comparison, just so we can all see where the hold up is, this code runs in 0.1 secs (but, of course, is lacking the important data):

# ~0.1 seconds on beaglebone
f.write(pclhead)
pix = image.getdata()
for y in xrange(1800):
  row = '\xff'*72
  ### vvv substituted vvv ###
  row += '\xff'*3600
  ### ^^^ substituted ^^^ ###
  row += '\xff'*72
  f.write(row)
f.write(pclfoot)

I guess a simplified version of this problem is to rewrite something like the following:

[ (1,2,3), (1,2,3) ... 1200 times ]

into

[ 2, 3, 1, 2, 3, 1, etc... ]

but as a string

"\x02\x03\x01\x02\x03\x01 ... "


texts: Refactor jaccard similarity the "Scala way"

texts:
I'm trying to pick Scala up. This is a simple heuristic that checks a similarity value between two sets. I've done this a million times in Java or Python. The function works, but I'm certain I am not doing this "the Scala way".

val a : List[Int] = List(1,1,2,2,3)
val b : List[Int] = List(1,2,3,4,5)

def calculateBags(a: List[Int], b: List[Int]): Double = {
    val a_counts = a.groupBy(x=>x).map(y=> y._1->y._2.size)
    val b_counts = b.groupBy(x=>x).map(y=> y._1->y._2.size)
    var count = 0
    a_counts.foreach{ x=>
        var k = x._1
        var t = x._2
        if (b_counts.contains(k)) {
            count+= Math.min(t,b_counts(k))
        }
    }
    (count.toDouble)/(a.size+b.size)
}


texts: How can I make this code more readable and efficient?

texts:
How can I rewrite this code to make it more readable and, if possible, more efficient? The conditions are entirely necessary in this problem, but how could I rewrite those if(a != 1) and such?

celula ** verificaNo(celula ** matriz, int linhas, int colunas){
celula ** aux = matriz;
int i, j, k;
int node = 1;
int a = 0;
int b = 0;
int c = 0;

for(i = 0; i < linhas; i++){
    for(j = 0; j < colunas; j++){
        if((i == 0) && (j == 0)){
            aux[i][j].no = node;
        }
        else if((i == 0) && (j != 0)){
            if(aux[i][j-1].peso == 0 && aux[i][j].peso == 0){
                aux[i][j].no = aux[i][j-1].no;
            }
            else if(aux[i][j-1].peso != 0 && aux[i][j].peso == 0){
                for(k = j; aux[i+1][k].peso == 0 && k > 0; k--){
                    if(aux[i][k-1].peso == 0){
                        aux[i][j].no = aux[i][k-1].no;
                        a = 1;
                    }
                }
                if(a != 1){
                    node++;
                    aux[i][j].no = node;
                }
            }
        }
        else if((j == 0) && (i != 0)){
            if(aux[i-1][j].peso == 0 && aux[i][j].peso == 0){
                aux[i][j].no = aux[i-1][j].no;
            }
            else if(aux[i-1][j].peso != 0 && aux[i][j].peso == 0){
                for(k = j; aux[i][k].peso == 0 && k < colunas; k++){
                    if(aux[i-1][k+1].peso == 0){
                        aux[i][j].no = aux[i-1][k+1].no;
                        b = 1;
                    }
                }
                if(b != 1){
                    node++;
                    aux[i][j].no = node;
                }
            }
        }
        else if(aux[i][j].peso == 0 && aux[i-1][j].peso == 0 && i != 0){
            aux[i][j].no = aux[i-1][j].no;
        }
        else if(aux[i][j].peso == 0 && aux[i][j-1].peso == 0 && j != 0){
            aux[i][j].no = aux[i][j-1].no;
        }
        else if(aux[i][j].peso == 0){
            for(k = j; aux[i][k].peso == 0 && k < colunas; k++){
                if(i != 0){
                    if(aux[i-1][k].peso == 0){
                        aux[i][j].no = aux[i-1][k].no;
                        c = 1;
                    }
                }
            }
            if(c != 1){
                node++;
                aux[i][j].no = node;
            }
        }
    }
}
return aux;
}


texts:
I have written a simple JS module "loader" (loader is in quotes because it doesn't actually load the files) that is designed to resolve simple dependencies between modules. It is heavily inspired by module.js and takes some of it's design from it.

Here is the code itself:

(function() {
  function create() {
    var definitions = {},
        instances = {};

    // Returns whether or not a module with the provided id is defined.
    var defined = function(id) {
      return definitions.hasOwnProperty(id);
    };

    // Define a module with the provided id and definition.
    var define = function(id, definition) {
      if(defined(id)) {
        throw new Error('module already defined: ' + id);
      }

      definitions[id] = definition;
    };

    // Undefine a module with the provided id.
    var undefine = function(id) {
      if (!defined(id)) {
        throw new Error('module not defined: ' + id);
      }

      delete definitions[id];
      delete instances[id];
    };

    // Require a module with the provided id.
    var require = function(id) {
      var stack = [];

      var internalRequire = function(id) {
        if(!defined(id)) {
          throw new Error('module not defined: ' + id);
        }

        // If we have already seen this id on the require stack, we've got
        // some form of cyclic dependency.
        if (stack.indexOf(id) !== -1 && stack.push(id)) {
          throw new Error('cyclic dependency: ' + stack.join(' -> '));
        } else {
          stack.push(id);
        }

        // If we already have an instance for this module, return it.
        if (instances.hasOwnProperty(id)) {
          return instances[id];
        } else if (typeof(definitions[id]) === 'function') {
          // Otherwise if our definition is a function, call it and pass the
          // require method to it.
          return instances[id] = definitions[id].call(null, internalRequire);
        } else {
          // Otherwise just return the definition itself (useful for objects
          // e.g. constants).
          return instances[id] = definitions[id];
        }
      };

      return internalRequire(id);
    };

    return {
      define: define,
      undefine: undefine,
      require: require
    };
  }

  window.module = create();
})();

And some example usage:

module.define('person', function() {
  var Person = function(name) {
    Object.defineProperty(this, 'name', {
      value: name
    });
  };

  Person.prototype.speak = function(text) {
    return this.name + ': ' + text;
  };

  return Person;
});

module.define('main', function(require) {
  var Person = require('person');

  var jack = new Person('Jack'),
      rocky = new Person('Rocky');

  console.log(jack.speak('Hi Rocky!'));
  console.log(rocky.speak('Hi Jack!'));
});

I don't really have any "burning questions" about my code; I'd just like some feedback on what people think of it and whether anyone can see any improvements.


texts:
I have a simple list and want to filter it by a specific key. But I guess my for loop solution is not an efficient way. I'm searching an other way or one best practice.

types = [
    {
        'name':'John',
        'surname':'Doe',
        'age':36,
        'type':'customer'
    },
    {
        'name':'Jane',
        'surname':'Doe',
        'age':31,
        'type':'supplier'
    }
]

Normally I'm iterating over on list and determining according to "type" field.

new_types = {}
for t in types:
    new_types[t['type']] = t

My purpose is also below but I'm looking another iterating and filtering way for upper loop. I have created the result and expectation is:

{
    'customer':{
        'type':'customer',
        'age':36,
        'surname':'Doe',
        'name':'John'
    },
    'supplier':{
        'type':'supplier',
        'age':31,
        'surname':'Doe',
        'name':'Jane'
    }
}


texts:
I am making a cookie clicker type game as a small project, within Xcode, written in Swift. I have a been developing a function which will turn a Int64() into a 4 digit long smaller version, to fit into text boxes.

For example, the function would turn 1,340,000 into £1.34M. The issue is, this could have to happen for a long time; the game could last long enough to the point where I go past conventional values like 100 trillion, and such. This is the function for when you click on one of the buttons to buy a building:

@IBAction func planetClicked(_ sender: Any) {
    let cost = Int64(buildingConstants.planetConstantCost)
    if moneyConstants.money >= cost {
        moneyConstants.money = moneyConstants.money - cost
        buildingLevels.planetNumber = buildingLevels.planetNumber + 1
        let originalValue = 5100000000
        let newValue = round(Double(originalValue) * pow(1.15, Double(buildingLevels.planetNumber)))
        buildingConstants.planetConstantCost = Int64(newValue)
        if String(newValue).characters.count >= 4 {
            if String(newValue).characters.count >= 7 {
                if String(newValue).characters.count >= 10 {
                    if String(newValue).characters.count >= 13 {
                        //Assume this goes on for as long as I need it to
                    } else {
                        planetCostLabel.text = turnIntoBil(newValue: String(newValue))
                    }
                } else {
                    planetCostLabel.text = turnIntoMil(newValue: String(newValue))
                }
            } else {
                planetCostLabel.text = turnIntoK(newValue: String(newValue))
            }
        } else{
            planetCostLabel.text = "£" + String(buildingConstants.planetConstantCost) + ".00"
        }

    }
}

buildingConstants is a structure:

struct buildingConstants {
    static var jitterClickConstantCost = NSInteger()
    static var macrosConstantCost = NSInteger()
    static var autoClickerConstantCost = NSInteger()
    static var anotherPCConstantCost = NSInteger()
    static var workerConstantCost = NSInteger()
    static var houseConstantCost = Int64()
    static var officeConstantCost = Int64()
    static var skyriseConstantCost = Int64()
    static var planetConstantCost = Int64()
}

buildingLevels is also a structure:

struct buildingLevels {
    static var jitterClickNumber = NSInteger()
    static var macrosNumber = NSInteger()
    static var autoClickerNumber = NSInteger()
    static var anotherPCNumber = NSInteger()
    static var workerNumber = NSInteger()
    static var houseNumber = NSInteger()
    static var officeNumber = NSInteger()
    static var skyriseNumber = NSInteger()
    static var planetNumber = NSInteger()
}

These are my value changing functions:

func turnIntoK(newValue: String) -> String {
    let firstChar = String(newValue)[0]
    let secondChar = String(newValue)[1]
    let thirdChar = String(newValue)[2]
    let fourthChar = String(newValue)[3]
    let string: String = "£" + firstChar + "." + secondChar + thirdChar + fourthChar + "k"
    return string
}

func turnIntoMil(newValue: String) -> String {
    let firstChar = String(newValue)[0]
    let secondChar = String(newValue)[1]
    let thirdChar = String(newValue)[2]
    let fourthChar = String(newValue)[3]
    let string: String = "£" + firstChar + "." + secondChar + thirdChar + fourthChar + "M"
    return string
}

func turnIntoBil(newValue: String) -> String {
    let firstChar = String(newValue)[0]
    let secondChar = String(newValue)[1]
    let thirdChar = String(newValue)[2]
    let fourthChar = String(newValue)[3]
    let string: String = "£" + firstChar + "." + secondChar + thirdChar + fourthChar + "M"
    return string
}

Is there a loop that I could possibly make which would make my code run smoother (instead of a lot of nested ifs)? Also, does my code look like it could be improved so it doesn't take up too much RAM on someone's phone if they were to use it?


texts: Rails create create default database records

texts:
In my application I have an accounts model:

class Account < ActiveRecord::Base
  belongs_to :user
  has_many :invoices
end

The Account model belongs to the User model. After the user is created, some default accounts must be created:

class User < ActiveRecord::Base
  has_many :accounts

  after_create do
    Account.create(name: "Repairs",user: self)
    Account.create(name: "Supplies", user: self)
  end
end

Invoices can then be assigned to one of these initial accounts:

class Invoice < ActiveRecord::Base
  belongs_to :accounts
end

Is this the proper way to to create the default accounts?


texts: Word ladder implemented using stack and queue

texts:
My function outputLadder function basically takes in a start and end string and generates the shortest word ladder from that.

It is iterating through a std::list containing over 3600 words read into it from a text file and seems to take a very long time.

What can I do to make my function faster while still maintaining a stack and queue implementation of the word ladder?

Here is the link to what the text file contains: http://textuploader.com/dkacm

Here is a video of the output which shows how long it takes.

Measuring it with clock() it takes about 8 seconds to find the shortest word ladder for style and crazy.

void WordLadder::outputLadder(const string &start, const string &end)
{
    stack<string> words;
    words.push(start);

    queue<stack<string>> ladder;
    ladder.push(words);

    while (!ladder.empty())
    {
        for (list<string>::iterator i = dictionary.begin(); i != dictionary.end(); ++i)
        {
            if (oneDiff(*i, ladder.front().top()))
            {
                if (*i == end)
                {
                    stack<string> output;

                    while (!ladder.front().empty())
                    {
                        output.push(ladder.front().top());
                        ladder.front().pop();
                    }

                    while (!output.empty())
                    {
                        cout << output.top() << " ";
                        output.pop();
                    }

                    cout << *i << endl;

                    return;
                }
                else
                {
                    stack<string> temp = ladder.front();
                    temp.push(*i);
                    ladder.push(temp);
                    i = dictionary.erase(i);
                }
            }
        }

        ladder.pop();
    }

    cout << "No word ladder exists for this word." << endl;
}

bool WordLadder::oneDiff(const string &dictWord, const string &stackWord)
{
    int count = 0;

    for (int i = 0; i < stackWord.size(); ++i)
    {
        if (dictWord.at(i) != stackWord.at(i))
        {
            ++count;
        }
    }

    if (count <= 1)
    {
        return true;
    }

    return false;
}


texts: Iterating over unequal unordered pairs in one collection

texts:
This code kinda hurts my feelings -- everything else in my code is done in neat one-liners, exploiting algorithms and, sometimes boost::bind, except for this piece. To say nothing about awkward if(b!=a).

Is there a better way to do the task?

#include <iostream>
#include <list>
using namespace std;

int main()
{
    int arr[] = {1,2,3,4,5,6};
    list<int> lst(arr,arr+sizeof(arr)/sizeof(int));

    for(list<int>::iterator a = lst.begin(); a != lst.end();a++)
    {
            for(list<int>::iterator b = a; b != lst.end(); b++)
                    if(b != a) cout << " ("<<*a<<","<<*b<<")";
            cout << "\n";
    }
    return 0;
}


texts: How can I make my program that calculates π faster?

texts:
For my first Raku program, I thought it might be a fun challange to port over a program I'd written in C# about two years ago, and I was right: it was.
There's just one problem: while the C# program runs in 5 seconds, the Raku program takes nearly 5 minutes. I think the Raku program is doing more or less the same as the C# code, and so it should be equally fast (or equally slow, depending on how you look at it).
Here's my code:
use v6;

class Point {
    has Num $.x;
    has Num $.y;

    method is-inside-unit-circle(--> Bool) {
        $!x²+$!y² <= 1;
    }
}

sub random-points(Int $count --> Seq) {
    gather for 0..^$count {
        take Point.new(x => 1.rand.Num, y => 1.rand.Num);
    }
}

sub compute-pi(Int $batch --> Seq) {
    my Num $total = 0e0;
    my Num $count = 0e0;

    gather for 0..^∞ {
        my Seq $pointsInside = random-points($batch).grep: *.is-inside-unit-circle;

        $total += $batch;
        $count += $pointsInside.elems;
        my Num $ratio = $count / $total;

        take $ratio * 4;
    }
}

{ say "π ≈ $_" } for compute-pi(100_000).head(500);

And here's part of the output:
% time raku estimation.raku
π ≈ 3.12912
π ≈ 3.12874
π ≈ 3.1326533333333333
…
π ≈ 3.1419357429718877
π ≈ 3.1419323446893785
π ≈ 3.14193696
raku estimation.raku  272,98s user 1,78s system 100% cpu 4:34,76 total

My two questions are:

How can I make it faster?
Is my code idiomatic, and how could I make it more idiomatic?

For completeness' sake, here's the C# code:
using System;
using System.Collections.Generic;
using System.Linq;

internal class Program
{
    internal readonly struct Point
    {
        private readonly double _x;
        private readonly double _y;

        internal Point(double x, double y)
        {
            _x = x;
            _y = y;
        }

        internal bool IsInsideUnitCircle()
        {
            return Math.Pow(_x, 2) + Math.Pow(_y, 2) <= 1;
        }
    }

    internal class PointGenerator
    {
        private readonly Random _random;

        public PointGenerator() => _random = new Random();

        public IEnumerable<Point> GeneratePoints(int count)
        {
            for (var i = 0; i < count; i++)
            {
                yield return new Point(_random.NextDouble(), _random.NextDouble());
            }
        }
    }

    private static IEnumerable<double> ComputePi(int batch)
    {
        var pointGenerator = new PointGenerator();

        var total = 0.0;
        var count = 0.0;

        while (true)
        {
            var pointsInside = pointGenerator.GeneratePoints(batch)
                .Where(point => point.IsInsideUnitCircle());

            total += batch;
            count += pointsInside.Count();
            var ratio = count / total;

            yield return ratio * 4;
        }
    }

    private static void Main()
    {
        foreach (var estimate in ComputePi(100_000).Take(500))
        {
            Console.WriteLine($"π ≈ {estimate}");
        }
    }
}

And part of its output:
% time dotnet run -c Release
π ≈ 3,13948
π ≈ 3,13904
π ≈ 3,138786666666667
…
π ≈ 3,1415373493975904
π ≈ 3,14154501002004
π ≈ 3,14155416
dotnet run -c Release  5,43s user 0,30s system 103% cpu 5,555 total


texts:
It has been a very long time since I've used Python.

What I'm looking for: I would like to create a 6-by-6 random matrix where each component is either 1 or 2, so that there are 18 ones and 18 twos.

Attempt:

import numpy
import random

array = numpy.zeros((6, 6))
while (array == 1).sum() != 18 or (array == 2).sum() != 18:
    for i in range(0, 6):
        for j in range(0, 6):
            array[i][j] = random.randint(1, 2)
print array

Sure, this works. But this seems to me to be extremely inefficient, as the code is literally having to insert new matrix values until the number of ones/twos is 18. How can I make this more efficient?


texts: Prompting for five test scores and printing the average

texts:
I am not sure how to properly make this readable. I have been trying to find examples online but I cannot find any that are specific to this simple program.

import java.util.Scanner;

public class KifahUnit3 {

    public static void main(String[] args) {

        Scanner stdIn = new Scanner(System.in);
        String first;  //first name
        String last;  //last name
        String full;  //full name
        Boolean nameMatch = false;
        int score1;
        int score2;
        int score3;
        int score4;
        int score5;
        int totalScore;
        int x;
        double scoreAverage;
        System.out.print("Please enter your first name: ");
        first = stdIn.next();
        System.out.print("Please enter your last name: ");
        last = stdIn.next();
        System.out.println(first + " " + last);
        nameMatch = first.equals(last);
        if (nameMatch == true) {
            System.out.println(
                    "Hello, " + first + " " + last + " "
                    + "your first and last name are the same.");
        } else {
            System.out.println(
                    "Hello, " + first + " " + last + " "
                    + "your first and last name are different.");
            full = first + last;
            System.out.println("The length of your first name is: " + first.length());
            System.out.println("The length of your full name is: " + full.length());
            System.out.println("Your initials are " + first.charAt(0) + last.charAt(0));

            System.out.println("Please enter your test scores");
            System.out.print("Score 1= ");
            score1 = stdIn.nextInt();
            System.out.print("Score 2= ");
            score2 = stdIn.nextInt();
            System.out.print("Score 3= ");
            score3 = stdIn.nextInt();
            System.out.print("Score 4= ");
            score4 = stdIn.nextInt();
            System.out.print("Score 5= ");
            score5 = stdIn.nextInt();
            scoreAverage = (score1 + score2 + score3 + score4 + score5) / 5;
            System.out.println(
                    "Score 1= " + score1 + "; " + "Score 2= " + score2 + "; " + "Score 3= "
                    + score3 + ";  " + "Score 4= " + score4 + "; " + "Score 5= " + score5);
            totalScore = score1 + score2 + score3 + score4 + score5;
            x = 10;
            System.out.println("Total= " + totalScore);
            System.out.println("Average: " + (scoreAverage + x));
            System.out.println("Ooops! Made a mistake. Your average is:  " + scoreAverage);

        }
    } // end main
} // end class KifahUnit3


texts: Filter array of objects by comparing nested object properties

texts:
I recently had a problem whereby I wanted to filter objects in an array by comparing the values of nested properties of each object to see if there were duplicates.

I have tried to explain as clearly as possible the scenario below and the solution I came up with. I wondering if it's possible to improve this solution and if so, how?

Example:

let articles = [{dateAdded: "31-5-1989", readId: 123, article: { id: 1}}, {dateAdded: "31-5-1989", readId: 124, article: { id: 2}}, {dateAdded: "31-5-1989", readId: 125, article: { id: 1}}]

In this array, you can see each object has a readId and an articleId. The first and last objects in the array have a different readId but a matching articleId. We want to return every object in this array unless we have already returned an object with the same articleId.

Here is my solution:

const removeDuplicatesbyArticleId = articles => {
  let articleIdsArray = [];
  let finalArray = [];

  articleResponse.reading.map(element => {
    if (!articleIdsArray.includes(element.article.id)) {
      articleIdsArray.push(element.article.id);
      finalArray.push(element);
    }
  });

  let filteredArticleResponse = articles;
  filteredArticleResponse.reading = finalArray;
  return filteredArticleResponse;
};

All I'm doing here is looping through the array, checking if the articleId exists in the articleIdsArray and if not, pushing this onto finalArray and then repeating before returning finalArray at the end of the loop.

This solution feels a little crude, I'd be really grateful if anyone could suggest an alternative(s) solution(s) that is easier to read, better for performance, or both!

I apologise if this is a repeat, from much searching I couldn't find a question and answer that matched my specific case.


texts:
I am working on designing a simple version of a Connect 4 game.
Here is my first draft code.
I would like some feedback on it, and also required modification for these follow up questions:

Add some intelligence in the players to select the column optimally.
How will you make the game generic so that it can check for 16 points in a row/column/diagonal
How will you handle a huge grid?

Regarding item3, I think since I am not storing the whole grid, my approach is scalable.
I appreciate for any recommendations or feedback.
class Connect4 {

vector <pair<int, map< pair<int,int>,int > > > rows;
vector <pair<int, map< pair<int,int>,int > > > cols;
vector <pair<int, map< pair<int,int>,int > > > diag;
int r;
int c;
int player;
public:
  Connect4 (int rr, int cc):r(rr), c(cc){
     rows = vector <pair<int, map< pair<int,int>,int > > >  (rr);
     cols = vector <pair<int, map< pair<int,int>,int > > > (cc);
     diag = vector <pair<int, map< pair<int,int>,int > > > (min (rr,cc));
  }

  int move(int row, int col, int player){
      int score = (player ==1)?1:-1;   // count player-1 socres with positive and player-2 with negative numbers

      rows[row].first +=score;
      rows[row].second[{row,col}]=score;
      if (abs(rows[row].first) ==4 && isValid(rows[row].second) )
            return player;

      cols[col].first += score;
      cols[col].second[{row,col}]=score;
      if (abs(cols[col].first) ==4 && isValid(cols[col].second) )
            return player;

      if(row ==col+2){
        diag[0].first +=score;
        if (abs(diag[0].first) ==4 ) //if the score is 4 no extra checking is needed
            return player;

      } else if (row ==col+1) {
        diag[1].first += score;
        if (abs(diag[1].first) ==4 && isValid(diag[1].second) )
            return player;

      } else if (row ==col) {
         diag[2].first += score;
         if (abs(diag[2].first) ==4 && isValid(diag[2].second) )
            return player;

      } else if (row+1 ==col) {
         diag[3].first += score;
         if (abs(diag[3].first) ==4 && isValid(diag[3].second) )
            return player;

      } else if (row+2 ==col) {
         diag[4].first += score;
         if (abs(diag[4].first) ==4 && isValid(diag[4].second) )
            return player;

      } else if (row+3 ==col) {
        diag[5].first += score;
        if (abs(diag[5].first) ==4 )
            return player;
      }
  }

  bool isValid(map<pair<int,int>, int> verify) {
      int cnt=1;
      map<pair<int,int>, int>::iterator itr = verify.begin();
      int prev= itr->second;
      itr++;
      for (;itr!= verify.end(); ++itr){
        int score = itr->second ;
        if(prev == score){
            cnt++;
            if(cnt ==4)
              return true;
        } else {
           cnt=0;
        }
        prev = score;
      }
      return (cnt>=4);
  }
};

The logic behind calculating the diagonal is discussed here:
in a grid of 6x7, we can have diagonal score of >=4 only in following matrix indices:
If we have same scores in following (X,Y):

(2,0), (3,1), (4,2), (5,3)                ->  diag[0]
(1,0), (2,1), (3,2), (4,3), (5,4)
(0,0), (1,1), (2,2), (3,3), (4,4), (5,5)
(0,1), (1,2), (2,3), (3,4), (4,5), (5,6)
(0,2), (1,3), (2,4), (3,5), (4,6)
(0,3), (1,4), (2,5), (3,6)                ->  diag[6]


texts: Mailinator automatic checker for new e-mails

texts:
I'm making a little script to run on the background and notify me when I received a new email in a mailinator inbox. I want to eventually daemonise it, but for now it just runs like a regular script.

Could you give me some pointers about the code itself, the code structure and so on? I'm not sure if I should have my functions in a particular order, they're quite randomly scattered around the script at the moment.

#!/usr/bin/env python3
#encoding: utf-8

import time
import argparse
import requests

from IPython import embed as qq

try:
    from apikey import API
except ImportError:
    API = input('Please provide your API key ')

CHECKING_FREQ = 30

def parse_arguments():
    parser = argparse.ArgumentParser(description="Mailinator inbox checker")
    parser.add_argument('inbox', nargs=1, help='The inbox that you want to check')
    return parser.parse_args()

def is_new(emails):
    # Here I could probably use any() instead of next()
    # but I'm thinking I might want the email itself later on
    return next((email for email in emails
                 if email['seconds_ago'] <= CHECKING_FREQ),
                False)

def check_inbox(inbox):
    inbox_page = get_inbox(inbox)
    return inbox_page['messages']

def wait_email(inbox):
    while 1:
        emails = check_inbox(inbox)
        if is_new(emails):
            print('New email received.')
        time.sleep(CHECKING_FREQ)

def get_inbox(inbox):
    return requests.get('https://api.mailinator.com/api/inbox?'
                        'to={inbox}&token={api}'.format(
                            inbox=inbox,
                            api=API)).json()

def start_daemon():
    ...

def main():
    args = parse_arguments()
    start_daemon()
    wait_email(args.inbox[0])

if __name__ == '__main__':
    main()


texts:
My aim is to merge k different sorted array with unique elements and I want a code review about it, here is my code below which is written in java;

public class MergeDemo {

    public static void main(String[] args) {
        int[] arr1 = { 1, 2, 6, 7, 18, 19 };
        int[] arr2 = { 3, 4, 5, 8, 9 };
        int[] arr3 = { 10, 11, 12 };
        int[] arr4 = { 13, 14, 15, 20};
        int[] arr5 = { 16, 17};

        int[][] arrays = { arr1, arr2, arr3, arr4, arr5 };

        handleAnswer(arrays);
    }

    public static void handleAnswer(int[][] arrays) {
        System.out.println("List of arrays to be merged;");
        System.out.println("****************************");
        for(int i = 0; i < arrays.length; i++) {
            System.out.printf("Array [%d]: ", i);
            printArray(arrays[i]);
        }

        System.out.println("");
        System.out.println("Merged array;");
        System.out.println("*************");
        printArray(merge(arrays));
    }

    public static void printArray(int[] array) {
        for(int i = 0; i < array.length; i++)
            System.out.printf("%d ", array[i]);
        System.out.print('\n');
    }

    /*
     * Merges k sorted arrays with arbitrary lengths
     * Calls overloaded merge method with two parameters
     */
    private static int[] merge(int[][] arrays) {
        int[] mergeArray = new int[arrays[0].length];
        System.arraycopy(arrays[0], 0, mergeArray, 0, arrays[0].length);

        for(int i = 1; i < arrays.length; i++) {
            mergeArray = merge(mergeArray, arrays[i]);
        }

        return mergeArray;
    }

    /*
     * Merges two sorted arrays assuming
     * they have unique elements
     */
    private static int[] merge(int[] arr1, int[] arr2) {
        int left = 0;
        int right = 0;

        int[] mergeArr = new int[ arr1.length + arr2.length ];
        int index = 0;

        while(index != mergeArr.length){
            if(left == arr1.length) {
                while(right != arr2.length) {
                    mergeArr[index++] = arr2[right++];
                }
            } else if(right == arr2.length) {
                while(left != arr1.length) {
                    mergeArr[index++] = arr1[left++];
                }
            } else {
                if(arr1[left] < arr2[right]) {
                    mergeArr[index++] = arr1[left++];
                } else {
                    mergeArr[index++] = arr2[right++];
                }
            }
        }

        return mergeArr;
    }
}

And sample output of the code above;

List of arrays to be merged;
****************************
Array [0]: 1 2 6 7 18 19
Array [1]: 3 4 5 8 9
Array [2]: 10 11 12
Array [3]: 13 14 15 20
Array [4]: 16 17

Merged array;
*************
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20


texts: Class or not in Page Scraper (Python BeautifulSoup)

texts:
I am trying to figure out whether the below is better than just having a raw script or just a script with functions.
class WebsiteImages(object):

    def __init__(self,photographer,Website_url):
        self.photographer = photographer
        self.Website_url = Website_url

    def GetNumberOfResultPages(self):
        #Get the exact number of pages in the results
        from selenium import webdriver
        browser = webdriver.Firefox()
        browser.get(self.Website_url)
        last_number_page = browser.find_elements_by_xpath("//span[@class='search-pagination__last-page']")
        for i in last_number_page:
            number_of_pages = i.text
        return number_of_pages

    def GetImageIds(self):
        number_of_pages = self.GetNumberOfResultPages()
        Website_ids = []
        self.number_of_pages = number_of_pages
        #For each page get the image IDs
        import urllib
        from bs4 import BeautifulSoup
        import sys
        from time import sleep
        for page in range(1,int(number_of_pages)+1):
            #Extract the image id only and save it in file
            url = urllib.request.urlopen(self.Website_url+'&page='+str(page)+'&sort=best')
            sleep(1)
            content = url.read()
            soup = BeautifulSoup(content, 'lxml')
            #search on page for div class and extract the id between the gi-asset attribute
            images_found = soup.find_all('gi-asset') #gi-asset is the HTML object that contains the image and the id in the search results
            for i in range(len(images_found)):  #range(len(images_found))
                Website_id = images_found[i].get('data-asset-id') #data-asset-id' is the HTML object that contains the ID
                if Website_id not in 'placeholder':
                    Website_ids.append(Website_id)
        return Website_ids

# Define some photographers
john_smith = WebsiteImages('John%20Smith', 'https://www.WebsiteImages.co.uk/search/photographer?assettype=image&photographer=John%20smith')

# Now we can get to the image IDs easily
#print(john_smith.GetNumberOfResultPages())
print(john_smith.GetImageIds())

The idea of using the class was to make the script more organised and the outputs accessible for different search results. Example below:
one_guy = WebsiteImages('One%20Guy', 'https://www.WebsiteImages.co.uk/search/photographer?photographer=John%20smith')

two_guy = WebsiteImages('Two%20Guy', 'https://www.WebsiteImages.co.uk/search/photographer?photographer=John%20smith')


texts:
I'm working with some math-heavy code in JavaScript. I just realized that there's a render that currently takes about 30 minutes. 95% of that time is spent in a single ~40 line function that I've pasted below. I am not extremely well-versed in JavaScript math optimization, so my first attempts to optimize this code haven't gone wonderfully.

I would love any pointers as to what in here is slowing things down. I have good reason to believe that things are non-optimal because the same code in Python runs about 30x faster and JS is not a slow language.

// return cost and gradient, given an arrangement
costGrad: function(Y) {
  var N = this.N; // About 5000 long
  var dim = this.dim; // About 300 long
  var P = this.P; // About 5000^2 long

  var pmul = this.iter < 100 ? 4 : 1; // trick that helps with local optima

  // compute current Q distribution, unnormalized first
  var Qu = zeros(N * N);
  var qsum = 0.0;
  for(var i=0;i<N;i++) {
    for(var j=i+1;j<N;j++) {
      var dsum = 0.0;
      for(var d=0;d<dim;d++) {
        var dhere = Y[i][d] - Y[j][d];
        dsum += dhere * dhere;
      }
      var qu = 1.0 / (1.0 + dsum); // Student t-distribution
      Qu[i*N+j] = qu;
      Qu[j*N+i] = qu;
      qsum += 2 * qu;
    }
  }
  // normalize Q distribution to sum to 1
  var NN = N*N;
  var Q = zeros(NN);
  for(var q=0;q<NN;q++) { Q[q] = Math.max(Qu[q] / qsum, 1e-100); }

  var cost = 0.0;
  var grad = [];
  for(var i=0;i<N;i++) {
    var gsum = new Array(dim); // init grad for point i
    for(var d=0;d<dim;d++) { gsum[d] = 0.0; }
    for(var j=0;j<N;j++) {
      cost += - P[i*N+j] * Math.log(Q[i*N+j]); // accumulate cost (the non-constant portion at least...)
      var premult = 4 * (pmul * P[i*N+j] - Q[i*N+j]) * Qu[i*N+j];
      for(var d=0;d<dim;d++) {
        gsum[d] += premult * (Y[i][d] - Y[j][d]);
      }
    }
    grad.push(gsum);
  }

  return {cost: cost, grad: grad};
}

For those that are curious to see more, this is from the wonderful tsnejs library from Andrej Karpathy.


texts:
I've made a little implementation of an undirected graph, using FIFO lists, for one of my homeworks. Never really knew how to write a proper FIFO data structure, so I would be glad to see some opinion of yours.

#include <iostream>
#include <fstream>

using namespace std;

class Graph
{
    class Node
    {
        struct adj
        {
            int data;
            adj* next;
        };

        adj* head;
        adj* tail;
        int num;
    public:
        Node();
        Node(const Node&);
        Node& operator=(const Node&);
        bool is_empty();
        bool is_leaf();
        void push(int);
        int pop();
        void print();
        ~Node();
    };

    int num_nodes;
    Node* nodes;
public:
    Graph(int);
    Graph(ifstream&);
    Graph(const Graph&);
    void add_edge(int, int);
    Node& operator[](int);
    void print();
    ~Graph();
};

Graph::Node::Node()
{
    head=NULL;
    tail=NULL;
    num=0;
}

Graph::Node::Node(const Node& F)
{
    head=NULL;
    tail=NULL;
    num=0;

    adj* tmp=F.head;

    while(tmp)
    {
        push(tmp->data);
        tmp=tmp->next;
    }
}

Graph::Node& Graph::Node::operator=(const Node& F)
{
    if(this!=&F)
    {
        head=NULL;
        tail=NULL;
        num=0;

        adj* tmp=F.head;

        while(tmp)
        {
            push(tmp->data);
            tmp=tmp->next;
        }
    }

    return *this;
}

bool Graph::Node::is_empty()
{
    return head==NULL;
}

bool Graph::Node::is_leaf()
{
    return num==1;
}

void Graph::Node::push(int value)
{
    adj* tmp=new adj;

    tmp->data=value;
    tmp->next=NULL;

    if(is_empty())
    {
        head=tmp;
    }
    else
    {
        tail->next=tmp;
    }

    tail=tmp;

    num++;
}

int Graph::Node::pop()
{
    if(!is_empty())
    {
        adj* tmp=head;

        head=head->next;

        int value=tmp->data;

        delete tmp;

        num--;

        return value;
    }
    else
    {
        return -1;
    }
}

void Graph::Node::print()
{
    adj*tmp=head;

    while(tmp)
    {
        cout<<tmp->data<<" ";
        tmp=tmp->next;
    }
    cout<<endl;
}

Graph::Node::~Node()
{
    while(!is_empty())
    {
        pop();
    }
}

Graph::Graph(int num_nodes)
{
    this->num_nodes=num_nodes;
    nodes=new Node[num_nodes+1];
}

Graph::Graph(ifstream& f)
{
    f>>num_nodes;

    nodes=new Node[num_nodes+1];

    int start, end;

    while(f>>start>>end)
    {
        add_edge(start, end);
    }
}

Graph::Graph(const Graph& G)
{
    num_nodes=G.num_nodes;

    nodes=new Node[num_nodes+1];

    for(int i=1; i<=num_nodes; i++)
    {
        nodes[i]=G.nodes[i];
    }
}

void Graph::add_edge(int start, int end)
{
    nodes[start].push(end);
    if(start!=end)
    {
        nodes[end].push(start);
    }
}

Graph::Node& Graph::operator[](int i)
{
    return nodes[i];
}

void Graph::print()
{
    for(int i=1; i<=num_nodes; i++)
    {
        nodes[i].print();
    }

    cout<<endl;
}

Graph::~Graph()
{
    delete[] nodes;
}

int main()
{
    ifstream f("graph.txt");

    Graph G(f);

    G.print();

    return 0;
}


texts: Still pulling information from XML to insert into Word Document inside 3rd party application

texts:
Follow up to This Question

I took some very good advice and changed my code around a little bit and eliminated some If statements.

I am not retrieving very much information but it looks so skinny now.

Is this a good thing?  Is there something that I should add to the code?

Dim phoneNode
Dim phoneNodeList
ReturnData = ""

Set phoneNodeList = XmlDoc.SelectNodes("/Record/Case/CaseFormsLoad/PartyLoad/Party/PartyPhones/Phone")
If phoneNodeList.Length > 0 Then
    For Each phoneNode In phoneNodeList
        If phoneNode.GetAttribute("ConfidentialFlag") = "True" Then
            ReturnData = ReturnData & phoneNode.Getattribute("PhoneNum") & VbCrLf
        End If
    Next
End If

This code is very readable and simple.  Is there anything that I can do to make it shorter, and should I make it shorter?  it is a Script and not a fully compiled code.


texts: Searching has_and_belongs_to_many relations for article categories

texts:
I have Article and Category, with a has_and_belongs_to_many relation between the two.

I want to use Article.in_categories(category_ids) to get any Article that is in any of the category_ids passed, and I want to handle the possibility of category_ids being nil in a way that all Article items are returned. The category_ids value is coming from a form, and I want the user to be able to ignore the Category selection part of the form if they do not want to limit their selection by that criteria.

I currently have this in place on the Article model:

def self.in_categories(category_ids = nil)
  category_ids.blank? ? all : includes(:categories).where(categories: { id: category_ids })
end

If I do not have the check for category_ids being nil, then it will only return the Article items that are not in any Category.

I do not want to manually set category_ids = [1,2,3] (for example) in the method call, because a Category can be added/removed.

Is there a better way of handling this than the way I already do?


texts:
I have built a calendar application just with jQuery. The script file is on Github. The code works perfectly fine and I have tested it. Please feel free to clone and test it as well.

I am uncertain on the logic that I have used for building this application.

Basically, I have used a table and for storing the dates and I have appended dates w.r.t day (Mo, Tu ... Su).

for(var rowNo=0; rowNo<dayRows-1;rowNo++){
   $(".tableBody", config.container).append("
"+ tank.weeks['Mo'].date[rowNo] +"	"+ tank.weeks['Tu'].date[rowNo]
+"	"+ tank.weeks['We'].date[rowNo] +"	"+ tank.weeks['Th'].date[rowNo]
+"	"+ tank.weeks['Fr'].date[rowNo] +"	"+ tank.weeks['Sa'].date[rowNo]
+"	"+ tank.weeks['Su'].date[rowNo] +"
");
}

The calendar should scroll to the present day and I am diving id for every cell and making the control to go there when the calendar is opened.

var currentDate = new Date();
var idInfo = currentDate.toDateString().split(" ");
var scrollingTo = idInfo[2]+idInfo[1]+idInfo[3];

/*Scrolling to the Present/selected date*/
        var flag=true;
        $("."+config.inputBoxName)
        .focusin(function(){

            $(".container", config.container).show();
            $(".bodyContainer", config.container).show();
            if(flag){
             $("."+config.inputBoxName).val(curDate +"-"+ config.monthNumber[config.monthName[currentDate.getMonth()].slice(0,3)] +"-"+ currentDate.getFullYear());
            $(".bodyContainer", config.container).scrollTop($('.'+scrollingTo, config.container).offset().top - ((bodyHeight-80)+(config.numOfDiabledRows)*40));
             flag = false;
            } else {
                $(".bodyContainer", config.container).scrollTop($('.'+scrollingTo)/*.position().top +(config.numOfDiabledRows)*40*/);
            }
        });

Is this the proper approach? If not, what would be more appropriate or correct way this application could be built?


texts: Simple table sorting using plain Javascript

texts:
This is a simple and clean script for sorting a specific column in a table. You could edit and parametrize it to add more customization, but I wanted to share the base concept.

Base concept (I think its a pretty cool 3 line code):

t = document.getElementById('myTable');
[...t.tBodies[0].rows] //Transforming HTMLCollection to an Array
.sort( (a,b) => a.cells[0].textContent  t.tBodies[0].appendChild(r)) //Appending the rows themselves, so the table is reordered without needing to create any new element

Parametrization example:

function sortTableColumn(tableID, columnIndex){
    t = document.getElementById(`#${tableID}`);
    [...t.tBodies[0].rows]
    .sort( (a,b) => a.cells[columnIndex].textContent  t.tBodies[columnIndex].appendChild(r))
}

Concerns:

Performance: is the use of spread operator ok here? Or is Array.from preferred?
Visual sorting: Since you're re-appending each element one by one, in a large table the user would see the table arranging until it is done. I couldn't think of a way of "one shotting" the appending without affecting performance too much. Maybe adding a loading overlay is the best solution?
What if we're dealing with a table with 1000+ records? What could go wrong?

Fiddle: http://jsfiddle.net/ppgab/nu0q62br/22/

Table (any table with one body should work):

                First
                Last
                Handle

                Mark
                Otto
                @mdo

                Jacob
                Thornton
                @fat

                Larry
                the Bird
                @twitter


texts: How to avoid carrying around a lock with my variable when multiple threads instantiation in Python?

texts:
I created an application using multiple threads defined in multiple class files which read and write into a "shared variable" (a dictionary).

To ensure thread-safety, I am using a Lock, and I pass it as argument to my Thread class next to my variable.

What bothers me is that two objects which are intrinsically linked have to be passed to my class, while ideally only the shared variable should be. This would reduce the code and bring greater certainty while avoiding confusion in the parameters.

Here is how my program looks:

inc_thread.py

from threading import Thread

class IncThread(Thread):

    def __init__(self, shared_dict, lock):
        Thread.__init__(self, daemon=True)
        self._shared_dict = shared_dict
        self._lock = lock

    def run(self):
        while 1:
            with self._lock:
                self._shared_dict['some_value'] += 1

dec_thread.py

from threading import Thread

class DecThread(Thread):

    def __init__(self, shared_dict, lock):
        Thread.__init__(self, daemon=True)
        self._shared_dict = shared_dict
        self._lock = lock

    def run(self):
        while 1:
            with self._lock:
                self._shared_dict['some_value'] -= 1

main.py

import time

from threading import RLock
from dec_thread import DecThread
from inc_thread import IncThread

if __name__ == '__main__':
    lock = RLock()
    shared_dict = {'some_value': 0}

    t1 = DecThread(shared_dict, lock)
    t2 = IncThread(shared_dict, lock)

    t1.start()
    t2.start()

    # Ensure equity regarding wich thread started first
    with lock:
        shared_dict['some_value'] = 0

    while 1:
        print(shared_dict['some_value'])
        time.sleep(1)

Is it the correct way to do it?

What I also thought:

Subclass dict and override get / set methods with an internal lock, but it becomes complicated when I want to set other datastructures (nested dict, list, set, etc.) as values.
Using Queue but it does not seem to fit my needs, as it is by default blocking for put / get while my design is more of "fire and forget".