samedi 25 avril 2015

Wrong order of elements in list in Java


I use following code to replace a list's elements. After replace elements aren't in the same order in the edges list, than in myCoordinates list. Is it maybe some randomness or what causes the change of its sequence?

for (int i = 0; i < edges.size(); i++) {
   int j = i*4;
   Edge edge = edges.get(i);
   edge.p1.x = myCoordinates.get(j);
   edge.p1.y = myCoordinates.get(j+1);
   edge.p2.x = myCoordinates.get(j+2);
   edge.p2.y = myCoordinates.get(j+3);
}


RegEx to divide string by +*-/ and keep delimiter?


How can I split a string into pieces every time a "/*-+" appears and keep the delimiter?

I've tried

@new = split( [/\+/]|[/\-/]|[/\//]|[/\*/], $start   );

and this doesn't even work to split in Perl. To keep the delimiter I believe I need something like this

/(?<=\.)/

But I'm not sure how that works.


Trouble with dynamic array of pure base class c++


I have this programming assignment for an intro c++ class. The program is supposed to use virtual functions to input, calculate and display quantities associated with various shapes. The Shape class must contain all pure virtual functions: display, getdimensions, area, perimeter, and volume.

The program driver must allocate an array of 20 pointers to Shape then repeatedly fill the array with the objects entered.

My program is quitting when it gets to the display call. So I take this to mean that either my getDimensions or display functions are not working correctly. I've spent hours trying to sort it out and can't seem to find what exactly is wrong if anyone could point me in the right direction.

Here is my code:

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

const double PI=3.141592654;

class Shape
{
protected:
    double x, y;
public:
    Shape(): x(1.0),y(1.0){}
    Shape(double a, double b): x(a),y(b){}
    virtual void display()=0;
    virtual void getDimensions()=0;
    virtual double area()=0;
    virtual double perimeter()=0;
   virtual double volume()=0;
};

class Rectangle: public Shape
{
public:
    Rectangle():Shape(){}
    Rectangle(double a, double b):Shape(a,b){}
    void display();
    void getDimensions()
    {
        cout<<"Input for Rectangle - "
            <<"enter length and width: ";
        cin>>x>>y;
    }
    double area()
        {return x*y;}
    double perimeter()
        {return (2*x)+(2*y);}
    double volume()
        {return 0;}
};

class Circle: public Shape
{
private:
    double radius;
public:
    Circle(): radius(1.0){}
    Circle(double r): radius(r){}
    void display();
    void getDimensions()
    {
        cout<<"Input for Circle - enter radius: ";
        cin>>radius;
    }
    double area()
        {return PI*radius*radius;}
    double perimeter()
        {return 2*PI*radius;}
    double volume()
        {return 0;}
 };

class Triangle: public Shape
 {
private:
    double z;
public:
    Triangle():z(1.0), Shape(){}
    Triangle(double f, double g, double w):z(w), Shape(f,g){}
    void display();
    void getDimensions()
    {
        cout<<"Input for Triangle - "
            <<"enter side 1, side 2, side 3: ";
        cin>>x>>y>>z;
    }
    double area()
    {
        double half, underroot;
        half = perimeter()/2;
        underroot = half*(half-x)*(half-y)*(half-z);
        return sqrt(underroot);
    }
    double perimeter()
        {return x+y+z;}
    double volume()
        {return 0;}
};

class Box: public Shape
{
private:
    double p;
public:
    Box():p(1.0), Shape(){}
    Box(double a, double b, double c): Shape(a,b), p(c){}
    void display();
    void getDimensions()
    {
        cout<<"Input for Box - "
            <<"enter length, width, and height: ";
        cin>>x>>y>>p;
    }
    double area()
        {return (2*x*y)+(2*x*p)+(2*y*p);}
    double perimeter()
        {return 0;}
    double volume()
        {return x*y*p;}
};

class Can: public Shape
{
public:
    Can():Shape(){}
    Can(double r, double h):Shape(r,h){}
    void display();
    void getDimensions()
    {
        cout<<"Input for Can - "
            <<"enter radius and height: ";
        cin>>x>>y;
    }
    double area()
    {
        double base;
        base = PI*x*x;
        return (2*PI*x*y)+(2*PI*x*x);
    }
    double perimeter()
        {return 0;}
    double volume()
        {return PI*x*x*y;}
};

class Cone: public Shape
{
public:
    Cone():Shape(){}
    Cone(double r, double h):Shape(r, h){}
    void display();
    void getDimensions()
    {
        cout<<"Input for Cone - "
            <<"enter radius and height: ";
        cin>>x>>y;
    }
    double area()
    {
        double underroot;
        underroot = sqrt((x*x)+(y*y));
        return (PI*x*x)+(PI*x*underroot);
    }
    double perimeter()
        {return 0;}
    double volume()
        {return (1/3)*PI*x*x*y;}
};

class Ball: public Shape
{
private:
    double radius;
public:
    Ball():radius(1.0){}
    Ball(double r):radius(r){}
    void display();
    void getDimensions()
    {
        cout<<"Input for Ball - "
            <<"enter radius: ";
        cin>>radius;
    }
    double area()
        {return 4*PI*radius*radius;}
    double perimeter()
        {return 0;}
    double volume()
        {return (4/3)*PI*radius*radius*radius;}
};

int main()
{
    int cnt=0, cnt2=0, choice;
    char yorn;

    Shape *sPtr[20];

    while(cnt<20)
    {
        cnt++;
        cnt2++;
        cout<<"\nIt is time to enter your shape selection"
            <<" and dimensions.\n"
            <<"Enter the number of the shape type: \n"
            <<"\t1 - Rectangle\n"
            <<"\t2 - Circle\n"
            <<"\t3 - Triangle\n"
            <<"\t4 - Box\n"
            <<"\t5 - Can\n"
            <<"\t6 - Cone\n"
            <<"\t7 - Ball\n"
            <<"=> ";
        cin>>choice;
        while (choice<1||choice>7)
        {
            cout<<"Invalid selection. Re-enter: \n"
                <<"=> ";
            cin>>choice;
        }
        switch (choice)
        {
        case 1:
        {
            sPtr[cnt]=new Rectangle;
            sPtr[cnt]->getDimensions();
            break;
        }
        case 2:
        {
            sPtr[cnt]=new Circle;
            sPtr[cnt]->getDimensions();
            break;
        }
        case 3:
        {
            sPtr[cnt] = new Triangle;
            sPtr[cnt]->getDimensions();
            break;
        }
        case 4:
        {
            sPtr[cnt] = new Box;
            sPtr[cnt]->getDimensions();
            break;
        }
        case 5:
        {
            sPtr[cnt] = new Can;
            sPtr[cnt]->getDimensions();
            break;
        }
        case 6:
        {
            sPtr[cnt] = new Cone;
            sPtr[cnt]->getDimensions();
            break;
        }
        case 7:
        {
            sPtr[cnt] = new Ball;
            sPtr[cnt]->getDimensions();
            break;
        }
        }

        cout<<"\nSelect another shape? (y or n): ";
        cin>>yorn;
        if(yorn=='n'||yorn=='N')
            cnt=20;
    }
    for(int i=0; i<cnt2; i++)
    {
        sPtr[i]->display();
    }
    return 0;
}

void Rectangle::display()
{
    cout<<"\nRectangle: "
        <<"\nDimensions: "
        <<"Length: "<<x<<"\nWidth: "<<y
        <<"\nArea: "<<area()
        <<"\nPerimeter: "<<perimeter();
}

void Circle::display()
{
    cout<<"\nCircle: "
        <<"\nDimensions: "
        <<"\nRadius: "<<radius
        <<"\nArea: "<<area()
        <<"\nPerimeter: "<<perimeter();
}

void Triangle::display()
{
    cout<<"\nTriangle: "
        <<"\nDimensions: "
        <<"\nSide 1: "<<x
        <<"\nSide 2: "<<y
        <<"\nSide 3: "<<z
        <<"\nArea: "<<area()
        <<"\nPerimeter: "<<perimeter();
}

void Box::display()
{
    cout<<"\nBox: "
        <<"\nDimensions: "
        <<"\nLength: "<<x
        <<"\nWidth: "<<y
        <<"\nHeight: "<<p
        <<"\nSurface area: "<<area()
        <<"\nVolume: "<<volume();
}

void Can::display()
{
    cout<<"\nBox: "
        <<"\nDimensions: "
        <<"\nRadius: "<<x
        <<"\nHeight: "<<y
        <<"\nSurface area: "<<area()
        <<"\nVolume: "<<volume();
}

void Cone::display()
{
    cout<<"\nCone: "
        <<"\nDimensions: "
        <<"\nRadius: "<<x
        <<"\nHeight: "<<y
        <<"\nSurface area: "<<area()
        <<"\nVolume: "<<volume();
}

void Ball::display()
{
    cout<<"\nBall: "
        <<"\nDimensions: "
        <<"\nRadius: "<<radius
        <<"\nSurface area: "<<area()
        <<"\nVolume: "<<volume();
}


C# array accessiblity


Is there a way to prevent reinitialization of an array? (to force specific length)

example initial:

int[] array = new int[3]{0,0,0};

usage:

array = new int[5]{1,2,3,4,5};

The above usage will reinitialize the array with length of 5.

The array will always have 3 elements, but the values of the elements will always be changing.

I am trying to avoid doing the following to assign it's values:

array[0] = 1;
array[1] = 2;
array[2] = 3;


Windows phone 8 play sound according to bit array


I have a textbox in my app, and for example it contains: "Hello World!". I have a wav file that represents a beep(1 ms). In accordance to the "Hello World" bits representation I want to play the beeps in this manner: play beep if '1' or wait for 1 ms(silence). What is the best way to achive this? Thanks. (I develop in C#)


php - get top repetitions from an array


I have an array which is of the form

array(23) { [0]=> string(13) "Richmond Town" [1]=> string(11) "Tasker Town" [2]=> string(18) "Vittal Mallya Road" [3]=> string(15) "Shanthala Nagar" [4]=> string(19) "Sampangi Rama Nagar" [5]=> string(9) "Jayamahal" [6]=> string(15) "Shanthala Nagar" [7]=> string(19) "Sampangi Rama Nagar" [8]=> string(15) "Shanthala Nagar" [9]=> string(15) "Shanthala Nagar" [10]=> string(11) "Nehru Nagar" [11]=> string(13) "Richmond Town" [12]=> string(21) "Koramangala 1st Block" [13]=> string(14) "Cleveland Town" [14]=> string(22) "Yellappa Chetty Layout" [15]=> string(13) "HAL 2nd Stage" [16]=> string(15) "Shanthala Nagar" [17]=> string(11) "Koramangala" [18]=> string(11) "Koramangala" [19]=> string(19) "Koramangala 6 Block" [20]=> string(11) "5th A Block" [21]=> string(15) "Pulikeshi Nagar" [22]=> string(16) "Cambridge Layout" } 

Now I want the top 5 repetitions from this array. Please help me out.


Control array in runtime C#


I need an array of Timer component with unknown size. New Timer may be added or removed existing.

Timer[] timers= new Timer[];

Above line shows must have array size.

Any help?


How to apply function by groups in array in R?


I have a 3d array with latitude, longitude and datetime (Year_Month_Day_Hour). Which is the best way in R to apply a function over the array by groups (in this case by years or month or days)? The result should be an array with the mean values. The 3 dimension is than the year, month or day.

str(data)
 num [1:7, 1:7, 1:5] 977 994 1010 1020 1026 ...
 - attr(*, "dimnames")=List of 3
  ..$ : chr [1:7] "60" "57.5" "55" "52.5" ...
  ..$ : chr [1:7] "-30" "-27.5" "-25" "-22.5" ...
  ..$ : chr [1:5] "2014_10_01_00" "2014_10_01_06" "2014_10_01_12" "2014_10_01_18" ...

Example (truncated):

dput(data) structure(c(977.2, 994.4, 1009.8, 1020.1, 1026.4, 1029.4, 1029.2, 
978.7, 995.7, 1010.2, 1020.5, 1026.5, 1028.8, 1028.3, 982, 997.5, 
1011.3, 1021.2, 1026.1, 1027.4, 1027.1, 986.2, 999.9, 1013, 1021.7, 
1025.1, 1025.7, 1026, 990.6, 1002.7, 1014.5, 1021.3, 1023.9, 
1024.7, 1025.6, 995.1, 1005.7, 1015.2, 1019.9, 1022.6, 1024.5, 
1025.9, 999.1, 1008, 1015.1, 1018.6, 1021.8, 1024.5, 1026.6, 
982.1, 998.9, 1011.8, 1020.1, 1025.5, 1028.4, 1028.8, 981.9, 
999.3, 1012.7, 1021.2, 1026.4, 1028.8, 1029, 983.9, 1000.2, 1013.5, 
1022.1, 1027, 1028.9, 1028.9, 987.1, 1001.8, 1014.6, 1022.7, 
1027.3, 1028.6, 1028.2, 990.9, 1004.1, 1016.1, 1023.3, 1027.2, 
1027.9, 1027.4, 995.1, 1006.9, 1017.8, 1023.8, 1026.8, 1027, 
1026.9, 999.5, 1010.1, 1019.1, 1023.8, 1025.9, 1026.1, 1026.9, 
990.3, 1002.3, 1010.9, 1018.3, 1024, 1027.6, 1028.6, 990.6, 1004.1, 
1013.2, 1020.8, 1026.2, 1029.3, 1029.8, 992.1, 1005.5, 1015.2, 
1023, 1028, 1030.4, 1030.5, 994.5, 1007, 1017.2, 1024.7, 1029.4, 
1031, 1030.3, 997.4, 1008.8, 1019, 1025.7, 1030, 1031, 1029.8, 
1000.1, 1010.9, 1020.9, 1026.5, 1030, 1030.6, 1029.5, 1002.9, 
1013.3, 1022.6, 1027.2, 1029.7, 1029.7, 1029.2, 993.6, 997.5, 
1001.3, 1007.4, 1015.5, 1022.7, 1026.4, 996.1, 1001.1, 1005.8, 
1012.7, 1020.1, 1025.6, 1027.9, 998.4, 1004.5, 1010.4, 1017.6, 
1023.8, 1027.6, 1029.1, 1000.2, 1007.3, 1014.4, 1021.5, 1026.4, 
1029, 1029.7, 1002, 1010, 1017.8, 1024.3, 1028.4, 1029.9, 1029.6, 
1004.3, 1012.9, 1020.7, 1026.3, 1029.7, 1030.2, 1029.3, 1006.9, 
1016, 1023.2, 1027.7, 1030.3, 1029.7, 1028.6, 987.9, 989.6, 995.1, 
1002.9, 1010.8, 1018.9, 1025.1, 989.8, 990, 995.1, 1004.7, 1013.9, 
1021.8, 1026.8, 993.1, 992.6, 998.1, 1008.8, 1018, 1024.6, 1028.3, 
996.9, 997.3, 1003.9, 1014, 1021.9, 1026.8, 1029.1, 1000.3, 1003.1, 
1010.5, 1019, 1025.2, 1028.5, 1029.6, 1003.6, 1008.7, 1016.4, 
1023.1, 1027.8, 1029.8, 1029.9, 1007.3, 1013.7, 1020.8, 1026.3, 
1029.8, 1030.2, 1029.6), .Dim = c(7L, 7L, 5L), .Dimnames = list(
c("60", "57.5", "55", "52.5", "50", "47.5", "45"), c("-30", 
"-27.5", "-25", "-22.5", "-20", "-17.5", "-15"), c("2014_10_01_00", 
"2014_10_01_06", "2014_10_01_12", "2014_10_01_18", "2014_10_02_00"
)))

SOLUTION:

group <- as.factor(as.Date(dimnames(data)[[3]],format="%Y_%m_%d"))

aperm(apply(data,c(1,2), by, group, mean),c(2,3,1))


Querying a Postgres array of integers in Rails


my model has a pg array which I use to store integers

Querying using the methods I found from other questions yields errors or gives empty results

MyModel.where("? = ANY (myarray)", 42)

gives

PG::UndefinedFunction: ERROR:  operator does not exist: integer = text

and

 MyModel.where("myarray @> '{?}'", 42)

gives an empty results, yet I do have a model with 42 as one of the ints in the array

#<MyModel:0x007f9a77dd5608> {
                :id => 170,
      :myarray => [
    [0] 42,
    [1] 43,
    [2] 58,
    [3] 61,
    [4] 63
  ]

Is there a special way to query integers(or floats) within a postgres array in Rails?

the migration

class AddMyarrayToMyModel < ActiveRecord::Migration
  def change
    add_column :my_models, :myarray, :integer, array: true, default: []
    add_index  :my_models, :myarray, using: 'gin'
  end
end

and schema

t.integer  "myarray",                 default: [],              array: true


Create array of objects using distinct values from two arrays with javascript


My question is a little more involved. I have two arrays of data:

var arr = [
  {title: "foo", namesIndices: [0,1]},
  {title: "bar", namesIndices: [2]},
  {title: "baz", namesIndices: [3,4]}
];

var names = [
  {name: "John", website: "someUrl"},
  {name: "Mike", website: "someUrl"},
  {name: "Jane", website: "someUrl"},
  {name: "Ali", website: "someUrl"},
  {name: "Robert", website: "someUrl"}
];

Where namesIndices will reference an index in the names array that will correspond with that person with their title. In order to match the person's name and website with the correct title to make this array:

var person = [
  {name: "John", title: "foo", website: "someUrl"},
  {name: "Mike", title: "foo", website: "someUrl"},
  {name: "Jane", title: "bar", website: "someUrl"},
  {name: "Ali", title: "baz", website: "someUrl"},
  {name: "Robert", title: "baz", website: "someUrl"}
];

I have had to loop through the first array, then loop through arr.namesIndices:

var person = [];
for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr[i].namesIndices.length; j++) {
        var personObj = {};
        personObj.title= arr[i].title;
        personObj.name = names[arr[i].namesIndices[j]].name;
        personObj.website= names[arr[i].namesIndices[j]].website;
        person.push(personObj);
     }
 }

Is there a way to do this without nested loops?


Inputting 2 txt files, data input into equation, then output in an array


a)Read “distance1.txt” and “distance2.txt” – These are 15 x 10 matrices.

