texts:
This is my code for running a background thread.  I believe it is very poor in naming and code structure.

package com.ocs.socialshare.bloggershare;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.google.gdata.util.AuthenticationException;

public class MainActivity extends Activity implements OnClickListener{

    private Thread doinBackground;

    private EditText username,password,blogurl;
    private Button login;
    private String user,pass,bloglink;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById();
        setOnclickListenerRegister();
    }

    private void findViewById() {
        // TODO Auto-generated method stub
        username        =   (EditText) findViewById(R.id.username);
        password        =   (EditText) findViewById(R.id.password);
        blogurl         =   (EditText) findViewById(R.id.blogurl);
        login           =   (Button) findViewById(R.id.login);
    }

    private void setOnclickListenerRegister() {
        // TODO Auto-generated method stub
        login.setOnClickListener(this);
    }
    private void blogShare(final String user,final String pass,final String bloglink) {
        // TODO Auto-generated method stub

            doinBackground =new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                // TODO Auto-generated method stub
                BloggerClient blog = new BloggerClient(getApplicationContext());
                try {
                    blog.oAuthBlogger(user,pass,bloglink);
                    }
                    catch (AuthenticationException e)
                    {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }
                }
            });
        doinBackground.start();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        int viewid  = view.getId();

        if(viewid == R.id.login)
        {
        validateFeild();
        blogShare(user,pass,bloglink);
        }
    }

    private void validateFeild() {
        // TODO Auto-generated method stub
        user        =    username.getText().toString();
        pass        =    password.getText().toString();
        bloglink    =    blogurl.getText().toString();

    }

}


texts:
Given a set of items with a weight and a value, this problem gives the subset of items which maximize value so that their combined weights is less or equal than a given maximum weight. This solution runs in \$O(w\cdot n)\$ where \$n\$ is the number of items and \$w\$ is the max weight.

#[derive(Debug, Clone)]
struct Item {
    value: usize,
    weight: usize,
}

impl Item {

    fn new(pvalue: usize, pweight: usize) -> Item {
        Item { value: pvalue, weight: pweight }
    }
}

#[derive(Debug, Clone)]
struct Info {
    ks_value: usize,
    added_weight: usize,
    included: bool,
}

impl Info {
    fn new(pks_value: usize, padded_weight: usize, pincluded: bool) -> Info{
        Info {
            ks_value: pks_value,
            added_weight: padded_weight,
            included: pincluded,
        }
    }
}

impl std::cmp::Ord for Info {
    fn cmp(&self, other: &Info) -> std::cmp::Ordering {
        self.ks_value.cmp(&other.ks_value)
    }
}

impl PartialOrd for Info {
    fn partial_cmp(&self, other: &Info) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Info {
    fn eq(&self, other: &Info) -> bool {
        self.ks_value == other.ks_value
    }
}

impl Eq for Info {}

fn _0_1_knapsack_items<'a>(items: &'a[Item], max_weight: usize, subproblems: &[Vec<Info>]) -> Vec<&'a Item>{
        (1..items.len() + 1).rev()
        .scan(max_weight, |w, i| {
                let sub    = &subproblems[i][*w];
                let result = (i, sub.included);
                *w -= sub.added_weight;
                Some(result)
        })
        .filter(|&(_, inc)| inc)
        .take_while(|&(i, _)| i > 0)
        .map(|(i, _)| &items[i - 1])
        .collect::<Vec<&Item>>()
}

fn _0_1_knapsack<'a>(items: &'a [Item], max_weight: usize) -> Vec<&'a Item>{
    let mut subproblems = vec! [ vec! [ Info::new(0, 0, false);
                                       max_weight + 1 ];
                                 items.len() + 1 ];
    for i in 0..items.len() {
        for w in 0..max_weight + 1 {
            let w_i      = items[i].weight;
            let exc_cost = subproblems[i][w].ks_value;
            subproblems[i + 1][w] = if  w < w_i {
                Info::new(exc_cost, 0, false)
            }
            else {
                let inc_cost = subproblems[i][w - w_i].ks_value
                               + items[i].value;
                std::cmp::max(Info::new(exc_cost, 0, false),
                              Info::new(inc_cost, w_i, true))
            }
        }
    }
    _0_1_knapsack_items(items, max_weight, &subproblems)
}

fn main() {
    let items = [ Item::new(92, 23),  //1
                  Item::new(57, 31),  //1
                  Item::new(49, 29),  //1
                  Item::new(68, 44),  //1
                  Item::new(60, 53),  //0
                  Item::new(43, 38),  //1
                  Item::new(67, 63),  //0
                  Item::new(84, 85),  //0
                  Item::new(87, 89),  //0
                  Item::new(72, 82) ];//0

    for i in _0_1_knapsack(&items, 165){
        println!("{:?}", i);
    }
}


texts: Computing even huger Fibonacci numbers in Java

texts:
See the next iteration.

I have that method for computing Fibonacci numbers \$F_n\$ (\$n = 0, 1, 2, \dots)\$, that relies on computing

$$
A =
\begin{pmatrix}
1 & 1 \\
1 & 0
\end{pmatrix}^n.
$$

The solution is then read from \$A_{1,2}\$. Now I can easily compute, for instance, \$F_{100000}\$.

However, in this code snippet, I need not just large integer additions, but multiplications as well, and looking at the source code of multiplication of two BigIntegers, it becomes evident that the algorithms are more smart and efficient than I could ever do.

What comes to the complexity of this approach, we need only \$\Theta(\log n)\$ matrix multiplications. Assuming that multiplying two (largest in the computation) BigIntegers takes time \$\mathcal{O}(f(n))\$, the complexity of the entire algorithm is \$\mathcal{O}(f(n) \log n)\$.

import java.math.BigInteger;

public class LargeFibonacciNumbers {

    public static String fibonacci(int n) {
        if (n < 0) {
            throw new IllegalArgumentException(
                    "The (" + n + ")th Fibonacci number is not defined.");
        }

        switch (n) {
            case 0:
                return "0";

            case 1:
                return "1";
        }

        BigInteger[][] matrix = new BigInteger[2][2];

        matrix[0][0] = BigInteger.ONE;
        matrix[0][1] = BigInteger.ONE;
        matrix[1][0] = BigInteger.ONE;
        matrix[1][1] = BigInteger.ZERO;

        return fibonacciMatrix(matrix, n)[0][1].toString();
    }

    private static BigInteger[][] multiply(BigInteger[][] matrix1,
                                           BigInteger[][] matrix2) {
        BigInteger[][] ret = new BigInteger[2][2];

        ret[0][0] = matrix1[0][0].multiply(matrix2[0][0])
               .add(matrix1[0][1].multiply(matrix2[1][0]));

        ret[0][1] = matrix1[0][0].multiply(matrix2[0][1])
               .add(matrix1[0][1].multiply(matrix2[1][1]));

        ret[1][0] = matrix1[1][0].multiply(matrix2[0][0])
               .add(matrix1[1][1].multiply(matrix2[1][0]));

        ret[1][1] = matrix1[1][0].multiply(matrix2[0][1])
               .add(matrix1[1][1].multiply(matrix2[1][1]));

        return ret;
    }

    private static BigInteger[][]
        fibonacciMatrix(BigInteger[][] matrix, int n) {
        if (n == 1) {
            // End the recursion.
            return matrix;
        }

        if ((n & 1) == 1) {
            // 'n' is odd.
            return multiply(matrix, fibonacciMatrix(matrix, n - 1));
        }

        // 'n' is even.
        BigInteger[][] tmp = fibonacciMatrix(matrix, n >> 1);
        return multiply(tmp, tmp);
    }

    public static void main(String[] args) {
        int n = -1;

        if (args.length > 0) {
            try {
                n = Integer.parseInt(args[0]);
            } catch (NumberFormatException ex) {

            }
        }

        System.out.println(fibonacci(n));
    }
}

So, what do you think?


texts:
I have file called Network.txt which contains SSID and BSSID as below:

  SSID                              BSSID               MODE             FREQ       RATE       SIGNAL   SECURITY   ACTIVE
'Bards Tale'                  30:DA:9B:70:EE:F4   Infrastructure   2412  MHz   54 MB/s    47       WPA2              no
'Alaskan Pale'                70:37:73:B7:3A:53   Infrastructure   2412 MHz   54 MB/s    44       WPA2             yes
'Abita Turbodog'              9C:1E:04:4C:59:FC   Infrastructure   2412 MHz   54 MB/s    7        WPA WPA2         no
'Alaskan Amber'               12:62:EB:2C:C0:06   Infrastructure   2422 MHz   54 MB/s    2        WPA WPA2         no

I want to get SSID and BSSID in safe and efficient way.  Here is my approach, which is working fine; can it be improved?

void GetSSIDAndBSSID(const std::string &temp)
    {
        if (temp.find("'") != std::string::npos)
        {

            std::string::size_type end_pos = temp.find_last_of(":");
            if (end_pos == std::string::npos)
                end_pos = temp.size();

     std::string FirstWord = temp.substr(1, end_pos+2);
    std::cout <<"SSID="<< FirstWord.substr(0,temp.find_last_of("'")-1) << std::endl;
   std::cout<<"BSSID=" << FirstWord.substr(temp.find_first_of(":")-2,temp.find_last_of(":")+2) << std::endl;
        }
    }

