mardi 5 mai 2015

Multidimensional Arrays in Ruby like C++

I had previously created a struct and an array of the same in C++ , now i want to implement the same in Ruby.

/ Number of Elements (Which can be increased) :D
#define ELM_NO 110

struct elem
{
  char name[18];
  char elm_symbol[5];

  double atm_weight;

  int elm_melting;
  int elm_boiling;
  int elm_yearofdis;
  int elm_group;

  double elm_ionis_e;
};

elem element[ELM_NO] = { {" Hydrogen"  ,"H"  ,1.0079 ,-259 ,-253 ,1776 ,1  ,13.5984 },
                      {" Hydrogen"  ,"H"  ,1.0079 ,-259 ,-253 ,1776 ,1  ,13.5984  } ,
                      {" Helium"  ,"He" ,4.0026 ,-272 ,-269 ,1895 ,18 ,24.5874  } ,
                      {" Lithium" ,"Li" ,6.941  ,180  ,1347 ,1817 ,1  ,5.3917 } ,
                      {" Beryllium" ,"Be" ,9.0122 ,1278 ,2970 ,1797 ,2  ,9.3227 } ,
                      {" Boron" ,"B"  ,10.811 ,2300 ,2550 ,1808 ,13 ,8.298  } ,
                      {" Carbon"  ,"C"  ,12.0107  ,3500 ,4827 ,0  ,14 ,11.2603  } ,
                      {" Nitrogen" ,"N"  ,14.0067  ,-210 ,-196 ,1772 ,15 ,14.5341  } ,
                      {" Oxygen" ,"O"  ,15.9994  ,-218 ,-183 ,1774 ,16 ,13.6181  } ,
                      {" Fluorine" ,"F"  ,18.9984  ,-220 ,188  ,1886 ,17 ,17.4228  } ,
                      {" Neon" ,"Ne" ,20.1797  ,-249 ,-246 ,1898 ,18 ,21.5645  } ,
                      {" Sodium" ,"Na" ,22.9897  ,98 ,883  ,1807 ,1  ,5.1391 } ,
                      {" Magnesium"  ,"Mg" ,24.305 ,639  ,1090 ,1755 ,2  ,7.6462 } ,
                      {" Aluminum" ,"Al" ,26.9815  ,660  ,2467 ,1825 ,13 ,5.9858 } };

Omitted some parts.

Now , I want to implement in Ruby . The problem is I don't know how to implement 2D arrays from which we can access an Individual Element from the Inner Array.

I have checked on previous Questions , and found that the answers were not either clear or were concerned with Narrays.

Can anybody show me how it's done ?

How to showing the date_part all

I have a data array's like this. and I want to make this data into grafik. and the problem is when i put the script

if (isset($b['admin'])) {
      echo $b['admin'];
      $series = $this->HighCharts->addChartSeries();
      $series->addName($user)->addData([(int)$b['admin']]);
      $mychart->addSeries($series);
}