b) Use (1/sqrt(2*3.14))(exp(-(xx)/2)) on each entry of these two matrices. (x is the individual entry from the matrix)

c) Generate “distribution1.txt” and “distribution2.txt” based on the result of the previous step – the dimension has to be 15 x 10 for each matrix in the individual txt file.

d) Your file should generate console output (on the screen) and file outputs (txt files).

e) Use the followings – Array, File Reading, File Writing, Class, Constructor, and Destructor.


ArithmeticException division by zero... how to fix this method?


The purpose of this method is to iterate through a 2D array of integers called grid[][], and translate the integers based on the maximum and minimum values into a smaller range between 100 and 250 (the original minimum value becomes 100, the original maximum value becomes 250, and everything in between is calculated respectively). When this method is called, division by zero ArithmeticException occurs.

Clearly I'm making some logic mistakes here... I just don't see the fix. Can anyone help?

public int greenValues(int arrayVal) {  

    int max = 0;
    int min = 0;
    int colorValue = 0;
    int temp;

    for (int i = 0; i < grid.length; i++) {  // finds maximum and minimum numbers in file 
        for (int j = 0; j < grid.length; j++) {  
            if (max < grid[i][j]) {
                max = grid[i][j];   
            }
            if (min > grid[i][j]) { 
                min = grid[i][j];
            }
        }
    }

        int arrayRange = (max-min); // arrayVal, arrayRange, and max and min are 0
        temp = (((arrayVal-min) * COLOR_RANGE) / arrayRange) + 100;    // map values to range of 100 - 250
        colorValue = temp;
        return colorValue;
    }