int main()
{
        ifstream fin("pathTO/Network.txt");
        std::string line;
        while(getline(fin,line))
        {

                GetSSIDAndBSSID(line);

        }


texts:
Here is the book question:

  Modify the CatFile function in the program so that it uses
  WriteConsole rather than WriteFile when the standard output handle
  is associated with a console.

And here is my solution:

static VOID CatFile(HANDLE hInFile, HANDLE hOutFile)
{
    DWORD nIn, nOut;
    TCHAR buffer[BUF_SIZE];
    LPTSTR pBuffer = &buffer[0];

    while (ReadFile(hInFile, buffer, BUF_SIZE, &nIn, NULL) &&
        (nIn != 0) &&
        (WriteFile(hOutFile, buffer, nIn, &nOut, NULL) || WriteConsole(hOutFile, pBuffer, _tcslen(pBuffer), &nOut, NULL)));
    return;
}

The part from the || sign in the code above is my addition to the code.

My question is to know if that would work once WriteFile wouldn't be TRUE since hOutFile is a handle of a console?

Another part of the question is just about the WriteConsole function: are these the correct arguments?


texts: Calculating the tip and tax portions for a refund amount

texts:
refundableSale is a PMSale object with properties refundableTip, refundableTax and refundableSubtotal. The requestRefundFor method takes a total refund amount as argument along with the refundable sale.

The requirement is you should first refund from the tips, then from the tax and then from the subtotal, if needed.

The flow works like this:

Refund the requested amount from tips
If there's more amount to refund, refund from tax next
If there's even more amount to refund, refund from subtotal

As you can see, my implementation of this has a lot of duplicate lines that I want to get rid of.

func requestRefundFor(amount refundAmount: NSDecimalNumber, sale refundableSale: PMSale) {
    var refundRequestedAmount = refundAmount

    var tipAmountToRefund = NSDecimalNumber.zero()
    var taxAmountToRefund = NSDecimalNumber.zero()
    var subtotalAmountToRefund = NSDecimalNumber.zero()

    if refundRequestedAmount.isGreaterThanOrEqualTo(refundableSale.refundableTip) {
        refundRequestedAmount = refundRequestedAmount.decimalNumberBySubtracting(refundableSale.refundableTip)
        tipAmountToRefund = refundableSale.refundableTip

        if refundRequestedAmount.isGreaterThanOrEqualTo(refundableSale.refundableTax) {
            refundRequestedAmount = refundRequestedAmount.decimalNumberBySubtracting(refundableSale.refundableTax)
            taxAmountToRefund = refundableSale.refundableTax

            if refundRequestedAmount.isGreaterThanOrEqualTo(refundableSale.refundableSubtotal) {
                refundRequestedAmount = refundRequestedAmount.decimalNumberBySubtracting(refundableSale.refundableSubtotal)
                subtotalAmountToRefund = refundableSale.refundableSubtotal

            } else {
                subtotalAmountToRefund = refundRequestedAmount
            }
        } else {
            taxAmountToRefund = refundRequestedAmount
        }
    } else {
        tipAmountToRefund = refundRequestedAmount
    }

    requestRefund(sale: refundableSale, subtotalRefundAmount: subtotalAmountToRefund, tip: tipAmountToRefund, tax: taxAmountToRefund)
}


texts:
I have two tables:

tableA

aid name age sex email password

tableB

bid idno aid

The steps should be

Enter, verify email and password
If email and password are correct, insert random number into tableB as idno
Select name, age, sex, email, idno from both tables and return an array as result.
If email and password are wrong, do nothing.

I wrote the following code in Codeigniter model

function login($data) {
    $email = $data["email"];
    $password = $data["password"];
    $sql = "select aid from tableA where email='".$email."' and password='".$password."'";
    $query = $this->db->query($sql);
    if ($query->num_rows() > 0) {
        $ret = $query->row();
        $idno = random();
        $aid = $ret->aid;
        $sql = "insert into tableB (idno, aid) values('".$idno."','".$aid."')";
        $query = $this->db->query($sql);
        if ($query) {
            $sql = "select '".$idno."' as idno, name, age, sex, email from tableA where aid='".$aid."'";
            $query = $this->db->query($sql);
            if ($query->num_rows() > 0) {
                return $query->result_array();
            }
            return $query->num_rows();
         } else {
            return false;
         }
         return false;
    }
    return $query->num_rows();
}

The code works, but I think the code is so ugly and not efficient. How can I optimize the code?


texts: Excel VBA Retrieving a Specific Pattern from String

texts:
The following VBA code is in response to a SuperUser question which I found interesting.

What I'm looking for in a response?

Code cleanliness. Can I do more to make the code easier to read and potentially debug in the future?
Code reduction. Is there anything else I can do, without changing the logic, to reduce the amount of code written?
The use of variants in code. I've noticed that the use of variants is frowned upon and with good reason. The memory needed for variants seems to be substantially larger than any other data type.
Use of modules. I've found that it's difficult for me to use modules as opposed to hosting the code within the Sheet or ThisWorkbook. Any comments on the use of modules?

Below is a screen shot of how my spreadsheet looks:

In the original question, the user is only asking to scrub 5 records. I duplicated them until I had 5K records. Completion time was 0.66 seconds. Speed doesn't seem like much of a concern in this case.

Below is the code. FYI, this is located in Sheet1:

Sub PatternScrub()

Dim targetRange As Range
Set targetRange = Range("A1", Range("A1").End(xlDown))

Dim Pattern As String
Dim x As Integer

' TO IMPROVE PERFORMANCE

With Application
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .DisplayStatusBar = False
    .EnableEvents = False
End With

' MAIN SCRUB
For Each cell In targetRange

    Pattern = Pattering(cell.Value)

    x = PatternIndex(Pattern)

    If x = 0 Then
        GoTo NextIteration
    Else
        cell.Offset(0, 1).Value = Mid(cell.Value, x, 13)
    End If

NextIteration:

Next cell

With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
    .DisplayStatusBar = True
    .EnableEvents = True
End With

End Sub

Private Function Pattering(ByVal target As String) As String

' TURNS THE STRING INTO 1s AND 0s

Dim i As Integer

For i = 1 To Len(target)

   If Mid(target, i, 1) = "." Then
        Mid(target, i, 1) = 0
    Else
        Mid(target, i, 1) = 1
   End If

Next

Pattering = target

End Function

Private Function PatternIndex(ByVal Pattern As String) As Integer

' MATCHES THE PATTERN AND RETURNS THE FIRST INDEX

    On Error GoTo ErrorHandler

    PatternIndex = Application.WorksheetFunction.Search("1101101110111", Pattern)

ErrorHandler:

    Select Case Err.Number
        Case 1004
            PatternIndex = 0
    End Select

End Function


texts:
I'm trying to learn C++ and I would interested in how I could write better code. The code should be independent of the architecture it is running on. What I want to do is writing some binary data to /dev/rfkill so that I can change some settings. The target is an embedded system so the program does run with root privileges and the program is using the Qt framework.

This is the code I currently have and which does what I want:

    rfkill_event event;
    event.type = RFKILL_TYPE_ALL;
    event.op = RFKILL_OP_CHANGE_ALL;
    event.soft = RFKILL_ACTION_UNBLOCK;

    QFile file("/dev/rfkill");
    if (!file.open(QIODevice::WriteOnly))
        quit();

    QDataStream out(&file);
    if (-1 == out.writeRawData((char*)(&(event.idx)), sizeof(event.idx))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.type)), sizeof(event.type))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.op)), sizeof(event.op))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.soft)), sizeof(event.soft))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.hard)), sizeof(event.hard))) {
        file.close();
        quit();
    }
    file.close();
    quit();

and the struct looks like this:

struct rfkill_event {
    __u32 idx;
    __u8  type;
    __u8  op;
    __u8  soft, hard;
};

The code is taken and adapted from the rfkill program.

I've removed __attribute__((packed)) from the struct because of the pitfalls mentioned here.

I'm using the writeRawData function instead of the << operator to write the data. The reason for this is that this code should work on big and little endian machines.

Are my assumptions correct and do you have any suggestions on how I could improve this code (besides not having any error handling)?


texts: Can this heap sort be further optimized to have fewer comparisons?

texts:
public static <T> void heapSort(
        T[] array,
        Comparator<? super T> comparator) {

    int length = array.length;
    int start = (length - 1) /2; //right-most parent node

    //build heap
    while (start > -1)
        maxHeapify(array, start--, length, comparator);

    //move max to end, and rebalance.
    while (length > 1) {
        swap(array, 0, length - 1);
        length--;
        maxHeapify(array, 0, length, comparator);
    }

}

private static <T> void maxHeapify(
        T[] array,
        int node,
        int length,
        Comparator<? super T> comparator) {

    int left = 2*node + 1;
    if (left >= length)
        return;
    int right = left + 1;

    int newNode = node;

    if (comparator.compare(array[left], array[node]) > 0)
        newNode = left;

    if (right < length && comparator.compare(array[right], array[newNode]) > 0)
        newNode = right;

    if (newNode != node) {
        swap(array, node, newNode);
        maxHeapify(array, newNode, length, comparator);
    }

}

I wrote a merge sort that seems to be using about half as many comparisons. Am I doing something wrong here?


texts: Move and rename images into separate folders

texts:
Basically, we came up with this task at work. I was wondering if there's a shorter and cleaner way of doing the following in some other language (or even improving what I did with Ruby).

We have a folder. In this folder we have files (images only, /w .jpg extension). The names of the images are random strings such as:

3e3eaa0b927d0158e1b2479ce31000b3.jpg
3e3eaa0b927d0158e1b2479ce31000b3_1.jpg
99a2b9c3442e716fc486e46abcfcfb05.jpg
99a2b9c3442e716fc486e46abcfcfb05_1.jpg
99a2b9c3442e716fc486e46abcfcfb05_2.jpg & etc.

To make it clearer, those images were related to certain objects. An object had multiple images (not a specific amount). We have to get those images, read their name, and get the "unique" part.

Example: For images:

3e3eaa0b927d0158e1b2479ce31000b3.jpg
3e3eaa0b927d0158e1b2479ce31000b3_1.jpg

the "unique" part is "3e3eaa0b927d0158e1b2479ce31000b3"

And we have to create a folder with this name (3e3eaa0b927d0158e1b2479ce31000b3) and put all the images that match (3e3eaa0b927d0158e1b2479ce31000b3_*). Also we have to rename those images, so in every folder there must be one image with thumb_ followed by a random string & the other images must be with img_ prefix and again followed by a random string.

This is my try:

require 'securerandom'
folder = "storage_test/"
Dir.glob("#{folder}*.jpg") do |img|
  fn = File.basename(img,".*").gsub(/(\_\d)+/, '') #folder name
  prefix = (!File.exists?( "#{folder}#{fn}") ? '/thumb_' : '/img_') #prefix
  new_name = "#{folder}#{fn}/#{prefix}" + SecureRandom.hex(32) + File.extname(img) #new_name (of the image)
  Dir.mkdir("#{folder}#{fn}")  unless File.exists?("#{folder}#{fn}") #create the folder
  File.rename(img, new_name) #move
end

(I work on Windows)

I'm sorry I've probably misused the term random. By random I mean that I need to create a name that's unique to the certain folder. Actually, there aren't going to be more than 40-50 files in a folder, so I presumed that SecureRandom.hex(32) will generate unique enough filename that will not cause overwriting in the same folder.

More detailed example:

Example folder: "storage_test"

And this is a part of its content:

I've grouped the files that should go in the same folder. I highlighted that part from the file's name that should be used as folders name.

So after executing the code "storage_test" will have:

091afecdc49a8e8e581f11f2f1bfea8f_1/thumb_unique(to the folder)name.jpg
091afecdc49a8e8e581f11f2f1bfea8f_1/img_unique(to the folder)name.jpg
091afecdc49a8e8e581f11f2f1bfea8f_1/img_unique(to the folder)name.jpg


texts:
Is this code secure and valid?  If so, can it be improved?