in the foreach($datas as $a){. why the date_part 3 couldn't be show?

QUERY RESULT ARRAY

$array = array(
        (int) 0 => array( 
                        'B' => array(
                                    'company' => 'ABC' 
                        ), 
                        'User' => array( 
                                    'company' => 'abc' 
                        ), 
                        (int) 0 => array(
                                    'date_part' => '3',
                                    'jumlah' => null, 
                                    'jumbuy' => '50990', 
                                    'admin' => '50010' 
                        )
        ),
        (int) 1 => array(
                        'B' => array( 
                                    'company' => 'BCD'
                        ), 
                        'User' => array( 
                                    'company' => 'bcd' 
                        ), 
                        (int) 0 => array( 
                                    'date_part' => '3',
                                    'jumlah' => null, 
                                    'jumbuy' => '65000', 
                                    'admin' => '5000' )
        ),
        (int) 2 => array(
                        'B' => array(
                                    'company' => 'ABC' 
                        ), 
                        'User' => array( 
                                    'company' => 'abc' 
                        ), 
                        (int) 0 => array(
                                    'date_part' => '4',
                                    'jumlah' => null, 
                                    'jumbuy' => '98990', 
                                    'admin' => '2010' )
        ),
        (int) 3 => array(
                        'B' => array(
                                    'company' => 'CDE'
                        ), 'User' => array( 
                                    'company' => 'cde' 
                        ), 
                        (int) 0 => array(
                                    'date_part' => '4',
                                    'jumlah' => null, 
                                    'jumbuy' => '34566', 
                                    'admin' => '2010' )
        ),
        (int) 4 => array(
                        'B' => array( 
                                    'company' => 'BCD'
                        ), 
                        'User' => array( 
                                    'company' => 'bcd' 
                        ), 
                        (int) 0 => array( 
                                    'date_part' => '4',
                                    'jumlah' => null, 
                                    'jumbuy' => '9000', 
                                    'admin' => '5000' )
        ),
);

IN CONTROLLERS

$chartName = 'Line Chart with Data Labels';
$tooltipFormatFunction = <<<EOF
function() { return '<b>'+ this.series.name +'</b><br/>'+ this.x +': '+ this.y +'°C';}
EOF;

    $mychart = $this->HighCharts->create($chartName, 'line');

    $data = array();
    foreach($report_posts as $values) {
        if (!isset($data[$values['User']['company']])) {
            $data[$values['User']['company']] = $values;
        } else {
            $last_element = array_pop($values);
            $data[$values['User']['company']][] = $last_element;
        }
    }
    $datas = array_values($data);

    foreach ($datas as $a) {
            $user = [$a['User']['company']];
            foreach ($a as $b) {
                if (isset($b['date_part'])) {
                    $this->HighCharts->setChartParams($chartName, array(
                            'renderTo' => 'linewrapper', // div to display chart inside
                            'chartWidth' => 1000,
                            'chartHeight' => 750,
                            'chartMarginTop' => 60,
                            'chartMarginLeft' => 90,
                            'chartMarginRight' => 30,
                            'chartMarginBottom' => 110,
                            'chartSpacingRight' => 10,
                            'chartSpacingBottom' => 15,
                            'chartSpacingLeft' => 0,
                            'chartAlignTicks' => FALSE,
                            'chartTheme' => 'dark-green',
                            'title' => 'Monthly Average Temperature',
                            'subtitle' => 'Source: WorldClimate.com',
                            'titleAlign' => 'center',
                            'titleFloating' => TRUE,
                            'titleStyleFont' => '18px Metrophobic, Arial, sans-serif',
                            'titleStyleColor' => '#0099ff',
                            'titleX' => 20,
                            'titleY' => 10,
                            'legendEnabled' => TRUE,
                            'legendLayout' => 'horizontal',
                            'legendAlign' => 'center',
                            'legendVerticalAlign ' => 'bottom',
                            'legendItemStyle' => array('color' => '#222'),
                            'legendBackgroundColorLinearGradient' => array(0, 0, 0, 25),
                            'legendBackgroundColorStops' => array(array(0, 'rgb(217, 217, 217)'), array(1, 'rgb(255, 255, 255)')),
                            'tooltipEnabled' => TRUE,
                            'tooltipFormatter' => $tooltipFormatFunction,
                            'xAxisLabelsEnabled' => TRUE,
                            'xAxisLabelsAlign' => 'right',
                            'xAxisLabelsStep' => 1,
                            'xAxislabelsX' => 5,
                            'xAxisLabelsY' => 20,
                            'xAxisCategories' => [$b['date_part']],
                            'yAxisTitleText' => 'Admin',
                            'plotOptionsLineDataLabelsEnabled' => TRUE,
                            'plotOptionsLineEnableMouseTracking' => TRUE,
                            'enableAutoStep' => FALSE
                        )
                    );
                }//end if

            }//end foreach

        if (isset($b['admin'])) {
            echo $b['admin'];
            $series = $this->HighCharts->addChartSeries();
            $series->addName($user)->addData([(int)$b['admin']]);
            $mychart->addSeries($series);
        }

    }

Array sent from Android to PHP via $_POST getting mucked up in transit

This problem is driving me crazy and I have no idea how to fix it. I have an Android program to gather all names and phone numbers into an array (basic key-value pairs) and then send that array over to a PHP script. The PHP script then parses the values received in a $_POST and inserts them into a MySQL table. Everything works fine except that the data doesn't always come as posted. For instance, some numbers get paired with names they don't belong to. Here's a snippet of my PHP:

$ar = 0;
foreach($_POST as $entry){
    echo $ar.". ".$_POST[$ar]."\n";
    $namenum = explode(',', $entry);
    $names[$ar] = $namenum[1];
    $numbers[$ar] = $namenum[0];
    echo $ar.". ".$numbers[$ar]."--->".$names[$ar]."\n"; 
    $ar += 1;
}
$namenum = NULL;
//$ar = NULL;

The above snippet is right at the beginning of the script and there's nothing to tamper with $_POST. The echo within the loop is to test this exact thing and that's how I discovered the problem. The weirdest part is that most of the time, the data received is exactly as sent. But then at times I suddenly notice a couple of numbers getting either mixed up with wrong names or disappearing altogether. I must also add that each time I have tested the program, I've done it on the same device, using the same contact list. Everything remains the same between test runs and yet results vary at random. The gremlins seem to be appearing in transit! Is this a known issue with $_POST or sending arrays in general? If so, what alternatives do I have? I can think of JSON or text files but would that ensure better data fidelity?

jQuery autocomplete - assigning one JSON PHP array to multiple HTML ID tags

I have successfully setup a jQuery autocomplete call from a PHP file using JSON encode. I am successfully sending a KVP (Key Value Pair) array back to my HTML.

The issue I have, is that I wish to send part of the array items to one id="sometag1" and the other array items to id="sometag2" and id="sometag3".

Here is my javascript jquery code:

jQuery(document).ready(function(data) {
    $('#edit-ad-location').autocomplete({
        source: '/postcodes-latlong.php',
        minLength: 2
    });
});

The file "postcodes-latlong.php" contains the following code:

$rs = mysql_query('select p.ID, p.post_title, m.* FROM wp_posts p, wp_postmeta m WHERE p.ID = m.post_id AND p.post_title like "' . mysql_real_escape_string($_REQUEST['term']) . '%" AND meta_value is NOT NULL AND meta_value !="" AND (meta_key = "_aphs_FYN_latitude" OR meta_key = "_aphs_FYN_longitude") order by post_title limit 0,25', $dblink);
$this_row = "";
// loop through each postcode returned and format the response for jQuery
$data = array();
if ($rs && mysql_num_rows($rs)) {
    while ($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
        $new_row = $row['post_title'];
        if ($new_row != $this_row) {
            $data[] = array(
                'id' => $row['meta_id'],
                'label' => $row['post_title'],
                'value' => $row['post_title']
            );
        }
        if ($row['meta_key'] == "_aphs_FYN_latitude") {
            $data[] = array_push($data, array(
                'id' => 'geo-search-lat',
                'value' => $row['meta_value']
            ));
        }
        if ($row['meta_key'] == "_aphs_FYN_longitude") {
            $data[] = array_push($data, array(
                'id' => 'geo-search-lng',
                'value' => $row['meta_value']
            ));
        }
        $this_row = $row['post_title'];
    }
}
// jQuery wants JSON data
echo json_encode($data);
flush();

And if the term 4503 is passed, we get the following returning array:

[{
    "id": "384047",
    "label": "4503, DAKABIN",
    "value": "4503, DAKABIN"
}, {
    "id": "geo-search-lat",
    "value": "-27.226474"
}, 2, {
    "id": "geo-search-lng",
    "value": "152.980732"
}, 4, {
    "id": "384062",
    "label": "4503, GRIFFIN",
    "value": "4503, GRIFFIN"
}, {
    "id": "geo-search-lat",
    "value": "-27.272654"
}, 7, {
    "id": "geo-search-lng",
    "value": "153.025911"
}, 9, {
    "id": "384077",
    "label": "4503, KALLANGUR",
    "value": "4503, KALLANGUR"
}, {
    "id": "geo-search-lat",
    "value": "-27.25075"
}, 12, {
    "id": "geo-search-lng",
    "value": "152.992606"
}, 14, {
    "id": "384092",
    "label": "4503, KURWONGBAH",
    "value": "4503, KURWONGBAH"
}, {
    "id": "geo-search-lat",
    "value": "-27.225828"
}, 17, {
    "id": "geo-search-lng",
    "value": "152.947552"
}, 19, {
    "id": "384107",
    "label": "4503, MURRUMBA DOWNS",
    "value": "4503, MURRUMBA DOWNS"
}, {
    "id": "geo-search-lat",
    "value": "-27.258672"
}, 22, {
    "id": "geo-search-lng",
    "value": "153.006916"
}, 24, {
    "id": "384122",
    "label": "4503, WHITESIDE",
    "value": "4503, WHITESIDE"
}, {
    "id": "geo-search-lat",
    "value": "-27.255364"
}, 27, {
    "id": "geo-search-lng",
    "value": "152.929729"
}, 29]

What I am trying to achieve, is send the ID, label and value (i.e. post_id, postcode, and suburb name) to the autocomplete field with id: "#edit-ad-location" and this works fine. But, I wish to send the latitude and longitude values to two other id tags #geo-search-lat and #geo-search-lng as shown below:

<div .... id="geo-search-lat" value=""> </div>

and

<div .... id="geo-search-lng" value=""> </div>

I have tried a number of approaches including converting the PHP JSON array to a Javascript array also trying to pass the JSON array as PHP array rather than JSON...

But I am struggling to glue all this together.

Is there a simple way to parse the array so that part of the KVP's go to one ID tag, and the rest goes to two other ID tags?

Something along the lines of:

jQuery(document).ready(function(data){
    $('#edit-ad-location', '#geo-search-lat', '#geo-search-lng').autocomplete({source:'/postcodes-latlong.php', minLength:2});
});

But if I try this approach returns an error.

You can try sending australian postcodes to the following URL and test it for yourslef:

http://ift.tt/1ckqpn9

Where XXXX is any integer from 0 to 9999.

Any help is appreciated.

Cheers, Henry

Need help accessing JSON array object

Objective: This code collects an array JSONAPIS and passes the APIS into a $.each() loop. Then JSON data field are evaluated in if statements and used to calculate precip. How do I access the JSONAPIS from the obj. Main issue: obj.daily.data.length is undefined on the daily array member. The obj should contain one of the API calls and the JSON dataset to use. Instead it contains keyword like abort, always, promise which I am not familiar how to use. What would access the result JSON object property?

var listAPIs = "";
    var darkForecastAPI = [];
    var result = [];
    var JSONAPIS = [];
$.each(numDaysAPITimes, function(a, time) {
    var darkForecastAPI = /*"http://ift.tt/1eU3pXU" + currentAPIKey + "/history_" + time + "/q/" + state + "/" + city +".json?callback=?"; */
        "http://ift.tt/1JmMFqC" + currentAPIKey + "/" + city + time + "?callback=?";
    //http://ift.tt/1iYC1hI
    JSONAPIS.push($.getJSON(darkForecastAPI, {
        tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
        tagmode: "any",
        format: "json"
    }));
});
$.when(JSONAPIS).then(function(result) { /*no log simply an array */
    var eachPrecipSum = 0.0;
    var totalPrecipSinceDate = 0.0;
    alert(result);

    $.each(result, function(d, obj) {
        for (var c = 0; c <= obj.daily.data.length - 1; c++) {
            if (obj.daily.data[c].precipIntensity >= 0.0000 && obj.daily.data[c].precipType == "rain") /*Number(result.history.dailysummary.precipm, result.history.dailysummary.rain*/ {
                eachPrecipSum = result[d].daily.data[c].precipIntensity;
                totalPrecipSinceDate = eachPrecipSum + totalPrecipSinceDate; ///Write mean precip
                alert(Math.round(eachPrecipSum * 10000) / 10000);
                $("body").append("p").text("There has been as least a total of " + Math.round(totalPrecipSinceDate * 10000) / 10000 + " inches per hour of rain at the location in the last " + userDataDatePick + " days")

            } else if (obj.daily.data[c].precipIntensity >= 0.0000 && obj.daily.data[c].precipType != "rain") {
                alert("There is was no rain on ____" /*+ result.history.dailysummary.mon + "/" + result.history.dailysummary.mday + "/" + result.history.dailysummary.year*/ );
            }
        }
    });
});
numDaysAPITimes = 0;

}