array_multisort not working PHP


Please i need your help. I want to sort the array into an ascending order by priority time.

Heres is the array

Array
(
    [process] => Array
        (
            [0] => Array
                (
                    [name] => p1
                    [burst_time] => 2
                    [priority_time] => 3
                )

            [1] => Array
                (
                    [name] => p2
                    [burst_time] => 2
                    [priority_time] => 4
                )

            [2] => Array
                (
                    [name] => p3
                    [burst_time] => 2
                    [priority_time] => 1
                )

        )

)

I tried this code but doesn't work for me. Thank you in advanced :)

foreach ($data as $key => $row) {
    $mid[$key]  = $row;
}
array_multisort($mid, SORT_ASC, $data);


C: Reading multiple areas into an array and finding the largest value


I'm attempting to find the largest value in an array. I'm given a set of areas (the input), which for now is:

4.5
19.59
1.92

These areas need to be read into an array using scanf and then from there I need to find the largest value (area) in that array. It should also be known that there can only be maximum of 100 areas that can be read into the array. So later on I may need to read in 5 or 20 or 99 etc... into the array.

If anybody could give me a hand it'd be much appreciated, I'm new to programming and don't really know where to begin.


I have a fixed point matlab code and it needs to be converted to verilog and below is the code


I have a fixed point matlab code and it needs to be converted to verilog and below is the matlab code

yfftshift has (5000x0) and y2shape has (100x50)

rows=100;

colms=50;

r=1; for m=0:colms-1

for n=0:rows-1

  y2shape(n+1,m+1)=yfftshift(r,1);

  r=r+1;

end

end

How to create memories in verilog and call it inside in for loop is making me difficult.Kindly help me out


IDL - Struct of Arrays to Array of Structs


From a FITS-Table I read data, and get a Struct containing the table, where each tag represents a column.

Is there a way to reformat the Struct of Arrays to an Array of Structs? So that one Struct in the Array represents a Row?


Add missing years and corresponding values into an array


I've been messing around with the JBChartView library and it seems really good for charting. It's easy enough to use but i'm having some problems getting my data in a format that i need for a particular chart.

The user can enter a value and corresponding year. This is saved using core data. The data could look like as follows:

Year: 0 Value: 100 Year:2 Value 200 Year 3 Value 150

I would create 2 arrays, 1 for the year number and another for the value. in this case though, I would get 3 bars. What i'd like is a bar with value 0 for Year 1.

I think the best way to approach this would be to look through the Year array, check to see if the first value is 0, then check if every consecutive year value is +1. If not, add 1 to the previous year and insert a value of 0 into the values array at the same index position.

I would like to know if this is the best approach and if I could get some help doing the comparison.

Thanks


PHP PDO MYSQL - Get Array comma separated from fetchAll


I'm really stuck in this.

I need a result like (138,139,140,141,142,143,144,145), but I'm getting just a (Array,Array,Array,Array,Array,Array,Array,Array)...

My code is:

<?php
    try {
                        $dbconn = DBCONNECTION();

                        $sql = "SELECT `product_category_id`, `product_category_parent_id`, `date_available`, `status` 
                                FROM `product_category` 
                                WHERE `product_category_parent_id` = '" . $_GET['cat'] . "' 
                                AND `date_available` <= NOW() 
                                AND `status` = '1' 
                                ORDER BY `product_category_id` ASC";

                        $stmt = $dbconn -> prepare($sql);
                        $stmt -> execute();
                        $array = $stmt -> fetchAll(PDO::FETCH_ASSOC);

                        foreach($array as $row) {
                            $category[] = array($row['product_category_id']);
                        }

                        $subcategory = implode(',', $category);
                        echo $subcategory;
    }