<?php
        // conect to the data base
        $mysqli =  new mysqli('localhost','user','pass','dbname');
         if($mysqli->connect_errno >0){
            die( "problem with the connection");
        }

        // creat a function to get table information
        function fetchTableFeildNames($mysqli , $databaseName , $tableName ){
            $sql = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`= '$databaseName' AND `TABLE_NAME`= '$tableName' ";
     if(!$stmt =$mysqli->prepare($sql)){
          die("There is an error with mysql preperation staetment".$mysqli->error);
        }
     if (!$stmt->execute()) {
          echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
         }
      $res = $stmt->get_result();
      //looping throught the result
       while ($array = $res->fetch_array()){
           $newArray[] =$array;
           }
        return $newArray;
        }

    //insert function
    function insert($mysqli,$tableName,$databaseName,$array){
        //fetching table columns information
        $tableColumns      = fetchTableFeildNames($mysqli , $databaseName , $tableName );
        // geeting table columns count
        $tableColumnsCount = count($tableColumns);
        //geting data array count
        $dataArrayCount    = count($array);
        //see if the table columns count dosenot mutch array data count we kill the script
        if  ($tableColumnsCount != $dataArrayCount){
            die("Data array dosenot mutch table columns count");
        }
        //forming the query depending on input array at same time we are geting data typs for the data array
        $sql = "INSERT INTO `{$databaseName}`.`{$tableName}` VALUES (";
        for($i=0;$i<$dataArrayCount;$i++){
            $string         =  gettype($array[$i]);
            //takeing the first litter example string= s ,integer =1
            $a_param_type[] =  $string[0];
            $sql .= "?,";
            }
            //remove the last char ","
            $sql  = rtrim($sql , ",");
            $sql .= ")";

            $a_params   = array();
            $param_type = '';
            $n          = count($a_param_type);
            //merging all types in one string
            for($i = 0; $i < $n; $i++) {
                $param_type .= $a_param_type[$i];
            }
            //passing the types to the array by refrence
           $a_params[]  = & $param_type;
           //passing the data array  by refrence
           for($i = 0; $i < $n; $i++) {
             $a_params[] = & $array[$i];
            }
             //preperaing the statment
           if(!$stmt = $mysqli->prepare($sql)){
                die("error in preperation " . $mysqli->error);
            }
           //using   call_user_func_array() because mysqli::bind dont work with dynamic parameters
           call_user_func_array(array($stmt, 'bind_param'), $a_params);

           //executing the query
           if(!$stmt->execute()){
                die("error in executeing the query".$mysqli->error);

           }
}

        $array = array ("","catName" ,"catDesecription","","","","");

        insert($mysqli,"items","yaztor",$array);
?>


texts: Efficient method to look for an instance of an object in a collection

texts:
I'm trying to determine if an instance of an object exists within a collection.

I'm using array_walk_recursive to walk and check the leaves of an array.

I've added a small short circuit, but still all leaves will be iterated over.

I could alternatively use something like an exception which is thrown on the first find, to break out early, but that feels kind of wrong.

Am I missing a simple alternative?

<?php

class Fish {}
class Mammal {}
class Whale extends Mammal {}
class Human extends Mammal {}
class Shark extends Fish {}

function anyFish(array $collection)
{
    $found = false;
    array_walk_recursive($collection, function ($v) use (&$found) {
        if(!$found && $v instanceof Fish)
            $found = true;
    });

    return $found;
}

$seas = [
    'pacific'  => [new Whale, new Shark],
    'atlantic' => [new Human, new Shark]
];

$pub = [new Human, new Human];

var_dump(anyFish($seas));
var_dump(anyFish($pub));

Output:

bool(true)
bool(false)

Found on Stackoverflow: https://stackoverflow.com/questions/17853113/break-array-walk-from-anonymous-function)


texts:
I am writing a unit test to be sure the code can connect to aws via boto, since I will be putting the credentials in place via some other process than code deployment.  So far, I've only figured out how to check if I have a valid connection by looking at an S3 bucket, but am hoping someone has a more direct way to check.

import unittest
import boto

class TestTest(unittest.TestCase):
    def setUp(self):
        self.s3 = boto.connect_s3()

    def tearDown(self):
        pass

    def test_connection(self):
        assert self.s3 is not None

        # must be a better way to ensure connection works
        bucket = boto.s3.bucket.Bucket(connection=self.s3, name='test_this_bucket')
        all_keys = bucket.get_all_keys()
        assert len(all_keys) == 0


texts: Find the highest number satisfying a condition in an infinite range

texts:
I wrote the below function for doing a variation of bisection search that I came up with. This can be useful when the higher bound is not known. It assumes that as number increases the result of the condition is also increasing.

For example - find the largest classroom size where the probability of two students sharing the same birthday is less than 0.99.

If I have a function that finds the probability of two students sharing the same birthday based on number of classrooms then I can pass that function and perform a bisection search over an infinite range to find the highest number.

def largest_satisfying_condition(condition):
    lo, hi = 1, 3
    mid = None
    lowest_hi_false = float('inf')
    while lo != hi:
        mid = (lo + hi) / 2
        if condition(mid):
            lo, hi = mid, hi * 2

            if hi > lowest_hi_false:
                #Because any value greater than this will give false result
                hi = lowest_hi_false - 1
        else:
            lo, hi = lo, mid
            if hi < lowest_hi_false:
                #No need to go over this when increasing hi
                lowest_hi_false = hi
    return mid

I wanted to know whether this can be written in a better way - according to either algorithm or Python.


texts:
I put together this implementation after playing around with various partitioning- and pivot-strategies, and it runs fine. I wrote this off a version which seemed a bit different from the majority of implementations, so I'm curious on what you guys think. It works and handles duplicates.

def quicksort(a, min=0, max=a.length-1)
  if min < max
    index = partition(a, min, max)
    quicksort(a, min, index-1)
    quicksort(a, index+1, max)
  end
end

def partition(a, l, r)

  m=(l+r)/2
  piv = a[m]
  a[m], a[r] = a[r], a[m]

  cur = l
  for i in l..r-1

    if a[i] <= piv
      a[i], a[cur] = a[cur], a[i]
      cur+=1
    end
  end
  a[cur], a[r] = a[r], a[cur]

  return cur

end


texts: Optionally creating a directory path based based on existence in NodeJS

texts:
I've been doing some reading and tutorials. As such I've contrived a node based project to apply what I've learned. I thought this was a good example as it had some conditional async calls and error handling.

Any and all criticism of not following current JS best practices welcome.

/**
 * mkLocalCfg function,
 * makes a local config directory structure and empty config file.
 * in the form "~/.config/nobjs/nobjs_config.json"
 *
 * @param {mkLocalCfgCallback} cb - The callback that handles the response.
 *
 */
function mkLocalCfg(cb) {
    //validate root folder exists, if not make it.
    if (!admin.hasHomeConfigDir()) {
        fs.mkdir(os.homedir() + "/.config", "775", function(err) {
            //stop here if you can't make it.
            if (err) {cb(err); return;}
        });
    }
    fs.mkdir(admin.getConfigLocation(false), "775", function(err) {
        //can't make config folder end it here
        if (err) {cb(err); return;}
        //write config file, return null or err on error
        fs.writeFile(admin.getConfigLocation(true), JSON.stringify({blogs: {}}), function(err) {
            if (err) {cb(err); return;}
            cb(null);
        });
    });
}


texts: Default value mechanism in Lua using metatables

texts:
I am writing a couple of functions accepting tables as input parameters. These tables constitute a range of options, which should either be given or inferred from default tables.

Concrete use cases can be found in the unit tests below.

The main question:
Is the code idiomatic Lua – especially the use of metatables?

Code

local defvalue = {}

--[[
    Provides a means to fill a table with default options if they are not
    already present.
    This function is based on meta tables and their __index() function.

    table: Your (input) table.
    defTable: A table containing all default values.
    recursive: A boolean indicating if sub-tables should also be bound to the
               values found in defTable.
--]]
function defvalue.bind_table(table, defTable, recursive)
  local mt = {
    __index = function (table, key)
      return defTable[key]
    end
  }
  setmetatable(table, mt)

  if recursive then
    for key, value in pairs(table) do
      if type(value) == "table" then
        defvalue.bind_table(table[key], defTable[key], true)
      end
    end
  end
end

return defvalue

Unit tests (using luaunit):

require('luaunit/luaunit')
local defvalue = require('defvalue')

TestDefaultValue = {} -- class
    function TestDefaultValue:testDefaultValue()
        local actualTable = {}
        local defTable = {
            property = "value"
        }
        defvalue.bind_table(actualTable, defTable, false)
        assertEquals(actualTable["property"], "value")
   end

    function TestDefaultValue:testRecursiveValues()
        local actualTable = {
            -- test merging of sub-tables
            secondSubTable = {
            }
        }
        local defTable = {
            subTable = {
                property = "value"
            };
            secondSubTable = {
                secondSubProperty = "secondSubValue"
            }
        }
        defvalue.bind_table(actualTable, defTable, true)
        assertEquals(actualTable["subTable"]["property"], "value")
        assertEquals(actualTable["secondSubTable"]["secondSubProperty"], "secondSubValue")
    end

    function TestDefaultValue:testNonRecursiveValues()
        local actualTable = {
            subTable = {}
        }
        local defTable = {
            subTable = {
                property = "Hello World!"
            }
        }

        defvalue.bind_table(actualTable, defTable, false)
        assertEquals(actualTable["subTable"]["property"], nil)
    end

    function TestDefaultValue:testDynamicChange()
        local actualTable = {}
        local defTable = {}

        defvalue.bind_table(actualTable, defTable, false)
        assertEquals(actualTable["property"], nil)

        defTable["property"] = 42
        assertEquals(actualTable["property"], 42)
    end

    function TestDefaultValue:testPropertyShadowing()
        local actualTable = {
            property = "value";
            subTable = {
                subProperty = "subValue"
            };
            secondSubTable = {
                secondSubProperty = "secondSubValue"
            }
        }
        local defTable = {
            property = "hello";
            subTable = {
                subProperty = "world"
            };
            secondSubTable = 42
        }

        defvalue.bind_table(actualTable, defTable, true)
        assertEquals(actualTable["property"], "value")
        assertEquals(actualTable["subTable"]["subProperty"], "subValue")
        assertEquals(actualTable["secondSubTable"]["secondSubProperty"], "secondSubValue")
    end

-- class TestDefaultValue

LuaUnit:run()


texts: Breadth-first search(BFS) Implementation in Python 3

texts:
I have implemented a BFS. Does this look like a proper implementation of BFS in Python 3? And if you think something needs to be improved, say it.

class Node(object):

    def __init__(self, name):
        self.name = name
        self.adjacencyList = []
        self.visited = False
        self.predecessor = None

class BreadthFirstSearch(object):

    def bfs(self, startNode):

        queue = []
        queue.append(startNode)
        startNode.visited = True

        # BFS -> queue
        while queue:

            actualNode = queue.pop(0)
            print(actualNode.name)

            for n in actualNode.adjacencyList:
                if not n.visited:
                    n.visited = True
                    queue.append(n)

node1 = Node("A")
node2 = Node("B")
node3 = Node("C")
node4 = Node("D")
node5 = Node("E")

node1.adjacencyList.append(node2)
node1.adjacencyList.append(node3)
node2.adjacencyList.append(node4)
node4.adjacencyList.append(node5)

bfs = BreadthFirstSearch()
bfs.bfs(node1)


texts:
I have to run a python script that enters data into MySQL database table.

My below query runs and inserts data into MySQL database. But I want to optimize it and I have 2 requests:

I want to use try except error handling inside the for loop. Probably before insertstmt or where it would be more efficient.
If there is bug while executing nSql, program should not terminate, rather continue in other nSql tests.
nSql has complex SQL queries with multiple joins, below shown is for simplicity. If any one of the nSql fails during quering, I want the error
message to be displayed.
If the data already exists for yesterday, I want to be deleted it as well.
As the loop iterates, I want data to be deleted if it exists for yesterday as loop iterates through the nSql.

I have:

#! /usr/bin/env python
import mysql.connector
con=mysql.connector.connect(user='root', password ='root', database='test')
cur=con.cursor()

sel=("select id, custName, nSql from TBLA")
cur.execute(sel)
res1=cur.fetchall()

for outrow in res1:
    print 'Customer ID : ', outrow[0], ': ', outrow[1]
    nSql = outrow[2]
    cur.execute(nSql)
    res2=cur.fetchall()

    for inrow in res2:
        dateK =inrow[0]
        id= inrow[1]
        name= inrow[2]
        city=inrow[3]
        insertstmt=("insert into TBLB (dateK, id, name, city) values ('%s', '%s', '%s', '%s')" % (dateK, id, name, city))
        cur.execute(insertstmt)

con.commit()
con.close()

Database schema is:

create table TBLA (id int, custName varchar(20), nSql text);

insert into TBLA values ( 101, 'cust1', "select date_sub(curdate(), interval 1 day) as dateK, id, 'name', 'city' from t1"), ( 102, 'cust2', "select date_sub(curdate(), interval 1 day) as dateK, id, 'name', 'city' from t2"), ( 103, 'cust3', "select date_sub(curdate(), interval 1 day) as dateK, id, 'name', 'city' from t3");

create table t1 (id int, name varchar(20), city varchar(20));
create table t2 (id int, name varchar(20), city varchar(20));
create table t3 (id int, name varchar(20), city varchar(20));

insert into t1 values( 101, 'bob', 'dallas'), ( 102, 'boby', 'dallas');

insert into t2 values( 101, 'bob', 'dallas'), ( 102, 'boby', 'dallas');

insert into t3 values( 101, 'bob', 'dallas'), ( 102, 'boby', 'dallas');

create table TBLB (dateK date, id int, name varchar(20), city varchar (20));


texts:
I wrote JS to clone image and attached this action to button.
It works but I'm not sure that this better way to do it.

My questions:

is it correct to use querySelector to return elements, or is it better to add additional classes or id for buttons and pictures?
use cloneNode is optimal or better use other ways in this case?

(function() {
  'use strict';
  document.querySelector('button[action="button"]').addEventListener('click', function() {
    let image = document.querySelector('img[alt="Dog"]');
    let cln = image.cloneNode(true);
    document.getElementById('image-section').appendChild(cln);
  });
})();

       <button action="button">Yeah, I want more dogs!</button>


texts:
While learning JavaScript I thought it was a good idea to make a digital clock program. I followed a youtube tutorial (with some tweaks to my preference) and came up with my final code that I have. I came to CodeReview to get the script reviewed, and to ask is there anything wrong with the script and/or any way to improve it as a whole. Ways to make the script shorter (yet also high in performance) are also accepted. I am also curious on if I have any 'red flags' currently. I will be giving the best answers the green checkmark. Thanks!

function showTime() {
  const date = new Date();
  let hours = date.getHours();
  let minutes = date.getMinutes();
  let seconds = date.getSeconds();
  let session = (hours < 12) ? "AM" : "PM";

  if (hours === 0) {
    hours = 12;
  } else if (hours > 12) {
    hours -= 12;
  }
  hours = (hours < 10) ? '0' + hours : hours;
  minutes = (minutes < 10) ? '0' + minutes : minutes;
  seconds = (seconds < 10) ? '0' + seconds : seconds;

  const time = `${hours} : ${minutes} : ${seconds} ${session}`;
  document.querySelector('div').innerHTML = time;

  setTimeout(showTime,1000)
}

showTime()
<!DOCTYPE html>

      <title>Digital Clock</title>

TL;DR: I am a JavaScript programmer, and CSS currently isn't my suite, therefore I know that the clock can use some styling. How can the JavaScript code be improved?


texts:
I have a function that is suppose to store variables based on their datatype, and this is table I have come up with to store those variables into.

Is it smarter to have everything broken down like this or would be wiser to only have columns for the largest for the largest datatype of a group (such as string datatypes only having a MEDIUMTEXT)? I am expecting this table to become quite large and I would like to keep the tables storage space demands as small as possible.

CREATE TABLE IF NOT EXISTS form_part_detail(
form_part_detail_id  INT NOT NULL    AUTO_INCREMENT  PRIMARY KEY,
form_part_detail_type_id   INT NOT NULL,
label   VARCHAR(255) NOT NULL,
`string`    VARCHAR(255)  NULL,
`text`   TEXT   NULL,
`mediumtext`    MEDIUMTEXT NULL,
`integer`   INT NULL,
`boolean`   TINYINT(1)  NULL,
`float` FLOAT NULL,
`double`    DOUBLE NULL,
FOREIGN KEY (form_part) REFERENCES `form_part` (form_part_id)
FOREIGN KEY (form_part_detail_type_id) REFERENCES `form_part_detail_type` (form_part_detail_type_id)
);


texts:
Per the title date only class (or struct?).

.NET does not offer a date only data type.

I get there is time zone dynamic but then you have daylight-savings that can still kill you. I do document management and we just have a document with a date.

// minimal limited test
DateOnly date1 = new DateOnly(1901, 2, 1);
DateOnly date2 = new DateOnly(1902, 3, 2);
DateOnly date3 = new DateOnly(1902, 3, 2);
Debug.WriteLine(date1.GetDayDiff(date2));  // 365 + 29 = 394
Debug.WriteLine(date2.GetDayDiff(date1));
Debug.WriteLine(date2.CompareTo(date1));
Debug.WriteLine(date1.CompareTo(date2));
Debug.WriteLine(date2.CompareTo(date3));
// end test

public class DateOnly: Object, IComparable
{
    private Dictionary<int, int> MonthDay = new Dictionary<int, int>() { { 1, 31 }, { 2, 29 }, { 3, 31 }, { 4, 30 },  { 5, 31 },  { 6, 30 }
                                                                       , { 7, 31 }, { 8, 31 }, { 9, 30 }, { 10, 31 }, { 11, 30 }, { 12, 31 } };
    public override int GetHashCode() { return (Int32)Days; }
    public override bool Equals(Object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        DateOnly other = (DateOnly)obj;
        return (this.Days == other.Days);
    }
    public int CompareTo(object obj)
    {
        if (obj == null)
        {
            throw new ArgumentNullException();
        }
        if (obj is DateOnly)
        {
            DateOnly other = (DateOnly)obj;
            if (other == null)
            {
                throw new ArgumentNullException();
            }
            return (this.Days).CompareTo(other.Days);
        }
        else
        {
            throw new ArgumentNullException();
        }
    }
    public override string ToString()
    {
        return string.Format("{0}/{1}/{2}", Year, Month, Day);
    }
    public Int64 GetDayDiff(DateOnly Date)
    {
        Int64 getDayDiff = (Int64)this.Days - (Int64)Date.Days;
        return (getDayDiff);
    }
    public UInt32 Days    { get; private set; }
    public int Year       { get; private set; }
    public int Month      { get; private set; }
    public int Day        { get; private set; }
    public UInt32 MaxDays { get; private set; }
    public DateOnly(int year, int month, int day)
    {
        if (!ValidateDate(year, month, day))
            throw new ArgumentOutOfRangeException("invalid date");
        MaxDays = GetDays(2078, 12, 31) - 1;
        Year = year;
        Month = month;
        Day = day;
        Days = GetDays(year, month, day);
    }
    private bool ValidateDate(int year, int month, int day)
    {
        bool valid = true;
        if (year < 1900 || year >= 2079)
            valid = false;
        else if (month < 1 || month > 12)
            valid = false;
        else if (day < 1 || day > 31)
            valid = false;
        else if (day > DaysPerMonth(year, month))
            valid = false;
        return valid;
    }
    private UInt32 GetDays(int year, int month, int day)
    {
        UInt32 days = 0;
        int yearSince1900 = year - 1900;
        UInt32 temp;
        for (int i = 1; i <= yearSince1900; i++)
        {
            temp = DaysPerYear(i + 1900 - 1);
            days += temp;
        }
        for (int i = 2; i <= month; i++)
        {
            temp = DaysPerMonth(year, i - 1);
            days += temp;
        }
        days += (UInt32)day;
        return days;
    }
    private bool IsLeap(int year)
    {
        return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
    }
    private UInt32 DaysPerYear(int year)
    {
        if (IsLeap(year))
            return 366;
        else
            return 365;
    }
    private UInt32 DaysPerMonth(int year, int month)
    {
        UInt32 days = (UInt32)MonthDay[month];
        if (month == 2 && !IsLeap(year))
            days = 28;
        return days;
    }
}


texts:
What do you think about this implementation of quicksort? Is it possible to make it shorter?

/**
 * 3-way quicksort
 * <p/>
 * Choose a value an put the greater values to the right, lowers to the
 * left, and equals in the center. recursive. O(n^2) but avg O(n log n). Memory: In place
 */
public static void quickSort(int[] array) {
    shuffleArray(array);
    quickSort(array, 0, array.length - 1);
}

private static void quickSort(int[] array, int lo, int hi) {
    if (hi <= lo)
        return;

    int lowerIndex = lo;
    int greaterIndex = hi;
    int element = array[lo];
    int i = lo;

    while (i <= greaterIndex) {
        if (array[i] < element)
            swap(array, lowerIndex++, i++);
        else if (array[i] > element)
            swap(array, i, greaterIndex--);
        else
            i++;
    }

    quickSort(array, lo, lowerIndex - 1);
    quickSort(array, greaterIndex + 1, hi);
}

// O(n)
private static void shuffleArray(int[] ar) {
    Random rnd = new Random();
    for (int i = ar.length - 1; i > 0; i--) {
        int index = rnd.nextInt(i + 1); // random between 0 and i
        swap(ar, i, index);
    }
}

private static void swap(int[] array, int i, int j) {
    int a = array[i];
    array[i] = array[j];
    array[j] = a;
}


texts: Optimized solution for a rolling dice code puzzle

texts:
I was asked to provide the solution of this rolling dice problem in an interview. When I showed him my solution, he said that there is another way to find the solution. I am looking for answer in PHP script only.

Question:
Two persons are playing a game of rolling 2 dices. Each person rolls the two dices n times and records the outcomes (sum of value of two dices) of all the n attempts. So after n attempts of both the player we have two list corresponding to the n outcomes of two players.
They want to know that whether they have got all possible outcomes( 1 to 12) same number of times or not. If they got all the possible outcomes same number of times then they are called lucky otherwise unlucky.
Input: Two Integer Arrays (L1, L2) corresponding to outcomes of two players.
Output: Lucky or Unlucky depending on the case

My Answer:
<?php
function rollingdice($input1,$input2)
{
  foreach($input1 as $k=>$a)
  {
    if(in_array($a,$input2))
    {$p = array_search($a, $input2);
     unset($input2[$p]);
    }
    else
    { return 'Unlucky';}
  }
return 'Lucky';
}
?>


texts: Generating filesystem paths from a fixed string

texts:
It's clever, but makes me vomit a little:

file = '0123456789abcdef123'

path = os.sep.join([ file[ x:(x+2) ] for x in range(0,5,2) ])


texts:
When developing a user interface that allows sorting by various different fields, I noticed that Array.prototype.sort() is extremely slow for large inputs. After some investigation, I found out that the problem was that my compare function was being called upwards of 8.5 million times for an input array of length 7500. If you ask me, that looks like \$O(n^2)\$ behavior. To address this, I decided to implement a merge sort.

Although I have tested my code and it appears to be working properly, it would still be helpful to have some other people look at it and see if there is more room for improvement or if it misbehaves in some subtle or pathological cases.

var mergesort = function (array, /* optional */ cmp) {
    /*
        Merge sort.
        On average, two orders of magnitude faster than Array.prototype.sort() for
        large arrays, with potentially many equal elements.
        Note that the default comparison function does not coerce its arguments to strings.
    */

    if (cmp === undefined) {
        // Note: This is not the same as the default behavior for Array.prototype.sort(),
        // which coerces elements to strings before comparing them.
        cmp = function (a, b) {
            'use asm';
            return a < b ? -1 : a === b ? 0 : 1;
        };
    }

    function merge (begin, begin_right, end) {
        'use asm';
        // Create a copy of the left and right halves.
        var left_size = begin_right - begin, right_size = end - begin_right;
        var left = array.slice(begin, begin_right), right = array.slice(begin_right, end);
        // Merge left and right halves back into original array.
        var i = begin, j = 0, k = 0;
        while (j < left_size && k < right_size)
            if (cmp(left[j], right[k]) <= 0)
                array[i++] = left[j++];
            else
                array[i++] = right[k++];
        // At this point, at least one of the two halves is finished.
        // Copy any remaining elements from left array back to original array.
        while (j < left_size) array[i++] = left[j++];
        // Copy any remaining elements from right array back to original array.
        while (k < right_size) array[i++] = right[k++];
        return;
    }

    function msort (begin, end) {
        'use asm';
        var size = end - begin;
        if (size <= 8) {
            // By experimentation, the sort is fastest when using native sort for
            // arrays with a maximum size somewhere between 4 and 16.
            // This decreases the depth of the recursion for an array size where
            // O(n^2) sorting algorithms are acceptable.
            var sub_array = array.slice(begin, end);
            sub_array.sort(cmp);
            // Copy the sorted array back to the original array.
            for (var i = 0; i < size; ++i)
                array[begin + i] = sub_array[i];
            return;
        }

        var begin_right = begin + (size >> 1);

        msort(begin, begin_right);
        msort(begin_right, end);
        merge(begin, begin_right, end);
    }

    msort(0, array.length);

    return array;
};


texts: Angular2 Toggling showing and hiding between two elements

texts:
I have a tabs nav element that has two tabs, it needs to show a component based on what tab was clicked and hide the other component.  If the clicked tab is already "active", the component needs to remain showing.

I have this working, but it seems very inefficient to me.  Can anyone show me a better way to do this?

Here's how I have it set up now.  For the sake of not posting every file in the question, know that the project is set up correctly.

@Component({
  selector: 'my-app',
  template: `

      <button type="button" (click)="changeShowStatus(oneShowing=true,twoShowing=false)">1</button>
      <button type="button" (click)="changeShowStatus(twoShowing=true,oneShowing=false)">2</button>

some content

some content2

  `,
})
export class App {
  name:string;
  oneShowing:boolean;
  twoShowing:boolean

  constructor() {
    this.oneShowing = true;
    this.twoShowing = false
  }
}

Plunker


texts:
I would like to know if this is a good approach to finding out all the expressions within brackets. (I was actually asked to find out the smallest bracket expression, I have omitted the function to check for the smallest string and spaces within the expression).

s = "((a+b*d)*(x/2))*(1+(y+(x-2)/10))"
b = []
j = 0
b.append(j)
stack = []

for i in range(0, len(s)):
    if s[i] == '(':
        j = j + 1
        b.append(j)
        b[j] = ''
    elif s[i] == ')':
        b[j] = b[j] + ')'
        stack.append(b[j])
        j = j - 1

    # 0 is omitted to exclude characters outside of brackets
    for k in range(1, j + 1):
        b[k] = b[k] + s[i]

print(s)
print(stack)


texts:
Recently on SO there was this question

i am trying to get sequence index of each array of array like I have
an element of the array and that 5 arrays have multiple elements and I
want to get the first index of each array then the second and so.
below is my array data const arrData = [[1,2,4,6],[3,8,7],[12,13],[],[9,10]];
and my expected outout [1,3,12,9,2,8,13,10,4,7,6]

This is very basic but I found it interesting and tried to solve it.
I solved it like this, I thought it is easy to understand and to read but in reasons that I go in every nested array through all elements maybe it is not the best solution.
For example if I have one array with length 100 and all the other ones are just have length 1.
What do you think about my code?

const arr = [
  [1, 2, 4, 6],
  [3, 8, 7],
  [12, 13],
  [],
  [9, 10]
];

let biggestLength = Number.MIN_VALUE;
for (let i = 0; i < arr.length; i++) {
  if (arr[i].length > biggestLength) {
    biggestLength = arr[i].length;
  }
}

let result = [];
for (let l = 0; l < biggestLength; l++) {
  for (let k = 0; k < arr.length; k++) {
    if (arr[k][l] !== undefined) {
      result.push(arr[k][l])
    }
  }
}

console.log(result)


texts: JavaScript program to find if array is in Arithmetic or Geometric sequence

texts:
Given an array of numbers I've to write a function to return the string "Arithmetic" if the sequence follows an arithmetic pattern or return "Geometric" if it follows a geometric pattern. If the sequence doesn't follow either pattern return "neither arithmetic and geometric".

I'm a beginner and I thought of following solution first. How do I improve on it and write better code next time?

var arr =[2,4,6,8,10];// [2,6,18,54]- Geometric
var arthCount=0;
var geoCount=0;
    function ArthGeo(){
        for (var i=0;i<arr.length-2;i++){
             if(arr[i+1]-arr[i]===arr[i+2]-arr[i+1]){
                 arthCount++;
            }
            else if(arr[i+1]/arr[i] ===arr[i+2]/arr[i+1]){
                 geoCount++;
            }
            else return "neither arithmetic nor geometric";
        }
         if(arthCount===arr.length-2)
             return "Arthematic series";
         else if(geocount===arr.length-2)
             return "Geometric series";
     }
 console.log(ArthGeo());


texts:
Here's a class I'm designing:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace Artworking.classes
{

    // A group permission level
    public class PermissionGroup
    {
        public int ID;                  // Unique ID for this group
        public bool hasFullControl;     // Does this group have complete control
        public user creator;            // Who created this group
        public string groupName;        // Reference name for group

        // Constructor for when a permission group ID is passed
        public PermissionGroup(SqlConnection cn, int ID)
        {
            using (SqlCommand cmd = new SqlCommand("SELECT creatorUserID, group_name, fullControl FROM tblATPermissionGroups WHERE ID = " + ID, cn))
            {
                SqlDataReader rdr = cmd.ExecuteReader();
                if (rdr.Read())
                {
                    this.creator.ID = int.Parse(rdr["creatorUserID"].ToString());
                    this.groupName = rdr["group_name"].ToString();
                    this.hasFullControl = bool.Parse(rdr["fullControl"].ToString());
                }
                rdr.Close();
            }
        }
    }

}

Am I on the right track?  Please note I'm not using the built in authentication as it needs to be backwards compatible for an old system. What I'm just checking is that I'm handling these classes properly and loading the data in correctly etc.  As I understand it I'm meant to put my SQL commands in the classes and away from the actual pages right?


texts: PHP review of object oriented GeoIP class

texts:
I wrote a little PHP wrapper class for GeoIP which looks like:

<?php
class GeoIP {
    private $ip;
    private $geo_ip_details;

    function __construct($ip) {
        $this->ip = $ip;
        $this->fetch();
    }

    private function fetch() {
        if(filter_var($this->ip, FILTER_VALIDATE_IP)) {
            $curl = new Curl();
            $json = $curl->get_request("http://freegeoip.net/json/" . $this->ip, true);
            $result = json_decode($json);

            if($result !== null) {
                $this->geo_ip_details = $result;
            }
        }
    }

    public function __get($property) {
        if(property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __toString() {
        if(isset($this->geo_ip_details) && !empty($this->geo_ip_details)) {
            if(isset($this->geo_ip_details->city) && !empty($this->geo_ip_details->city) && isset($this->geo_ip_details->region_name) && !empty($this->geo_ip_details->region_name) && isset($this->geo_ip_details->country_name) && !empty($this->geo_ip_details->country_name)) {
                return $this->geo_ip_details->city . ", " . $this->geo_ip_details->region_name . " " . $this->geo_ip_details->country_name;
            } else if(isset($this->geo_ip_details->region_name) && !empty($this->geo_ip_details->region_name) && isset($this->geo_ip_details->country_name) && !empty($this->geo_ip_details->country_name)) {
                return $this->geo_ip_details->region_name . " " . $this->geo_ip_details->country_name;
            } else if(isset($this->geo_ip_details->country_name) && !empty($this->geo_ip_details->country_name)) {
                return $this->geo_ip_details->country_name;
            }
        }
    }
}
?>

Usage is like:

//Constructor, and autocalls fetch()
$geoip = new GeoIP('64.87.28.98');

//Getter of ip property
print_r($geoip->ip);

//Getter of geo_ip_details property
print_r($geoip->geo_ip_details);

//toString of the class
echo $geoip;

Basically, I am going back and forth on implementation details. Should I expose fetch() publicly, and not automatically call it in the constructor? I.E.

$geoip = new GeoIP('64.87.28.98');
$result = $geoip->fetch();

Is using a getter a good idea? Should I have a class method called stringify() instead of overriding the __toString?

Also, right now, once you instantiate GeoIP with an ip address, there is no way to pass a new ip address into the existing object. You must instantiate a new GeoIP object. Does making a method:

public function set($ip) {
    $this->ip = $ip;
    $this->fetch();
}

Make sense, or simply just do something like: $geoip = new GeoIP('new-ip-address');

What is the best practice for object oriented design for this pattern?


texts:
I've made a Discord Bot in Python that uses the Psycopg module to make calls to a PostgreSQL database in order to display information.
https://github.com/Chombler/cardbot
Specifically, I call this function when a user calls the bot:
def pullCardRecord(recordName):
    success = True
    try:
        print("Trying")
        connection = psycopg2.connect(user = db_credentials[0],
                                        password = db_credentials[1],
                                        host = db_credentials[2],
                                        port = db_credentials[3],
                                        database = db_credentials[4])
        print("connected")
        cursor = connection.cursor()

        join_table_query = '''
        SELECT id
        FROM card
        WHERE card.name = ('%s') ''' % (recordName)

        cursor.execute(join_table_query)
        results = cursor.fetchall()
        print(results)
        if len(results) < 1:
            success = False
            raise ValueError('The name that was given to cardbot didn\'t exist in the card table.')

        join_table_query = '''
        SELECT  name,
                cardclass.cardclass,
                tribe.tribe, cardtype.cardtype,
                cost, side.side, strength, trait.strengthmodifier, health, trait.healthmodifier,
                trait.trait,
                ability,
                flavor,
                cardset.cardset,
                rarity.rarity
        FROM card
        LEFT JOIN cardtoclass ON card.id = cardtoclass.cardid
        LEFT JOIN cardclass ON cardtoclass.classid = cardclass.id
        LEFT JOIN cardtotrait ON cardtotrait.cardid = card.id
        LEFT JOIN trait ON cardtotrait.traitid = trait.id
        LEFT JOIN cardtotribe ON card.id = cardtotribe.cardid
        LEFT JOIN tribe ON cardtotribe.tribeid = tribe.id
        LEFT JOIN cardtype ON cardtype.id = card.typeid
        LEFT JOIN cardset ON cardset.id = card.setid
        LEFT JOIN rarity ON card.rarityid = rarity.id
        LEFT JOIN side ON card.sideid = side.id
        WHERE card.name = ('%s') ''' % (recordName)

        cursor.execute(join_table_query)
        results = cursor.fetchall()

        print("Printing Results")
        for row in results:
            for col in row:
                print(col)
            print()

        cardInstance = cardObject(results)
        print(cardInstance.information())

        # Print PostgreSQL version
        cursor.execute("SELECT version();")
        record = cursor.fetchone()
        print("You are connected to - ", record,"\n")

    except (Exception, psycopg2.Error) as error :
        print ("Error retrieving card information using PostgreSQL,", error)
    finally:
        #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")
        return(cardInstance.information() if success else "I'm sorry, I couldn't find a card with that name.")

I want to make sure that the bot is protected from any direct sql injections before I deploy it. Is it currently fairly safe or do I need to add anything to protect its integrity?


texts:
I'm coding for a project euler question and every now and then, the question will demand a program that is efficient even when doing brute force. Which I struggle with.

Below is a piece of code for problem 35 which I'm fairly certain works correctly so far with numbers under 10000 however when I set it to 1 million it takes way too long to run. I still havent got an answer yet and it's been running for about 15 mins....

If anyone could give me general tips on efficiency that would be awesome!

def rwh_primes(n):
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*int((n-i*i-1)/(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

def is_prime(n):
    for i in range(3, n):
        if n % i == 0:
            return False
    return True

def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

primes = rwh_primes(1000000)
lisp = []
working = []
count = 0
counter = 0

for x in primes:
    z = 1
    y = (len(str(x)) + 1)

    if len(str(x)) == 2:
        thingy = list(str(x))
        number = int(thingy[1] + thingy[0])
        if is_prime(number) == True:
            lisp.append(x)

    elif len(str(x)) < 2:
        lisp.append(x)

    else:
        while count < len(sorted(str(x))) - 1:
            num = list((str(x) + str(x)))
            new = num[z:y]
            newest = ''.join(new)
            verynew = int(newest)
            working.append(verynew)
            count += 1
            z += 1
            y += 1

            if count == len(sorted(str(x))) - 1:
                for a in working:
                    if is_prime(a) == True:
                        counter += 1
                        if counter == len(working):
                            lisp.append(x)
                            lisp = f7(lisp)
        count = 0
        counter = 0
        working = []

print(len(lisp))


texts:
I haven't done much programming in C++, so I figured I'd try making an Optional class. I'm mainly concerned that I didn't follow good conventions or that I didn't use exceptions well. I know that there are no comments, but for now, let's ignore that.

The idea is that my Optional class can be used instead of pointers and nullptr when I need to return an optional value.

optional.h

#pragma once

namespace extra { // I'm putting random library classes/functions in this namespace
    template <typename T>
    class Optional
    {
    public:
        const static Optional<T> empty;
        static Optional<T> of(const T &v);
        static Optional<T> of(T *v);
        T get() const;
        bool hasValue() const;
        ~Optional() { if (value != nullptr) delete value; }
    private:
        Optional(T *v) : value{ v } {}
        const T *value;
    };

    template<typename T>
    const Optional<T> Optional<T>::empty = Optional::of(nullptr);

#include "optional.impl"
}

optional.impl

#include <stdexcept>

template<typename T>
Optional<T> Optional<T>::of(const T &t) {
    return Optional<T>{ new T(t) };
}

template<typename T>
Optional<T> Optional<T>::of(T *t) {
    if (t != nullptr) return Optional<T>{ new T(*t) };
    return Optional<T>{ nullptr };
}

template<typename T>
bool Optional<T>::hasValue() const {
    return value != nullptr;
}

template<typename T>
T Optional<T>::get() const {
    if (!hasValue()) throw std::runtime_error("Tried to get the value from an optional that has no value");
    return *value;
}

template<typename T>
bool operator==(const Optional<T>& t1, const Optional<T>& t2) {
    if (!t1.hasValue() && !t2.hasValue()) return true;
    else if (!t1.hasValue() || !t2.hasValue()) return false;
    return t1.get() == t2.get();
}

template<typename T>
bool operator!=(const Optional<T>& t1, const Optional<T>& t2) {
    return !(t1 == t2);
}


texts: Can I draw a square with pixels more efficiently?

texts:
I'm drawing a square on a window using an implementation of Xlib. I put a colored pixel with my_pixel_put at a specific (x,y) coordinate.
Code to review
#define LWST_VAL 200
#define HGHST_VAL 400

int     main()
{
    t_data  img; //image data
    int x = LWST_VAL, y = LWST_VAL;

    // steps creating a window, creating an image
    while (x >= LWST_VAL && x <= HGHST_VAL)
    {
        while ((y > LWST_VAL && y < HGHST_VAL && (x == LWST_VAL || x ==
            HGHST_VAL)) || y == LWST_VAL || y == HGHST_VAL)
        {
            my_pixel_put(&img, x, y, 456);
            y++;
        }
        if (x > LWST_VAL && x < HGHST_VAL && y == (LWST_VAL + 1))
            y = HGHST_VAL;
        else
        {
            y = LWST_VAL;
            x++;
        }
    }
    // steps pushing image to the window, keep the window open
}

Output

Question
Could anything improve the performance of my code ? Or its readability ?
Any feedback appreciated.
Edit
This is the prototype of my_pixel_put :
void    my_pixel_put(t_data *img, int x, int y, int colour)

img is a structure containing data about the image such endiannes, bits per pixel, ...
x and y are the width and height of the window.
colour is the RGB colour of the pixel. (0,0) is actually the top left corner of the window (I know don't ask me why).


texts: Python script to extract text from PDF with images

texts:
I have the following Python script. The purpose of the script is to extract text from PDFs. I use textract for that because soon I realized there is no easy way to check if a page contains an image or not. So I extract the whole text using textract.

The workflow is like this. main() parses each pdf file from a folder, I extract the text, I search for keyword strikes and then I export the result to a csv file inside folder output_results.

What I can fix on my logic? What can I change in my code? I find it messy, how I can clean it up?

import textract
import os
import csv

class PdfMiner():

    path = os.getcwd() + '/folderForPdf/'
    output_path = os.getcwd() + '/output_results/'

    def __init__(self):
        pass

    def main(self):
        for self.filename in os.listdir(self.path):
            self.text = (PdfMiner().extract_text_from_pdf(self.path + self.filename))
            self.keyword_strike_dict = PdfMiner().keyword_strike(self.text)
            if bool(self.keyword_strike_dict):
                PdfMiner().output_to_csv(self.filename, self.keyword_strike_dict)

    def keyword_strike(self, text, keyword_strike_dict={}):
        '''keyword_strike function counts how many times a specific keyword occurs'''
        self.keyword_strike_dict = {}
        self.text = text
        self.keywords_list = PdfMiner().extract_keywords()
        for keyword in self.keywords_list:
            if keyword in text.decode('utf-8'):
                self.keyword_strike_dict[keyword] = text.decode('utf-8').count(keyword)
        return self.keyword_strike_dict

    def extract_keywords(self, keywords_list=None):
        '''function extract_keywords extract the keywords from file keywords.txt, into a list'''
        keywords_list = []
        with open('keywords.txt', 'r', encoding='utf8') as keywords_file:
            for keyword in keywords_file:
                keywords_list.append(keyword.strip('\n'))
        return keywords_list

    def extract_text_from_pdf(self, file_destination, text=None):
        '''extract_text_from_pdf'''
        self.file_destination = file_destination
        text = textract.process(self.file_destination, method='tesseract', language='eng', encoding='utf-8')
        return text

    def output_to_csv(self, *args, **kwargs):
        '''output_csv exports results to csv'''
        self.filename = args[0]
        self.keyword_strike_dict = args[1]
        self.output_file_path = PdfMiner().output_path + self.filename.strip('.pdf')
        with open(self.output_file_path + '.csv', 'w+', newline='') as csvfile:
            row_writer = csv.writer(csvfile, delimiter=',')
            row_writer.writerow(['keyword', 'keyword_count'])
            for keyword, keyword_count in self.keyword_strike_dict.items():
                print(keyword, keyword_count)
                row_writer.writerow([keyword, keyword_count])

if __name__ == "__main__":
    PdfMiner().main()


texts:
I had a test on sorting using quick sort algorithm, which I have implemented. It's working fine.

But my examiner is not satisfied. They say that the solution which I provided is not a proper quicksort, my code partially deviates from the actual quicksort algorithm, and the code is a mess in certain places.

I took the quicksort explanation from wikipedia's quick sort's graphical explanation.

The examiner said to again go through the code again, which I have done. It works fine.

My code also uses the concept of "divide and conquer" as the "partition" function in the code only works on a certain part of input array.

What's my examiner pointing at that I'm missing?

function quickSort(inputArray){
  var pivotIndex = undefined;
  var low_Index = undefined;
  var high_Index = undefined;

  pivotIndex = inputArray.length - 1;
  low_Index = 0;
  high_Index = (inputArray.length > 2) ? (inputArray.length - 2) : 0;

  partition(pivotIndex,low_Index,high_Index);

  // the function which works on partitioned array
  function partition(pivot_Index,low_Index,high_Index){
    var temp = 0;

    console.log("\nPivot Number : "+inputArray[pivot_Index]);
    console.log("input Array : "+inputArray);
    console.log("partitioned array : "+inputArray.slice(low_Index,pivot_Index+1));

    for(var low = low_Index; low < pivot_Index; low++){

        if(inputArray[low] > inputArray[pivot_Index]){

            temp = inputArray[low];
            inputArray[low] = inputArray[high_Index];
            inputArray[high_Index] = inputArray[pivot_Index];
            inputArray[pivot_Index] = temp;
            pivot_Index = high_Index;
            high_Index--;
            low--;
        }
    }// end of for loop

    if(inputArray[low_Index] > inputArray[high_Index]){
        temp = inputArray[low_Index];
        inputArray[low_Index] = inputArray[high_Index];
        inputArray[high_Index] = temp;
        pivot_Index = high_Index;
    }

    if(pivot_Index < inputArray.length - 1){

        if((pivot_Index + 1) < inputArray.length - 1){
            partition(inputArray.length - 1,(pivot_Index + 1),inputArray.length - 2);
        }

        if((pivot_Index - 2) >= 1){
            partition((pivot_Index - 1),0,(pivot_Index - 2));
        }

    }// end of if condition

  } // end of partition funtion

  return inputArray;

} // end of quick sort function

When I run the above code for input

console.log("\nFinal Sorted Array "+quickSort([5,6,1,2,7,8,3]));

the output is

rahul@rahul:~/myPractise/Algo$ node sorting.js

Pivot Number : 3
input Array : 5,6,1,2,7,8,3
partitioned array : 5,6,1,2,7,8,3

Pivot Number : 5
input Array : 1,2,3,6,7,8,5
partitioned array : 3,6,7,8,5

Pivot Number : 6
input Array : 1,2,3,5,7,8,6
partitioned array : 7,8,6

Pivot Number : 7
input Array : 1,2,3,6,5,8,7
partitioned array : 5,8,7

Pivot Number : 5
input Array : 1,2,3,6,5,7,8
partitioned array : 1,2,3,6,5

Pivot Number : 8
input Array : 1,2,3,5,6,7,8
partitioned array : 6,7,8

Pivot Number : 3
input Array : 1,2,3,5,6,7,8
partitioned array : 1,2,3

Pivot Number : 8
input Array : 1,2,3,5,6,7,8
partitioned array : 5,6,7,8

Pivot Number : 3
input Array : 1,2,3,5,6,7,8
partitioned array : 1,2,3

Pivot Number : 8
input Array : 1,2,3,5,6,7,8
partitioned array : 5,6,7,8

Pivot Number : 3
input Array : 1,2,3,5,6,7,8
partitioned array : 1,2,3

Pivot Number : 8
input Array : 1,2,3,5,6,7,8
partitioned array : 5,6,7,8

Final Sorted Array 1,2,3,5,6,7,8
rahul@rahul:~/myPractise/Algo$


texts:
I am making a web app that will have a "my files" area and to do so I am writing my own html and jQuery to control the opening and closing of each folder (or ul li). I want to make sure that this web app is as efficient as I can make it as it may have to deal with a large amount of hierarchy.

jsFiddle

<!doctype html>

        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width" />
        <title>Title</title>

                    Animals

                            Birds

                            Mammals

Elephant

Mouse

                            Reptiles

Plants

                                Flowers

Rose

Tulip

Trees


texts:
Sometimes I use std::unique_ptr<BaseClass> when all I really want is polymorphism.  For fun, I made this container that skips the heap allocation.  The downside is that it needs to know all possible derived types it will store in order to know how much space to reserve.

Any feedback is appreciated, but I'm especially interested in how this implementation enables/prevents compiler optimizations you would otherwise have with virtual types.

Edit: I am also intersted in supporting constexpr access, but right now the reinterpret_cast prevents constexpr dereference.

#include <algorithm>
#include <type_traits>

template <typename B, size_t Size, size_t Align>
struct PolyUnionSize {
    template <typename D>
    explicit PolyUnionSize(D&& d) noexcept (std::is_nothrow_copy_constructible_v<D>) {
        new(&storage) D(std::forward<D>(d));
    }

    template <typename D>
    PolyUnionSize& operator=(D&& d) noexcept(std::is_nothrow_assignable_v<B, D>) {
        this->~PolyUnionSize();
        *(new(&storage) D) = std::forward<D>(d);
        return *this;
    }

    ~PolyUnionSize() noexcept {
        (*this)->~B();
    }

    B const& operator*() const noexcept {
        return *reinterpret_cast<B const*>(&storage);
    }

    B& operator*() noexcept {
        return *reinterpret_cast<B*>(&storage);
    }

    B const* operator->() const noexcept {
        return reinterpret_cast<B const*>(&storage);
    }

    B* operator->() noexcept {
        return reinterpret_cast<B*>(&storage);
    }

private:
    typename std::aligned_storage<Size, Align>::type storage;
};

constexpr auto max(std::initializer_list<std::size_t> const& t) noexcept {
    return *std::max_element(std::begin(t), std::end(t));
}

template <typename B, typename ... Ds>
struct PolyUnion : public PolyUnionSize<B, max({sizeof(Ds)... }), max({alignof(Ds)... })> {
    using PUSize = PolyUnionSize<B, max({sizeof(Ds)... }), max({alignof(Ds)... })>;

    template <typename D>
    explicit PolyUnion(D&& d) noexcept(std::is_nothrow_copy_constructible_v<D>)
        : PUSize(std::forward<D>(d))
    {
        static_assert((std::is_base_of_v<B, Ds> && ...));
        AssertDinDs<D>();
    }

    template <typename D>
    PolyUnion& operator=(D&& d) noexcept(std::is_nothrow_assignable_v<B, D>) {
        AssertDinDs<D>();
        PUSize::operator=(std::forward<D>(d));
        return *this;
    }

private:
    template <typename D>
    constexpr void AssertDinDs() const& noexcept{
        static_assert((std::is_same_v<D, Ds> || ...));
    }
};

Sample usage:

struct Base {
    virtual int Foo() const { return 1; }
};

struct A : Base {
    int Foo() const final { return 2; }
};

struct B : Base {
    int Foo() const final { return 3; }
};

int main() {
    PolyUnion<Base, A, B> pu(A{});
    pu = B{};
    return pu->Foo();
}

Compiles with -std=c++17 or -std=c++2a


texts: Is this the right way to handle Exceptions in PHP?

texts:
I'm using the function countLikes() to fetch URLs' Likes count from the Facebook API.

// Link.php

class Link
{

private $url;

public function __construct($url){
    $this->url = new Url($url);
}

public function getUrl(){
    return $this->url();
}

public function countLikes()
{
    global $config;

    $call = $config["facebook.api"]["baseurl"] .
            "/" .
            $config["facebook.api"]["version"] .
            "/?" .
            "id=" . $this->url->getEncodedUrl() .
            "&access_token=" . $config["facebook.api"]["key"];

    try {
        $response = Utils::curl($call);
    } catch (\Exception $e) {
        throw new LinkException("Unable to cURL Facebook API.", 0, $e);
    }

    if (is_array($response)) {
        if (array_key_exists("error", $response)) {
            throw new LinkException(
            "Facebook Graph API v2.2 error : "
            . $response["error"]["message"], $response["error"]["code"]
            );
        } elseif (isset($response["share"])) {
            $count = $response["share"]["share_count"];
        } else {
            $count = 0;
        }

        return $count;
    } else {
        throw new LinkException("Graph API Response is not an array");
    }
}
}

And this is how it's used :

$link = new Link("http://www.facebook.com");

try{
    $likes = $link->countLikes();
    echo "Link $link->getUrl()->getFullUrl() has $likes likes for the moment. <br>";
} catch(LinkException $e){
    do{
        $logger->add($e->getMessage());
    }while ($e = $e->getPrevious());
}

While this is working as it's supposed to do, I'm not happy with the way exceptions are treated and I'm not even sure this is the right way to do it. Is there a better way to manage exceptions and handle them?


texts:
I am currently for a program I am writing needing to compare two associative arrays by key and value in PHP and get the common elements as well as the difference between the common elements.

I have currently arrived at the following solution:

<?php
$newArr = [0 => ['id' => 'UT5', 'qty' => '4'], 1 => ['id' => 'WRO', 'qty' => '3'], 2 => ['id' => 'SHO', 'qty' => '3']];

$oldArr = [0 => ['id' => 'SHO', 'qty' => '1'], 1 => ['id' => 'UT5', 'qty' => '2'], ];

$newReset = [];
foreach( $newArr as $item ) {
    $newReset[$item['id']] = $item['qty'];
}

$oldReset = [];
foreach( $oldArr as $item ) {
    $oldReset[$item['id']] = $item['qty'];
}

foreach( $newReset as $key => $val ) {
    if( isset( $oldReset[$key] ) ) {
        $toAdd[$key] = max( $oldReset[$key], $val ) - min( $oldReset[$key], $val );
    }
    else $toAdd[$key] = intval($val);
}

var_dump( $toAdd );

I am just curious as to how I can go about implementing perhaps array functions or an array function with a closure etc... to refactor the approach or use another method entirely?

For reference, my output is currently as follows:

array(3) {  ["UT5"]=> int(2)  ["WRO"]=> int(3)  ["SHO"]=> int(2) }

Any help is appreciated.

Thanks!


texts: Forecasting function using auto.arima for 15 samples of data

texts:
I have a workbook with data sampled. i have multiple samples based on date range. one sample starts from january, where other can start from february and so on. I need to build forecasting function using auto.arima for 15 samples of data. instead of writing auto.arima 15 times, i tried using a loop to execute the code and get results from 15 models in the end for comparison. It takes lot of time to execute this through loops Vs if i do this manually one after another. Is there any way to reduce the processing time? I know that for loop tends to slower, but is there any way to replace for loop in this case?

library("readxl")
library("lubridate")
library("forecast")
library("parallel")
library("doParallel")
library("foreach")

##Use multicore processing
cl <- makeCluster(detectCores() - 1)
registerDoParallel(cl, cores = detectCores() - 1)

  for (i in 1:15) {
    #read excel file and format date column
    da<-paste("El3M","-",i,sep = "")
    a<-read_excel("All Models.xlsm", sheet = da,col_names=TRUE)
    a$Date<-as.Date(a$Date,"%Y-%m-%d")

    #add seasonality dummy variable and remove intercept column
    abc <- cbind(Weekday=model.matrix(~as.factor(a$DOW)),
                 Day=model.matrix(~as.factor(a$DOM)),a[,7,drop=FALSE])
    abc<-data.frame(abc)
    abc<-data.frame(abc[,c(-1,-8)])

    #partition data into train and test
    abc2 <- subset(abc,abc$Ya==1)
    abc2 <- abc2[,-37]
    abc3 <- subset(abc,abc$Ya==2)
    abc3 <- abc3[,-37]

    #train and insample MAPE
    a1<-subset(a,a$Ya==1)
    a2<-subset(a,a$Ya==2)

    ###ARIMA###
    val.ts<-ts(a1$Actual,start=c(year(a1$Date[1]),month(a1$Date[1]),day(a1$Date[1])),freq=365)
    ARIMAfit2 <- auto.arima(val.ts,xreg=abc2,stepwise=FALSE,approx=FALSE)

    #test and forecasted MAPE
    azz<-forecast(ARIMAfit2,h=90,xreg=abc3)
    azz<-azz$mean
    azz <- data.frame(azz)
    azz$Actual <- a2$Actual
    azz$MAPE <- abs(azz$azz-azz$Actual)/azz$Actual

    #print error results from model
    print(paste("ARIMA Sample ",da, "MAPE hold Total =",mean(azz$MAPE[1:90],na.rm = TRUE),sep = ""))

}


texts: Typesetting A* in LaTeX using algorithm2e - follow-up

texts:
(See the previous and initial iteration.)

I have this second version of my LaTeX code. I made it less dry by removing the duplicate keyword definitions shared by the two algorithms being typeset. Also, in the previous version, in the argument of main While loop, OPEN was typeset instead of desired OPEN.

See what I have now:

\documentclass[10pt]{article}

\usepackage{amsmath}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}

\SetArgSty{textnormal} % Make the While argument non-italic

% Define special keywords.
\SetKw{Nil}{nil}
\SetKw{Is}{is}
\SetKw{Not}{not}
\SetKw{Mapped}{mapped}
\SetKw{In}{in}
\SetKw{ChildNode}{child node}
\SetKw{Of}{of}
\SetKw{Continue}{continue}

\begin{document}

  % A*.
  \begin{algorithm}
        $\text{OPEN} = \{ s \}$ \\
        $\text{CLOSED} = \emptyset$ \\
        $\pi = \{ (s \mapsto$ \Nil $)\}$ \\
        $g = \{ (s \mapsto 0) \}$ \\
        \While{$|\text{OPEN}| > 0$}{
          $u = \textsc{ExtractMinimum}(\text{OPEN})$ \\
          \If{$u$ \Is $t$}{
            \KwRet \textsc{TracebackPath}$(u, \pi)$ \\
          }
          $\text{CLOSED} = \text{CLOSED} \cup \{ u \}$ \\
          \ForEach{\ChildNode $v$ \Of $u$}{
            \If{$v \in \textsc{CLOSED}$}{
              \Continue \\
            }
            $c = g(u) + w(u, v)$ \\
            \If{$v$ \Is \Not \Mapped \In $g$}{
              $g(v) = c$ \\
              $\pi(v) = u$ \\
              \textsc{Insert}$(\text{OPEN}, v, c + h(v))$ \\
            }
            \ElseIf{$g(v) > c$}{
              $g(v) = c$ \\
              $\pi(v) = u$ \\
              \textsc{DecreaseKey}$(\text{OPEN}, v, c + h(v))$ \\
            }
          }
        }
        \KwRet $\langle \rangle$
        \caption{\textsc{AStarPathFinder}$(s, t, w, h)$}
  \end{algorithm}

  % Traceback path.
  \begin{algorithm}
        $p = \langle \rangle$ \\
        \While{$u$ \Is \Not \Nil}{
          $p = u \circ p$ \\
          $u = \pi(u)$ \\
        }
        \KwRet $p$
      \caption{\textsc{TracebackPath}$(u, \pi)$}
  \end{algorithm}

\end{document}

The result looks like this:

Any critique is much appreciated.


texts:
I've been looking for a way to have a predicate that establishes that all elements of a list are substrings delimited by a given string. Analogues in other languages include: 'delimiter'.join(list) in Python, (mapconcat function sequence delimiter) in Emacs Lisp, array.join('delimiter') in JavaScript, and I'm sure there are more of the kind. Below are three different variants I came up with, but I've a strong feeling that I'm reinventing the wheel here:
join
join(_, [X], X) :- !.
join(Sep, [X | Xs], S) :-
    join(Sep, Xs, Sx),
    string_concat(Sep, Sx, Sy),
    string_concat(X, Sy, S).

Seems to be the simplest, but I don't like that it is not tail-recursive and that it has an obvious repetitive pattern.
interleave
interleave([X], _, X) :- !.
interleave([X | Xs], Glue, Result) :-
    interleave(Xs, Glue, Previous),
    format(atom(Result), "~p~p~p", [X, Glue, Previous]).

Still not tail-recursive, no repetition, but I'm not sure how bad is format if compared to plain string_concat.
mapconcat
reduce([], X, _, X) :- !.
reduce([X | Xs], Acc, Predicate, Result) :-
    call(Predicate, Acc, X, Interim),
    reduce(Xs, Interim, Predicate, Result).
reduce([X | Xs], Predicate, Result) :- reduce(Xs, X, Predicate, Result).

mapconcat_helper(Glue, X, Y, Z) :- format(atom(Z), '~p~p~p', [X, Glue, Y]).

mapconcat(List, Glue, Result) :-
    reduce(List, mapconcat_helper(Glue), Result).

To my surprise, there isn't a reduce-like predicate in the standard library, so I had to write my own. Finally, this won't explode the stack for longer lists.

So, which one, if any of these is best? Perhaps there are libraries that already do this better? I'm using SWI Prolog, and am doing this mostly for self-education, so I'm not yet concerned with portability etc. If it's SWI-specific, I think it'd still do.


texts: Calculate total, minimum, maximum and mean from a set of distances

texts:
I have only begun to learn C++ and am reading through the book, "Programming Principles and Practices Using C++". This bit of code is my attempt to complete exercise 3 at the end of chapter 4.

The actual task is:

  Read a sequence of double values into a vector. Think of each value as the distance between two cities along a given route. Compute and print the total distance (the sum of all distances). Find and print the smallest and greatest distance between two neighboring cities. Find and print the mean distance between two neighboring cities.

I am looking for any constructive criticism of my code. Keep in mind some things have not been covered. Even saying that, I still wouldn't mind hearing about what could be. Some things have been covered and I just don't implement them well.

    #include "std_lib_facilities.h"

int main()
{
    double ddistance = 0;
    double dtotaldist = 0;
    double dgreatest = 0;
    double dshortest = 0;
    char cgoagain;
    bool bgoagain = true;
    vector<double>vdistance;

    while (bgoagain) {
        cout << "Enter a valid 'double' ";
        cin >> ddistance;

    if (cin) {
        vdistance.push_back(ddistance);
        dtotaldist += ddistance;
        dshortest = ddistance;

        for (int i = 0; i < vdistance.size(); ++i)
            if ((vdistance[i]) > dgreatest) {
                dgreatest = vdistance[i];
            }
        for (int i = 0; i < vdistance.size(); ++i)
            if (vdistance[i] < dshortest) {
                dshortest = vdistance[i];
            }

        std::cout << "vdistance size is\t" << vdistance.size() << "\n";
        std::cout << "dtotaldist size is\t" << dtotaldist << "\n";
        std::cout << "The mean distance is\t" << dtotaldist / vdistance.size() << "\n";
        std::cout << "The long distance is\t" << dgreatest << "\n";
        std::cout << "The short distance is\t" << dshortest << "\n";
    }

    else {
        std::cout << "That is not a valid value. Would you like to try again? 'y' / 'n' \n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cin >> cgoagain;
        if (cgoagain == 'y' || cgoagain == 'Y') {
            bgoagain = true;
        }
        else{
            bgoagain = false;
        }
    }

    }
}


texts: Preprocess HTML input and generate word count

texts:
Below you see the product of my first baby-steps in programming. The purpose of the script is twofold:
1. Take html input of a specific website, process it, and return relevant info such as document id, text, and headline.
2. Generate a count of the words in all the articles.

The script is working and does what it is supposed to, however, I cannot help but feel that I'm missing a lot in terms of performance.

import re
import pandas as pd
from urllib.request import urlopen as uReq
from sklearn.feature_extraction.text import CountVectorizer

TAG_RE = re.compile(r'<[^>]+>')
def RemoveTags(text):
     """Remove all html tags"""
     return TAG_RE.sub('', text)

ESCAPES_RE = re.compile(r'\\.')
def RemoveEscapes(text):
    """Remove extra escape characters from encoding"""
    return ESCAPES_RE.sub('', text)

def ReadFromLink(link):
    """Read html from link and return raw html"""
    with uReq(link) as response:
        html = response.read()#
        html = str(html).lower()
        return html.lower()

def ArticleRaw(html):
    """Find articles in html"""
    article = re.findall(r'<doc>.*?</doc>', html)
    return article

def GetDocID(html):
    """Find document ids in html"""
    docid = re.findall(r'<docid>(.*?)</docid>', html)
    docid = [docid.strip() for docid in docid]
    docid = [int(docid) for docid in docid]
    return docid

def GetHeadline(html):
    """Find headlines in html"""
    headline = re.findall(r'<headline>(.*?)</headline>', html)
    headline = [RemoveTags(headline) for headline in headline]
    headline = [RemoveEscapes(headline) for headline in headline]
    return headline

def GetMainText(html):
    """Find maintext in html"""
    maintext = re.findall(r'<text>(.*?)</text>', html)
    maintext = [RemoveTags(maintext) for maintext in maintext]
    maintext = [RemoveEscapes(maintext) for maintext in maintext]
    maintext = [' '.join(maintext.split()) for maintext in maintext]
    return maintext

link = link
html = ReadFromLink(link)

ArticlesDict = {
        "docid": GetDocID(html),
        "raw_article": ArticleRaw(html),
        "headline": GetHeadline(html),
        "maintext": GetMainText(html)
}

def CountFeatures(text):
    documents = ArticlesDict['maintext']
    # Stem first?
    vector = CountVectorizer()
    x = vector.fit_transform(documents)
    df_features = pd.DataFrame(x.toarray(), columns = vector.get_feature_names())
    return df_features

df_features = CountFeatures(df_articles['maintext'])


texts:
This is the original question:
https://www.geeksforgeeks.org/run-length-encoding/

  Given an input string, write a function that returns the Run Length
  Encoded string for the input string. For example, if the input string
  is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6”.

the only change I did is that if the character appears once there is no need to print 1 after the letter.

Please review for perfomance

using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace StringQuestions
{
    /// <summary>
    /// https://www.geeksforgeeks.org/run-length-encoding/
    /// </summary>
    [TestClass]
    public class RunLengthEncoding
    {
        [TestMethod]
        public void RunLengthEncodingTest()
        {
            string str = "wwwwaaadexxxxxxywww";
            string expected = "w4a3dex6yw3";
            Assert.AreEqual(expected, RLE.Encode(str));
        }
    }

    public class RLE
    {
        public static string Encode(string str)
        {
            str = str.ToLower();
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < str.Length; i++)
            {
                int counter = 1;
                if (!char.IsLetter(str[i]))
                {
                    throw new ArgumentException("string should contains only letters");
                }

                while (i < str.Length - 1 && str[i] == str[i + 1])
                {
                    counter++;
                    i++;
                }

                if (counter == 1)
                {
                    stringBuilder.Append(str[i]);
                }
                else
                {
                    stringBuilder.Append(str[i]);
                    stringBuilder.Append(counter);
                }
            }

            return stringBuilder.ToString();
        }
    }
}


texts:
So for an side exercise on exercism I implemented a BinarySearchTree.
I was confident in implementing the creation of the binary tree. But I'm very unsure about the traversal of the tree. So I came up with two implementations of the traversal algorithm - which one is the "better" solution?

I'm learning about F# because I want to learn Functional Programming. This is code review - so any criticism is welcome!

module BinarySearchTree

type Node<'a> =
    { Left: Node<'a> option
      Right: Node<'a> option
      Data: 'a }

let left (node: Node<'a>)  = node.Left

let right (node: Node<'a>) = node.Right

let data (node: Node<'a>) : 'a = node.Data

let rec insertNode (root: Node<'a> option) (nextValue: 'a) : Node<'a> =
    match root with
    | Some root -> if nextValue <= root.Data then { root with Left = Some(insertNode root.Left nextValue) }
                   elif nextValue > root.Data then { root with Right = Some(insertNode root.Right nextValue) }
                   else root
    | None -> { Left=None; Right=None; Data=nextValue }

let create (items: 'a list) : Node<'a> =
     items
     |> List.fold (fun (acc: Option<Node<'a>>) (item: 'a) -> Some(insertNode acc item)) None
     |> function
        | None -> failwith "Failed to construct binary tree. You must pass a valid item list."
        | Some root -> root

let sortedData (node: Node<'a>) : ('a list) =
    let rec traverse (acc: 'a list) (node: Node<'a>)  =
        match (node.Left, node.Right) with
        | Some left, Some right -> seq {
                                   yield! node.Data::acc
                                   yield! (traverse [] left)
                                   yield! (traverse [] right)}
                                   |> Seq.toList
        | Some left, None -> traverse (node.Data::acc) left
        | None, Some right -> traverse (node.Data::acc) right
        | None, None -> node.Data::acc

    List.sort (traverse [] node)

And the alternative implementation of sortedData:

let sortedData (node: Node) : (int list) =

 let rec traverse (acc: int list) (node: Node)  =
        match (node.Left, node.Right) with
        | Some left, Some right -> (node.Data::acc)@(traverse [] left)@(traverse [] right)
        | Some left, None -> traverse (node.Data::acc) left
        | None, Some right -> traverse (node.Data::acc) right
        | None, None -> node.Data::acc

    List.sort (traverse [] node)


texts:
Learn You a Haskell presents the randoms function.

I implemented it as follows:

-- randoms that takes a generator and returns an infinite sequence
-- of values based on that generator
import System.Random

randoms' :: StdGen -> [Int]
randoms' g = num : randoms' gen
   where (num, gen) = random g

Please critique it.


texts: Toggling the visibility of drop-down menu items

texts:
var x = 0;
document.getElementById("1").addEventListener("click", function() {
    if ((x % 2) == 0) {
        document.getElementById("dropdown_1").style.display = 'block';
    } else {
        document.getElementById("dropdown_1").style.display = 'none';
    }
    x += 1;
});
var y = 0;
document.getElementById("2").addEventListener("click", function() {
    if ((y % 2) == 0) {
        document.getElementById("dropdown_2").style.display = 'block';
    } else {
        document.getElementById("dropdown_2").style.display = 'none';
    }
    y += 1;
});

I made a HTML-Page with a menu that has a drop-down function. But i wasnt able to write it in a proper code, i thought using a loop would be helpful but i didnt manage to do so.