Bank Account Java Program

I am creating a bank account program for my java class that is suppose to manage up to 5 different bank accounts. The program has to allow the creation of a new account, which I have done, allow deposit and withdraw, which is also done, the 2 parts I cannot get to work are 1: the bank can only have up to 5 accounts, so if a 6th is trying to be created, a message comes up saying that 5 are already created, and 2: one of the options has to print out all the account balances of current accounts in the bank.

This is my code as of now:

import java.util.Scanner;
public class Bankapp {

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    Bank myBank = new Bank();

    int user_choice = 2;


    do {
        //display menu to user
        //ask user for his choice and validate it (make sure it is between 1 and 6)
        System.out.println();
        System.out.println("1) Open a new bank account");
        System.out.println("2) Deposit to a bank account");
        System.out.println("3) Withdraw to bank account");
        System.out.println("4) Print account balance");
        System.out.println("5) Quit");
        System.out.println();
        System.out.print("Enter choice [1-5]: ");
        user_choice = s.nextInt();
        switch (user_choice) {
            case 1: 
                System.out.println("Enter a customer name");
                    String cn = s.next();
                    System.out.println("Enter a opening balance");
                    double d = s.nextDouble();
                    System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
                    break;
            case 2: System.out.println("Enter a account number");
                    int an = s.nextInt();
                    System.out.println("Enter a deposit amount");
                    double da = s.nextDouble();
                    myBank.depositTo(an, da);
                    break;
            case 3: System.out.println("Enter a account number");
                    int acn = s.nextInt();
                    System.out.println("Enter a withdraw amount");
                    double wa = s.nextDouble();
                    myBank.withdrawFrom(acn, wa);
                    break;
            case 4: System.out.println("Enter a account number");
                    int anum = s.nextInt();
                    myBank.printAccountInfo(anum);
                    break;
            case 5:
                    System.out.println("Here are the balances " + "for each account:");
            case 6:
                System.exit(0);
        }
}
while (user_choice != '6');
}