?>

Can you please help me?

Thanks a lot!


unusual syntax for accessing array elements? [duplicate]


This question already has an answer here:

I know that when we![enter image description here][1] access an element in an array we use [] for example :

    int arr[2][3]={1,2,3,4,5,6}; 
    arr[1][2];//last element

but i found out that i can use 2[1[arr]] instead of arr[1][2] so how the compile know this trick ?! is this a way as the reduction function?

thanks.


Dividing values from one array by values from a separate array


I am trying to take values from separate arrays and perform divisional math. I have created a method to perform the division, but I keep getting the "bad operand..." error. I have searched and searched, but cannot find resolution. I need to be able to take the values from tripMiles and divide that by the values from gallons.

import java.util.Scanner;

public class Week6Challenge {

public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int count = 0;
//double miles = 0, gallons = 0;
//Arrays
String[] tripName;
tripName = new String[11];
double[] tripMiles;
tripMiles = new double[11];
double[] tripMPG;
tripMPG = new double [11];
double[] gallons;
gallons = new double [11];

//double miles = 0, gallons = 0;


while (count <= 9){//start while
    System.out.println("Enter a description of this trip");
    tripName[count] = scan.next();

    System.out.println("How many miles did you drive?");
    tripMiles[count] = scan.nextDouble();

    System.out.println("How many gallons of gas did you use on this trip");
    gallons[count] = scan.nextDouble();
    count++;
        }//end while

        tripMPG[count] = answer(tripMiles, gallons);

System.out.println("Trip Name \t Miles Traveled \t MPG");
int k = 0;
for(k = 0; k < 10; k++){
System.out.println(tripName[k]+ "\t\t" + tripMiles[k] + "\t\t\t" + tripMPG[k]);

    }
}
 public static double answer(double[] num1, double[] num2){
 return (num1/num2);
    } 

}


How to find pattern groups in boolean array?


Given a 2D array of Boolean values I want to find all patterns that consist of at least 2 columns and at least 2 rows. The problem is somewhat close to finding cliques in a graph.

In the example below green cells represent "true" bits, greys are "false". Pattern 1 contains cols 1,3,4 and 5 and rows 1 and 2. Pattern 2 contains only columns 2 and 4, and rows 2,3,4.

example

Business idea behind this is finding similarity patterns among various groups of social network users. In real world number of rows can go up to 3E7, and the number of columns up to 300.

Can't really figure out a solution other than brute force matching.

Please advice the proper name of the problem, so I could read more, or advice an elegant solution.


creating an array from database


I'm using a array to get a range between 1011-2371 but I'didnt need all digits. It's a long list thats why I import the CSV to the database.

I want to create a array from a database table. But I can't get it.

Here's a rough mockup of the old php:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="text" placeholder="1234AB" name="postcode" />
    <input type="submit" value="verstuur" />
</form>
<?php

if($_SERVER['REQUEST_METHOD'] == "POST") {
    $postcode = range(1011,2371);
    if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
        if(in_array($_POST['postcode'],$postcode)) {
            echo 'FreshFoods is beschikbaar bij jou in de buurt.';
        } else {
            echo  'FreshFoods is nog niet beschikbaar bij u in de buurt.';
        }
    } else {
        echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
    }
}
?>

and this is what I try do get the array from the database:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="text" placeholder="1234AB" name="postcode" />
    <input type="submit" value="verstuur" />
</form>
<?php
require_once 'db_config.php'; 

if($_SERVER['REQUEST_METHOD'] == "POST") {
    $postcode = array();
    $result = mysql_query("SELECT postcode FROM postcode_check");

    if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
        if(in_array($_POST['postcode'],$postcode)) {
            echo 'FreshFoods is beschikbaar bij jou in de buurt.';
        } else {
            echo  'FreshFoods is nog niet beschikbaar bij u in de buurt.';
        }
    } else {
        echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
    }
}
?>

the db_config.php file looks like:

<?php 
$db = array ( 
    'host' => 'localhost', 
    'user' => 'root', 
    'pass' => 'root', 
    'dbname' => 'testzip' 
); 

if(!mysql_connect($db['host'], $db['user'], $db['pass'])) 
{ 
    trigger_error('Fout bij verbinden: '.mysql_error()); 
} 
elseif(!mysql_select_db($db['dbname'])) 
{ 
    trigger_error('Fout bij selecteren database: '.mysql_error()); 
} 
else 
{ 
    $sql = "SET SESSION sql_mode = 'ANSI,ONLY_FULL_GROUP_BY'"; 
    if(!mysql_query($sql)) 
    { 
        trigger_error('MySQL in ANSI niet mogelijk'); 
    } 
} 
?>


How could I call a function as a pointer from an array in c++?


So Im using an array of structs like so:

struct node
{
  char* name;
  int   value;
};

node *nodeArray = new node*[50];

Im trying to call a function from the array so I can search through the elements like so:

struct node* newNode;
newNode = nodeArray->find(name);

if name was a char* so it returns a pointer to the node in the array once the name is found.

How would I go about creating a class to call a find function from the array?


how do you change arrays?


help! im trying to replace 'a' and 'e' with ' ' in my array but it keeps replacing all of the array instead.

    for(int x = 0; x < array_length); x++)
    { if(city_name[x] == 'a' || 'e')
      city_name[x] = " ";}


How do I add values to class objects then put them in an array?


I'm trying to embed queries into the variables in the class.
Like so:

    class FooBar{
        public $bar;
    }


    $result = array();

    $db = mysqli_connect("127.0.0.1", "foo", "foo", "Farm");
    $sql = "SELECT * FROM `Lot`;";
    $result = mysqli_query($db, $sql);

    while($row = mysqli_fetch_assoc($result)){
        $foo = new FooBar;            
        $foo->$bar = $row["cow"];

        array_push($result, $foo);
    }

But when I print the array using print_r($result), I'm just getting this as an output:

Array( )

I was hoping to see the objects stored in the array.

Where did I go wrong? What should I be doing?


Comparing two byte arrays guarding against timing attacks


I want to write a method to compare two byte arrays, but I do not want to use these solutions because I want the method to be resistant to timing attacks. My method essentially looks like:

static bool AreEqual(byte[] a1, byte[] a2)
{
    bool result = true;
    for (int i = 0; i < a1.Length; ++i)
    {
        if (a1[i] != a2[i])
            result = false;
    }
    return result;
}

(with the assumption that a1 and a2 have the same length).

My concern is that a sufficiently smart just-in-time compiler might optimize this by returning early if result is ever set to false.

I have checked the JITted assembly code produced by .NET 4.0.30319, and it does not:

                         ; `bool result = true;'
00e000d1 bb01000000      mov     ebx,1
                         ; `int i = 0;'
00e000d6 33f6            xor     esi,esi
                         ; store `a1.Length' in eax and at dword ptr [ebp-10h]
00e000d8 8b4104          mov     eax,dword ptr [ecx+4]
00e000db 8945f0          mov     dword ptr [ebp-10h],eax
                         ; if `a1.Length' is 0, then jump to `return result;'
00e000de 85c0            test    eax,eax
00e000e0 7e18            jle     00e000fa
                         ; `if (a1[i] != a2[i])'
00e000e2 0fb6443108      movzx   eax,byte ptr [ecx+esi+8]
00e000e7 3b7704          cmp     esi,dword ptr [edi+4]
00e000ea 7316            jae     00e00102
00e000ec 3a443708        cmp     al,byte ptr [edi+esi+8]
00e000f0 7402            je      00e000f4
                         ; `result = false;'
00e000f2 33db            xor     ebx,ebx
                         ; `++i'
00e000f4 46              inc     esi
                         ; check: `a1.Length > i'
00e000f5 3975f0          cmp     dword ptr [ebp-10h],esi
00e000f8 7fe8            jg      00e000e2
                         ; `return result;'
00e000fa 8bc3            mov     eax,ebx
00e000fc 59              pop     ecx
00e000fd 5b              pop     ebx
00e000fe 5e              pop     esi
00e000ff 5f              pop     edi
00e00100 5d              pop     ebp
00e00101 c3              ret
00e00102 e81f7a1772      call    clr!CreateHistoryReader+0x8e97c (72f77b26)
00e00107 cc              int     3
00e00108 0000            add     byte ptr [eax],al
00e0010a 0000            add     byte ptr [eax],al
00e0010c 0000            add     byte ptr [eax],al
00e0010e 0000            add     byte ptr [eax],al
...

However, I am thinking that this could change in the future.

Is there a way to prevent the JIT compiler from optimizing this method? Alternatively, is there a library function that I can use that specifically checks two byte arrays for equality, but resistant to timing attacks?


array to create a linked-list


typedef struct num{
    int num;
    int pre;
    struct num* next;
}Num;

Num list[10]=
{{3,4},{2,1},{6,5},{7,2},{4,3},{3,9},{5,6},{1,3},{8,4},{10,0}
};

#include <stdio.h>

int main(){

    int cnt;
    Num *ptr = NULL;

    Num tempTwo;
    for (cnt = 0; cnt < 10; cnt++) {
        tempTwo = list[cnt]; 
        ptr->next = &tempTwo; //Error
        ptr = ptr->next;
    }

    for (cnt = 0; cnt<10; cnt++) {
        printf("num: %d, pre: %d\n",ptr->num,ptr->pre);
        ptr = ptr->next;
    }
}

I want to make linked-list with array 'list' using pointer ptr.
Error: Bad access
What can I do to solve this problem?


I have tried writing the logic for the below partition algorithm in java but could not succeed


Could anyone please help me.

  • Partition Algorithm:

-pivot = pick a random element out of the array A -swap the pivot with the last element of A

small_count = 0 for each element x of array A except the last if x < pivot swap x with A[small_count] add 1 to small_count

swap A[small_count] with the last element of A

Example Run:

Array after picking 4 as pivot and swapping with last pivot = 4, ^ indicates current array element in for loop.

7 6 5 2 3 8 1 9 4 small_count = 0 ^ next element

7 6 5 2 3 8 1 9 4 small_count = 0 ^ next element

7 6 5 2 3 8 1 9 4 small_count = 0 ^ next element

7 6 5 2 3 8 1 9 4 small_count = 0 ^ swap A[0] with 2, add 1 to small_count, next element

2 6 5 7 3 8 1 9 4 small_count = 1 ^ swap A[1] with 3, add 1 to small_count, next element

2 3 5 7 6 8 1 9 4 small_count = 2 ^ next element

2 3 5 7 6 8 1 9 4 small_count = 2 ^ swap A[2] with 1, add 1 to small_count,

next element 2 3 1 7 6 8 5 9 4 small_count = 3 ^ next element 2 3 1 7 6 8 5 9 4 small_count = 3 ^ swap A[small_count] with last element

2 3 1 4 6 8 5 9 7 small_count = 3

Now elements 0 to small_count - 1 are < pivot elements from small_count on are >= pivot


Querying any member of a Postgres array type in Rails 4


Everywhere I looked there were 2 examples

either

Book.where("'history' = ANY (subjects)")

to query a book with a specific subject in the subject array

or

 Book.where("subjects @> ?", '{'history', 'drama'}')

to query books that the subjects array has both history and drama

How do I query for books that has either history or drama or both?



According to the Microsoft documentation, calling Clear() on a List is an O(n) operation. I'm guessing this is because if the list were to hold references, it would need to null them. I was wondering if Clear() is still an O(n) operation if the list has value types, since the capacity is not changed. Shouldn't it be enough to reset the index pointer and count?

I'm asking this because in a current application we're using lists that get cleared hundreds of thousands of times in a very short time span, and wanted to know if there could be a different implementation that makes it faster.


Order of size specifiers in unpacked ports


I was wondering what is the difference in declaring an unpacked port this way:

input logic a[10];

or this way:

input logic a[9:0];

I could not find the difference documented anywhere, I only know by experience that connecting two ports with these "different?" types would not cause any warning (tested in both vcs and modelsim) but the order of data might be reversed.


Java - Finding Duplicates in Array and printing them only Once


I am trying to loop through my array and find all the numbers that are repeating more than once:

E.G: if there is 1 1 2 3 4

It should print saying "1 repeats more than once"

Here is my code and so far what I have tried, however it prints all duplicates and keep going, if there is 4 4 4 4 3 6 5 6 9, it will print all the 4's but i dont want that:

class average {

 public static void main(String[] args) throws IOException {

    int numOfLines = 0;
    int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
    int[] buffer;

    File myFile = new File("num.txt");
    Scanner Scan = new Scanner(myFile);

    while(Scan.hasNextLine()) {
        Scan.nextLine();
        numOfLines++;
    }
    Scan.close();
    Scan = new Scanner(myFile);

    System.out.println("Number Of Lines: " + numOfLines);

    buffer = new int[numOfLines];

    for(int i=0; i<numOfLines; i++) {
        buffer[i] = Scan.nextInt();
    }
    Scan.close();
    Scan = new Scanner(myFile);

    for(int i=0; i<buffer.length; i++) {
        sum = sum+i;
        mean = sum/numOfLines;
    }
    System.out.println("Sum: " + sum);
    System.out.println("Mean: " + mean);

    for(int i=0; i<buffer.length; i++) {
        for(int k=i+1; k<buffer.length; k++) {
            if(buffer[k] == buffer[i]) {
                System.out.println(buffer[k]);
            }
        }
    }


Populating ViewBased table from data in 6 different NSMutable arrays


I have 6 different NSMutable arrays [(Arr(A); Arr(B); etc.] each of which represents data for one cell of a row in the table. The array is essentially the key representation. They are built in a prior classes, passed to the current class and have exactly the same number of string objects (63) in each. The table is essential a data representation of

Questions:

  1. Must I build a NSDictionary with 'keys' and 'objects'. How do I build thatDictionary. I have tried various methods stepping through a count loop with no success. I can to find a method for inserting objects for specific keys.

  2. Can I load the table directly from the various arrays without a ViewController. I have the table and id's laid out but I have not been able to add a ViewController to this class - I only have 'Files Owner'. If this is easiest how can I do that.

  3. If needed, how do I take elements of the 6 arrays in order as a comma delimited string in another array that becomes the input to a row of of the table and therefore parsed into the table.

No code to offer because all my attempts w/code have been unsuccessful.

NEED SOME SPECIFIC DIRECTION HERE.

.h

     //  ReportsOutput.h
        //  Stamp Collection
        //  Created by Terry Lengel on 4/20/15.
        //  Copyright (c) 2015 Terry Lengel. All rights reserved.

        #import <Cocoa/Cocoa.h>
        #import <Foundation/Foundation.h>
        #import "ReportsClass.h"

        @interface ReportsOutput : NSWindowController <NSMenuDelegate,NSTableViewDataSource,NSTableViewDelegate,NSApplicationDelegate>{


        // variable and outlet for the table

            IBOutlet NSTableView *rptTable;

        }

        // data element sources

        @property(nonatomic,strong) NSMutableArray *tblYrScott;
        @property(nonatomic,strong) NSMutableArray *tblYrExt;
        @property(nonatomic,strong) NSMutableArray *tblYrYear;
        @property(nonatomic,strong) NSMutableArray *tblYrType;
        @property(nonatomic,strong) NSMutableArray *tblYrPrice;
        @property(nonatomic,strong) NSMutableArray *tblYrDescription;

        // the Display data source array for the table

        @property(strong) NSMutableArray *rptData;

        #pragma mark - Method Declarations

        -(BOOL)conditionData;

        -(NSDictionary *)makeDictionaryRecord:(NSString*)scott withInfo:(NSString*)ext withInfo:(NSString*)year withInfo:(NSString*)type withInfo:(NSString*)price withInfo:(NSString*)Description;

        @end

    .m

        //  ReportsOutput.m
        //  Stamp Collection
        //  Created by Terry Lengel on 4/20/15.
        //  Copyright (c) 2015 Terry Lengel. All rights reserved.

        #import "ReportsOutput.h"
        #import "ReportsClass.h"

        @interface ReportsOutput ()

        @end

        @implementation ReportsOutput

        @synthesize tblYrScott;
        @synthesize tblYrExt;
        @synthesize tblYrType;
        @synthesize tblYrPrice;
        @synthesize tblYrYear;
        @synthesize tblYrDescription;

        @synthesize rptData;

        -(id)initWithWindow:(NSWindow *)window{
            self = [super initWithWindow:window];
            if (self){
                // initialize code here
            }
            return self;

        }


        -(void)windowDidLoad {
            [super windowDidLoad];

            // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
        }

        -(void)applicationDidFinishLaunching:(NSNotification *)notification{

            //Insert code here to initialize your application
        }

        //  Terminate the app by using the RED button:

        -(BOOL)applicationShouldTerminateAfterLastWindowClosed:
        (NSApplication *)sender{

            return YES;

        }

        -(void)awakeFromNib{

            if (self.conditionData == YES){

                [rptTable reloadData];
            }

        }

        -(BOOL)windowShouldClose:(id)sender{
            return YES;
        }

        -(void)performClose:(id)sender{
            [self close];
        }

        #pragma mark - Table View Data Source

        -(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{

            return rptData.count;

        }

        -(NSView *) tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{

            NSTableCellView *scott = [tableView makeViewWithIdentifier:@"Scott" owner:self];

            scott.textField.stringValue = [self.rptData objectAtIndex:row];

            return scott;


        }

        // request for sorting

        -(void) tableView:(NSTableView *)tableView sortDescriptorsDidChange:(NSArray *)oldDescriptors{

            // table view received sort request
            //sort the data, then reload the tableView data:

            [rptData sortUsingDescriptors:[rptTable sortDescriptors]];

            [rptTable reloadData];

        }

        -(BOOL)conditionData{

            BOOL conditionData = NO;

            NSString *rPrice;
            NSString *rExt;
            NSString *rYear;
            NSString *rType;
            NSString *rDescription;


            for (int b=0; b<[tblYrScott count]; ++b){

                //condition source data to remove any null appearences

                rExt = [tblYrExt objectAtIndex:b];
                if (rExt == (id)[NSNull null] || rExt.length == 0 ){
                    rExt = @"None";
                }else if ([rExt isEqualToString:@" "]){
                    rExt = @"None";
                }else
                    rExt = [tblYrExt objectAtIndex:b];

                rYear = [tblYrYear objectAtIndex:b];
                if (rYear == (id)[NSNull null] || rYear.length == 0 ){
                    rYear = @" ";
                }else
                    rYear = [tblYrYear objectAtIndex:b];

                rType = [tblYrType objectAtIndex:b];
                if (rType == (id)[NSNull null] || rType.length == 0 ){
                    rType = @" ";
                }else
                    rType = [tblYrType objectAtIndex:b];

                rPrice = [tblYrPrice objectAtIndex:b];
                if (rPrice == (id)[NSNull null] || rPrice.length == 0 ){
                    rPrice = @"n/r";
                }else
                    rPrice = [tblYrPrice objectAtIndex:b];

                rDescription = [tblYrDescription objectAtIndex:b];
                if (rDescription == (id)[NSNull null] || rDescription.length == 0 ){
                    rDescription = @" ";
                }else
                    rDescription = [tblYrDescription objectAtIndex:b];

                NSDictionary *rptData = @{@"Scott":[tblYrScott objectAtIndex:b],@"Ext":rExt,@"Year":rYear,@"Type":rType,@"Price":rPrice,@"Description":rDescription};

            }

            //[rptTable reloadData];

            return conditionData = YES;
        }


        -(NSDictionary*) makeDictionaryRecord:(NSString *)scott withInfo: (NSString *)ext withInfo: (NSString *)year withInfo: (NSString *)type withInfo: (NSString *)price withInfo: (NSString *)description{

            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:scott,@"Scott",ext,@"Ext",year,@"Year",type,@"Type",price,@"Price",description,@"Description", nil];

           return dict;

        }

        @end

Data Sample:

2015-04-25 12:20:49.251 StampsProjectDev[2981:591183]  rptData = {
    Description = "Lunar New Year - Horse";
    Ext = None;
    Price = "n/r";
    Scott = 4846;
    Type = C;
    Year = 2014;
}
2015-04-25 12:20:49.252 StampsProjectDev[2981:591183]  rptData = {
    Description = "Jimi Hendrix";
    Ext = None;
    Price = "n/r";
    Scott = 4880;
    Type = C;
    Year = 2014;
}
2015-04-25 12:20:49.252 StampsProjectDev[2981:591183]  rptData = {
    Description = "Charlton Heston";
    Ext = None;
    Price = "n/r";
    Scott = 4892;
    Type = C;
    Year = 2014;
}
2015-04-25 12:20:49.252 StampsProjectDev[2981:591183]  rptData = {
    Description = "Janice Joplin";
    Ext = None;
    Price = "n/r";
    Scott = 4916;
    Type = C;
    Year = 2014;
}
2015-04-25 12:20:49.252 StampsProjectDev[2981:591183]  rptData = {
    Description = "Ralph Ellison";
    Ext = None;
    Price = "n/r";
    Scott = 4866;
    Type = C;
    Year = 2014;
}


issue with php shuffle multidimensional array


hi there I declare an array variable and fill it:

foreach($urls as $url) 
{
    $webs[] = array( 'name' => $url['name'],
                     'url' => $url['link']);
}

it will fill something like this:

$webs: ((name:cnn,'link:cnn.com/1')
       (name:cnn,'link:cnn.com/1')
       (name:cnn,'link:cnn.com/1')
       (name:bbc,'link:bbc.com/1')
       (name:bbc,'link:bbc.com/1')
       (name:bbc,'link:bbc.com/1'))

Now I want to print it:

foreach($webs as $web) 
{
        echo "<br/>".$web['name'].':'.$web['url'];
}

result:

cnn: cnn.com/1
cnn: cnn.com/2
cnn: cnn.com/3
bbc: bbc.com/1
bbc: bbc.com/2
bbc: bbc.com/3

But I do not want it. I want print all result but randomlay something like this:

bbc: bbc.com/1
cnn: cnn.com/1
bbc: bbc.com/3
cnn: cnn.com/3
cnn: cnn.com/2
cnn: cnn.com/3
bbc: bbc.com/2

I try

$webs = shuffle($webs);
foreach($webs as $web) 
    {
            echo "<br/>".$web['name'].':'.$web['url'];
    }

but no success with this error:

Warning: Invalid argument supplied for foreach() 

Note: In my real code, $url['name'] is an another array.


How I can fix this array


Good morning, I was trying to fill a dynamic vector but when I print the input data i get something like this:

input: 1,5,3,4,2
output: 0,1,5,3,4

Could somebody help me I can't fix it I've been trying a lot and can't get it. I'll apreciatte so much (sorry for the english)

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

#define MAX_STR 10

int vecto();

char seguir[MAX_STRLEN];
int var;

float* vector; 
char* bv;

int vecto(){
int cont=0,ch;
char v[MAX_STR];
printf ("¿number of elements to order?: ");
scanf("%d",&var);
vector = (float*)malloc(var*sizeof(float));
while((ch = fgetc(stdin)) != EOF && ch != '\n' ){};
printf("input number press f for finish \n");
    do{
    fgets(v,sizeof(v),stdin);
    if((strcmp(v,"f")!=0)){
        cont++;
        vector[cont]=strtod(v,&bv);
    }
    }while(!((cont==var) || (strcmp(v,"f")==0)));
printf("\n");
return 0;
}


Are array memory addresses always in the order of least to greatest?


When I'm making a procedure with pointer arithmetic and !=, such as

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n; 
    while (arr != end && arr != --end) 
    {
         swap(arr,end);
         ++arr;
    }
}

I always take a lot of caution because if I write my procedure wrong then in a corner case the first pointer might "jump over" the second one. But, if arrays are such that

&arr[0] < &arr[1] < ... < &arr[n]

for any array arr of length n-1, then can't I just do something like

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n;
    if (arr == end) break;
    --end;
    while (arr < end)
    {
        swap(arr,end);
        ++arr; --end;
    }
}

since it's more readable? Or is there a danger looming? Aren't memory addresses just integral types and thus comparable with < ?


C# Dynamic array


I want an array to contain strings, floats and ints that can be accessed via a index key.

I have an example in Lua how you would do but I don't know how you do it in

bookArray = {];
bookArray[1] = 
{
    Name = "Book 1";
    Price = 50;
    WPP = 374;
    Pages = 42;
}


Rails update multiple columns based on an array


I'm trying to blank out a bunch of columns in an easy-to-read formatted code. I know I could just do this:

@user = User.find(3)
@user.column1 = nil
@user.column2 = nil
@user.column3 = nil
etc...

But that doesn't seem like a very Ruby way to do things, nor is it particularly clean to read.

I'm trying to figure out why I can't just do an 'each do' array like this:

columns = [ "key", "provider", "uid", "access_code",
                "customer_id", "cc_id", "cc_brand", "cc_last4",
                "cc_expiration", "last_payment_id", "last_payment_date",
                "last_payment_amount" ]

columns.each do |record|
  @user.record = nil
end

@user.save

I receive the following error:

undefined method `record=' for #<User:0x00000003a91d18>