static class Bank {
private BankAccount[] accounts;     // all the bank accounts at this bank
private int numOfAccounts = 5;      // the number of bank accounts at this bank

// Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
    accounts = new BankAccount[5];
    numOfAccounts = 0;
    }

// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {

    BankAccount b = new BankAccount(customerName, openingBalance);
    accounts[numOfAccounts] = b;
    numOfAccounts++;
    return b.getAccountNum();
}

// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
    for (int i =0; i<numOfAccounts; i++) {
        if (accountNum == accounts[i].getAccountNum()  ) {
            accounts[i].withdraw(amount);
            System.out.println("Amount withdrawn successfully");
            return;
        }
    }
    System.out.println("Account number not found.");
    }

// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
    for (int i =0; i<numOfAccounts; i++) {
        if (accountNum == accounts[i].getAccountNum()  ) {
            accounts[i].deposit(amount);
            System.out.println("Amount deposited successfully");
            return;
        }
    }
    System.out.println("Account number not found.");
}

// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
    for (int i =0; i<numOfAccounts; i++) {
                if (accountNum == accounts[i].getAccountNum()  ) {
                    System.out.println(accounts[i].getAccountInfo());
                    return;
                }
            }
    System.out.println("Account number not found.");
}


public void printAccountInfo(int accountNum, int n) {
    for (int i =0; i<numOfAccounts; i++) {
                        if (accountNum == accounts[i].getAccountNum()  ) {
                            System.out.println(accounts[i].getAccountInfo());
                            return;
                        }
                    }
    System.out.println("Account number not found.");
    }

}





  static class BankAccount{

       private int accountNum;
       private String customerName;
       private double balance;
       private  static int noOfAccounts=0;

       public String getAccountInfo(){
           return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
       }


       public BankAccount(String abc, double xyz){
         customerName = abc;
         balance = xyz;
         noOfAccounts ++;
         accountNum = noOfAccounts;
       }

    public int getAccountNum(){
        return accountNum;
    }
    public void deposit(double amount){

        if (amount<=0) {
            System.out.println("Amount to be deposited should be positive");
        } else {
            balance = balance + amount;

        }
    }
    public void withdraw(double amount)
    {
        if (amount<=0){
             System.out.println("Amount to be withdrawn should be positive");
         }
        else
        {
            if (balance < amount) {
                System.out.println("Insufficient balance");
            } else {
                balance = balance - amount;

            }
        }
    }

}//end of class

The program runs fine, I just need to add these two options, and cannot get them to work properly, how would I go about doing this? Also, options 3 and 4 should not work if no accounts have been created yet. Thanks in advance.

Comparing 2-dimension arrays in VB Excel

I'm trying to compare two 2d arrays in VBA Excel.

Source:

1 2 3 4

4 5 6 2

3 3 4 4

Target:

4 5 3 2

1 2 3 4

3 7 7 5

Given the above two 2-d arrays which I will call source and target I want to compare each row from source with entire target and check if it exists in target. For Example row 1 from source (1 2 3 4) would be considered a match as it would found in target (at row 2). So I need to compare each row in target for a given row from source. If row in source does not exist in target then I will need to make note of this some how in order to mark as not existing in target.

Something on the lines of (not actual code just idea):

For i to ubound(srcArray)
    isFound = False
    For j To ubound(trgArray)
        If srcArray(i) = trgArray(j) Then
            isFound = True

    If Not isFound Then
        //make note of some sort

I know approach worked ok for single dim. array. But trying to do this for 2d arrays in some sort of loop in VB or other method. Not too familiar with VB in Excel. I would also like to look at each row as entire array if possible rather than comparing each element for each array individually.