I know that similar questions have been asked before, but they are usually related to updated a bunch of different tables. I'm only interested in the user table.

Also, there are a lot of answers linking to http://ift.tt/1apioMa. But that's an old deprecated method that apparently bypasses callbacks. That seems rather dangerous.

Can anyone think why a simple 'each do' array won't work?


ActionScript 3 sort an array with numbers and letters not working as expected


I'm trying to sort the users cards in a card game, for example all user's aces to stand close to each other. I'm using this:

p1cards is an array with elements like "c8", "d9", "h1", letters stand from card symbol (Club, Diamond, Hearts) and number is the card value (1 is Ace, 2 is 2, and so on)

p1cards.sort(sortOrder);

    function sortOrder(a,b)
    {
        var aN = parseInt(a.substr(1));
        var bN = parseInt(b.substr(1));

        if (aN > bN)
        {
            return 1;
        }
        else
        {
            return -1;
        }
    }

The problem is that sorted card like the 8d, 8c are switching places to 8c, 8d, kind of randomly, when I draw a new card.

Any help will be apreciated.

See in picture below:

http://ift.tt/1I9gxbu


Why does variable only increment once in Java code?


I am making a game where a player ('P') starts on a 2d array of dashes at [0][0]. The player is prompted to enter the size of the array, and then enter an action (left, right, up, down, or exit). When that action is entered, 'P' is supposed to move by 1 index. I am working on my moveDown method and nothing else yet. When I type "down", it will increment to theWorld[1][0], but will not increment again (theWorld[2][0]) if I type "down". It just stays at [1][0].

There are two classes to this program, but the only thing my other class has right now is the main method and the world.userInput method, so I won't include that. This is a work in progress, so excuse any sloppy code, extra space, etc. Here is what I have so far:

    import java.util.Scanner;

class World {

private int characterRow;
private int characterColumn;
private char[][] theWorld; 
char player = 'P';
int playerX = 0;
int playerY = 0;
String userAction;
boolean keepPlaying = true;
boolean outOfBounds;

public World() {

    characterRow = 0;
    characterColumn = 0;


}
public World(int height, int width) {

    this.characterRow = height;
    this.characterColumn = width;

}

public void setHeight(int height) {

    characterRow = height;

}
public void setWidth(int width) {

    characterColumn = width;

}
public void userInput(int height, int width, int x, int y) {
    Scanner input = new Scanner(System.in);


    System.out.print("Enter World width: ");
    width = input.nextInt();
    System.out.print("Enter World height: ");
    height = input.nextInt();

    displayWorld(height, width, x, y);

    input.nextLine();

    while(keepPlaying)
    {
    System.out.print("ACTION > ");
    String action = input.nextLine();

    while(!action.equalsIgnoreCase("exit"))
    {
        keepPlaying = true;
        if(action.equalsIgnoreCase("down") && x > theWorld.length)
        {
          outOfBounds = true;
          System.out.println("You cannot go out of bounds. Try again.");
        }
        else
        break;
    }

    if(action.equalsIgnoreCase("down"))
    {
        moveDown(height, width, x, y, action);

    }
}

public void moveDown(int height, int width, int x, int y, String action) {

      if(x < theWorld.length-1)
      {
      x += 1;
    }
      displayWorld(height, width, x, y);


}

    public void displayWorld(int height, int width, int x, int y) {
    theWorld = new char[height][width];
    for(height = 0; height < theWorld.length; height++)
    {
        for(width = 0; width < theWorld[height].length; width++)
        {

            theWorld[height][width] = '-';
            theWorld[x][y] = player;


            System.out.print(theWorld[height][width] + " ");
        }
        System.out.println();
    }



}//end displayWorld
}//end class


Using Random Objects in Arrays


So i am fairly new to programming but I have the basics like loops and arrays down and now I'm moving on the classes and objects. I want my to get my pet to "eat" and output 3 food elements using an array.

This is my main method

Food[] f = new Food[3];
    for(int i = 0; i < 3; i++){
        f[i] = new Food();
        System.out.println("Your " + pet.type + " ate some " + food.name);
        pet.eat(food);
    }

And I am calling the food from the "Food Class"

public class Food {

int nutrition;  // scale from 0 - 5 where 5 is super nutritious
String name;  // name of food

public Food(){
    Random r = new Random();
    int num = r.nextInt(6);
    if (num == 0){
        name = "rocks";
        nutrition = 0;
    } else if (num == 1){
        name = "seeds";
        nutrition = 1;
    } else if (num == 2){
        name = "chips";
        nutrition = 2;
    } else if (num == 3){
        name = "carrots";
        nutrition = 3;
    } else if (num == 4){
        name = "fish";
        nutrition = 4;
    } else if (num == 5){
        name = "steak";
        nutrition = 5;
    }
}

My problem here is when I try to run the loop above, it outputs 3 of the same foods even though i specified in the food class that I wanted it to generate a random one.

Example Output Your dog ate some chips This food is not nutritious at all... Your dog ate some chips This food is not nutritious at all... Your dog ate some chips This food is not nutritious at all...

Thanks in advance!


Changing the order of an array to be the same as another array SWIFT


I've seen this has been done before but can't seem to find it in swift. So I have two arrays, arrayA and arrayB. I want arrayB to sort itself into the same order a arrayA. So for example her is the arrays:

var arrayA = [1,2,3,4,5]
var arrayB = [5,4,3,2,1]

Thanks


Is there a reliable jQuery plugin hat can repopulate the form from json values?


I have a form with 180 form fields. On a button click I need to replace current form fields values with the ones from json var. Instead of doing

on some element click 
$.each(getData, function(index, value) {

    check if select
        add new value, trigger refresh
    check if radio
       add new value, trigger refresh
    check if textarea
       add new value, trigger refresh
...

is there already a plugin that does something like this? I browsed and came up with very old scripts like populate or loadJSON wich are not supported anymore.

My biggest issue is that this is a multi level json array and the field names are like

<input name="form_field[one]"...
<input name="form_field[one][two][three]"...
<input name="form_field[one][two]"...

any help is appreciated.


Why is zIndex in RichMarker library for google maps not working?


I have follow documentation for creating custom markers in google maps (link) and create code like this (documentation of richmarker (link)):

var locations = [
    ['LocA', 45.65, 15.2, 4],
    ['LocB', 45.57, 13.87, 2],
    ['LocC', 46.05, 14.68, 1],
    ['LocD', 46.43, 15.75, 5],
    ['LocE', 46.4, 13.85, 3]            
];

setMarkers(map, locations);

function setMarkers(map, location){

    for(var i = 0; i < location.length; i++){
      var loc = location[i];
      var coordinate = new google.maps.LatLng(loc[1], loc[2]);
      var marker = new RichMarker({
          position: coordinate,
          map: map,
          zIndex: loc[3],
          content:'<div class="myClass">'...+'</div>'
      });
    }           
}

As I understand in zIndex: loc[3] means that it take forth element in array "locations" which is a number in my array (1,2,3,4,5): For example for first (0 row) LocA is name, 45.65 is latitude, 15.2 is longitude, 4 is number of zIndex.

But zIndex in my case is not working. As we can see "LocC" should be in the top of the all markers, than should be followed by "LocB", "LocE", "LocA" and "LocD". But instead the order that is created is: on the top is: LocA, LocB, LocC, LocD, LocE, the order is order from array, so if I put e.g. LocC after LocA in my "locations" array, "LocC" will be on the top. So why is zIndex in my case not working - positions of markers are depending on positions in array?

Tnx for any sugestions.


Number of elements in float array in C


i have array of float in C. the length of this array depends of user input. I need to find out number of elements in this array. Example:

float a[10] = {3.1314, 1.5131, 9.133,  10.333}

How can i check number of elements? sizeof(a)/sizeof(a[0]) always give the max number of elements (10 in this case).


java.util.NoSuchElementException when looping to the second client


new to java and I'm tring to create an array of 5 client objects and pet object depending on the amount in the file specified. However, it reads the first client and pet info fine but when I get to the next client it gives me java.util.NoSuchElementException: null (in java.util.StringTokenizer).

import java.io.*;
import java.util.*;
/**
 * Write a description of class VetClientDriver here.
 * 
 * @author (Anastasia) 
 * @version (4/19/15 --THPT4)
 */
public class VetClientDriver
{
    /**
     * Constructor for objects of class VetClientDriver
     */
    public static void main(String[] args) throws IOException
    {
        String filename = ("C:\\Users\\Anastasia\\Desktop\\clientdata.txt") ;
        File file = new File(filename);
        Scanner fs = new Scanner(file);
        StringTokenizer stok = new StringTokenizer(fs.nextLine(), ",|//");

        VetClient []clients;
        VetPets []pets;
        String last, first, addr, id, num, balance;
        String name,type,rabies,visit,weight;
        String numOfPets;
        //fs = new Scanner(file);
         //stok = new StringTokenizer(fs.nextLine(), ",|//");
         clients = new VetClient[5];
          for(int i=0; i<clients.length; i++)
                     {

                     last = stok.nextToken();
                     first = stok.nextToken();
                     addr = stok.nextToken();
                     id = stok.nextToken();
                     num = stok.nextToken();
                     balance = stok.nextToken();
                     numOfPets = stok.nextToken();

                     clients[i] = new VetClient(last,first,addr,id,num,balance,numOfPets);
                     System.out.println(clients[i].clientInfo());
                     pets = new VetPets[Integer.parseInt(numOfPets)];

                     for(int k=0; k<pets.length; k++)
                        { 
                       stok = new StringTokenizer(fs.nextLine(), ",|/");
                       name = stok.nextToken();
                       type = stok.nextToken();
                       weight = stok.nextToken();
                       rabies = stok.nextToken();
                       visit = stok.nextToken();
                       pets[k] = new VetPets(name,type,weight,rabies,visit);
                       System.out.println(pets[k].petInfo() + "\n");

                        }  


                    }
                     fs.close();
                    } 

                }      


Finding the largest number in an array of integers


I am trying to recursively find the largest element in an array. The user has to input the number of elements that the array will have. My error is that if that the list does not have an element which is larger than the number of elements in the list, the output of the largest number will be the number of elements in the list. eg: array of 5 integers containing {1 1 1 2 3}. the answer will be 5 and not 3. import java.util.*; public class test7 {

public static int findLargest(int[] a, int max) {

    int i=0, j=0, tempmax=0;
    if (a.length == 1) return a[0]>max ? a[0]:max;
    else if(max < a[i]){
        max = a[i];
        int[] tempArr = new int[a.length -1];
        for (i=1; i<a.length; i++){
            tempArr[j] = a[i];
            j++;
        }
        tempmax = findLargest(tempArr, max);
        return tempmax;
    }
    else{
        int[] tempArr = new int[a.length -1];
        for (i=1; i<a.length; i++){
            tempArr[j] = a[i];
            j++;
        }
        tempmax = findLargest(tempArr, max);
        return tempmax;
    }

}

public static void main(String[] args) {
    int[] values = new int[100];

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the number of elements in your list: ");
    int x = scan.nextInt();
    if(x>1 || x<100){
        for (int i=0; i<=(x-1); i++){
            System.out.print("Enter your number: ");
            System.out.println();
            values[i] = scan.nextInt();
        }       
        System.out.println();
        System.out.println("The largest number is: "+findLargest(values, x));
    }
    else System.out.println("The maximum number of elements must be less than 100");


}

}


How to store a number array in MongoDB


I am looking to store an array of individual lotto drawn numbers within a MongoDB document.

Neither of the below structures work. Can anyone point out the correct way to form JSON to facilitate this type of storage?

[{
    "date":"2014-02-10T10:50:42.389Z",
    "numbers":{
        [10,20,30,40,12,31,35]
    }
}]

[{
"date":"2014-02-10T10:50:42.389Z",
    "numbers":{
        10,20,30,40,12,31,35
    }
}]

I am looking to import this document as a Mongo document and ultimately build on it after that.


Create 3rd level foreach and loop the arrays and save it to data?


I am using opencart 1.5.6.4 . I've create a module.

<?php $module_row = 1; ?>
<?php foreach ($modules as $module) { ?>

<?php $element = 1; ?>
<?php if(isset($module['tabs'])) { foreach($module['tabs'] as $tab) { ?>

<?php $elements = 1; ?>
<?php if(isset($tab['styles'])) { foreach($tab['styles'] as $style) {  ?>

<?php $elements++; } }  ?>

<?php $element++; }  } ?>

<?php $module_row++; } ?>

But 3rd level not working and saved.

<?php $elements = 1; ?>
    <?php if(isset($tab['styles'])) { foreach($tab['styles'] as $style) {  ?>

When i changed it to

<?php $elements = 1; ?>
        <?php foreach($tab as $style) { if ($style > 0) {  ?>

Not working properly.

What is the correct solution?


constexpr char array with GCC and clang


Consider the following code:

#include <cstddef>
#include <iostream>
#include <stdexcept>

class const_string {
public:
    template <std::size_t sz>
    constexpr const_string(const char (&str)[sz]): p_(str) {}
    constexpr char operator[](std::size_t i) const { return p_[i]; }
private:
    const char* p_;
};

template <char c>
void Print() { std::cout << c << '\n'; }

int main() {
    constexpr char str[] = "Hello World";
    Print<const_string(str)[0]>();
}

It compiles fine with clang, while GCC gives the following error message:

in constexpr expansion of 'const_string((* & str)).const_string::operator[](0ul)' error: '(const char*)(& str)' is not a constant expression

However, if I change Print<const_string(str)[0]>(); to Print<const_string("Hello World")[0]>();. Both clang and GCC compile fine.

What is going on here? Which compiler is correct according to the standard?