Java- Iterating backwards through Array under a condition

So for one of my game models, there is an array of elements represented as a string "--X-X" so that this board has 5 boxes, and positions are 0-4. Each 'X' can only move left. There is an "X-Index" so that if I run getIXPosition(1) it will return the position of the first X which is 2. And getXPosition(2) will return second X's position which is 4. So the string board is "--X-X" but in my code it's represented as an array as "00102" so that I can keep track of xIndex.


Now my issue is that I need to make a move method that prevents the second x from skipping over the first X into position 1 or 0. That is not allowed in this game. I thought I wrote the method correctly but my tests aren't passing when I test to make sure second X can not hop over any X's before it.



public void move(int xIndex, int newPosition) {
int oldPosition = getXPosition(xIndex);

for(int i= oldPosition - 1; i >= 0;i--) {
while (board[i] == 0 ) {
board[oldPosition] = '0'; // so this spot is open '-'
board[newPosition] = xIndex;
}

throw new IllegalArgumentException("Error cannot move X to new position");
}
}


What am I doing wrong?


Jquery Numberical Array to String and get a Substr()

I initiated a numerical array inside a javascript and to converted it into a string using join() but when I try to get a substr(), it doesn't to work. There seems to be a techincal error. Please help!



var array = [85, 13, 7, 42, 78, 9];
$("#div1").html("<b>This is the original array:</b><br><br>" + array.join("<br>"));

$("#div2").html("<br><b>This is the converted string:</b><br><br>" + array.join(""));

$("#div3").html("<br><b>The substring (from 0 to 3) is:</b><br><br>" + array.substr(0,3));


NOTE: div1,div2,div3 are 3 seperate divs with ids respectively. Thats where i want to display the results.


Putting strings in to an array in x86?

I need help putting a string from stdin into a an array in x86 using NASM and sys_calls. I'm having trouble putting each char of the string in an index of an array. I'm also having trouble exiting when the sring gets the end of string char. the array is a global array so it needs to be in the data section. the array is a byte array.


How do you properly use "write" in Applescript?

I'm having trouble figuring out how to properly use "write" in applescript. I currently have code like this:



set randomArray to {"hello", "text", "file"}
set saveFile to (path to desktop as text) & "RandomFile.txt"

write randomArray to saveFile starting at eof as list


I know that this is not right, but I can't seem to figure out what the correct thing to put where "saveFile" is would be.


Any help is appreciated, thanks :)


Swig - C++ Array of size3 to a custom datatype

I am using Swig to wrap code from C++ to C#. I want to use this function



//C++
void dummy(float vec[3])
{
//do stuff
}


and it should look like this after being swigged



//C#
void dummy(float float3[3])
{
//do stuff
}


while float3 is a custom datatype representing a classical Vector in 3-dimensional Space. I'm aware of "arrays_csharp.i" but I don't want it to be bound to the name of a variable since the later to be swigged code is way to extensive for this. How doeas a typemap for a case like this look? I'm really thankfull for any kind of help and even just little tips or suggestions.


Find a list of max values in a text file using awk

I am new to awk and I cannot figure out the correct syntax for the task I am working on.


I have a text file which looks something like this (the content is always sorted but is not always the same, so I cannot hard code the index of the array): 27 abc123 27 abd333 27 dce123 23 adb234 21 abc789 18 bcd213


So apparently the max is 27. However, I want my output to be: 27 abc123 27 abd333 27 dce123 and not the first row only.


The second column is just there, my code always sorts the text file based on the first column.


My code right now set the max as the first value (27 for example), and as it reads through the lines, it stores only the rows with the max values in an array and eventually print out the output.


awk 'BEGIN {max=$1} {if(($1)==max) a[NR]=($0)} END {for (i in a) print a[i]}' file


How to turn an array of Strings into an Array of Ints?

I'm new to Java programming, but after looking around on this site, I'm fairly certain this should work.



public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output

for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int

return arrayInt;
}


What I want this method to do is take an input array: ["1","2","3"] with each item being a string and return [1,2,3] where each item is an int.


I'm calling the method with this code



int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);


In this case, toBeSorted is both being declared here and initialized at the same time.


Whenever I try to run this I get the following error:



Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at sorter.Sorter.ArrayStringToArrayInt(Sorter.java:31)
at sorter.Sorter.main(Sorter.java:22)
Java Result: 1


Line 31 is the body of my For loop, the part that does the parsing, and line 22 is the place where the method is called.


The reason I need this is because I'm trying to take an input from the user, with the Scanner class and want them to be able to enter many numbers at the same time. I then use a delimiter pattern to turn the input into an array. While that seems fine, I could only figure out how to make the input be an array of strings, not ints, which is my problem.


So I guess what I'm asking is 1) why does my code not work? and 2) is there an easier way to take an input from the user and turn it into an array of ints than this?


For those who would like to see my entire code, here it is


The bit in the middle with the test variable and the adding of two numbers is just a way for me to test my code and see if it worked. It should show the result of adding the first two numbers in the list that you entered



package sorter;

import java.util.Scanner;
import java.util.Arrays;

public class Sorter {

public static void main(String[] args) {

Scanner userInput = new Scanner( System.in );

System.out.println("Enter a list to be sorted, seperate numbers by commas:");

String input = userInput.nextLine(); //Gets aan input as a String
String delims = "[,]+"; //Use Comma as Delimiter
String[] inputStringArray = input.split(delims); //Parse String and creates
//an array

System.out.println(Arrays.toString(inputStringArray)); //Outputs a string of
//the given array

int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
int test = toBeSorted[0] + toBeSorted[1];
System.out.println(test);
}

public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output

for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int

return arrayInt;
}
}

Triangular part of a table

I would like to access the lower triangular part of a (square) table with cell elements. I tried the tril function, but it doesn't work for input arguments of type 'cell'. Is there any workaround? Thanks.


Getting the array sorted in relation to a value Matlab

Let's say I have an array arr of doubles:



arr = 120,121,118,119,117,123,120


And a value x



x = 120


I want to get this value



newarr = 120,120,119,121,118,117,123


Which is a new array, the same size of arr, but the values are sorted in relation to the value x, having the closest value first (doesn't matter if it's ascending or descending).


Any idea?


PHP function to retrieve all images and their attributes from given html string and save to array and returns array

I need to write php function to retrieve all images attributes like src,alt, height, width from given html string and store those attributes into array result. i need this function to return the array result for further processing like saving into database, thumbnail creation ...etc.


i have wrote the following function but i am not satisfied as i am not able to extract elements other then scr



$url = '<ul> <li> <img src="http://ift.tt/1yIjxd6"/> </li> <li> <img src="http://ift.tt/1DzXhkb"/> </li> <li> <img src="http://ift.tt/1yIjxdb"/> </li> <li> <img src="http://ift.tt/1DzXhkf"/> </li> <li> <img src="http://ift.tt/1yIjA8C"/> </li> <li> <img src="http://ift.tt/1DzXfJf"/> </li> <li> <img src="http://ift.tt/1yIjy0H"/> </li> </ul> ';

function getItemImages($content)
{
$dom = new domDocument;
$dom->loadHTML($content);
$dom->preserveWhiteSpace = false;

$elements = $dom->getElementsByTagName('img');

if($elements->length >= 1) {
$url = array();
$title = array();
foreach($elements as $element) {
$url[] = $element->getAttribute('src');
$Title[] = $element->getAttribute('title');
}
return ($url);
}

How to limit function parameter as array of fixed-size?

How can I limit python function parameter to accept only arrays of some fixed-size?


I tried this but it doesn't compile:



def func(a : array[2]):


with



TypeError: 'module' object is not subscriptable


I'm new to this language.


How to read from File into 2d char Array

I'm trying to figure out how to read from a txt which looks like this:



12
12
WWWWWWWWWWWW
W3000000000W
W0000000000W
W0000000000W
W0000000000W
W0000000000W
W0000000040W
W0000000000W
W0000000000W
W0000000000W
W0000000000W
WWWWWWWWWWWW


Into a String[][];


The first 2 lines are the size of the String[][]. This is the code which says



Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 at map[i][j] = temp[j].toString();




public String[][] read() throws IOException{
BufferedReader br = new BufferedReader(new FileReader("D:/College/Java Eclipse/Map.txt"));
String line = " ";


int columnCount = Integer.parseInt(br.readLine());
int rowCount = Integer.parseInt(br.readLine());

String[] temp;
String[][] map = new String[rowCount][columnCount];

while ((line = br.readLine())!= null){
temp = line.split("\\s+");

for(int i = 0; i<rowCount; i++) {
for (int j = 0; j<columnCount; j++) {
map[i][j] = temp[j].toString();
}
}

}
br.close();
return map;

}


What is wrong i can't figure out?


I need an array to print all the numbers and count their occurrence

I have an array with the numbers (2,2,2,2,4,5,9,9,11,11,12) and I need the console to print out all the numbers inbetween the min and the max and count their occurrence. ie. Number 2 occurs 4 times, number 3 occurs 0 times, number 4 occurs 1 time.


I have it semi working but it is printing too much. I understand why but cannot figure out how to do it another way.



int min = 2;
int max = 12;
int m=0;


for(int i=min;i<=max;i++){
for(int j=0;j<y.length;j++){
if(y[j]==i){
m+=1;
}
else{
if(m>=1){
System.out.println(i+" "+m);
m=0;
break;
}
System.out.println(i+" "+m);

}
}
}

Filtering dynamically generated search results in php

Background to project


I will start off by saying I am not the best at php and am a beginner by all accounts, but I stupidly tried to create a php based search for my university project.


It is a smoothie recipe website, in the first instance a user will search by typing in a keyword, this will generate search results. This part I have got down fine. When it comes to filtering the results however, I am really struggling. The user should be able to filter by the fruits/vegetables/type of smoothie as well as the keyword itself. For example:


Keyword = apple Filters = mango(fruit filter), spinach(veg filter) detox (type filter)


However, what currently happens is, I will get every instance of apple, mango, spinach and detox smoothies. As well as this, if a smoothie contains both apple and mango for example it will generate that smoothie twice. I am aware I need to include array_unique() in here somewhere, but I really don't know where.


PHP


Here is my php so far:`



$dbhost = '*';
$dbuser = '*';
$dbpass = '*';
$dbname = '*';

$k = $_GET['k'];
$terms = explode(" ", $k);

//START THE QUERY HERE
$query = "SELECT * FROM search";

//FROM THE VIEW FIND OUT IF THE USER HAS CLICKED ON ANY FRUITS.
//IF SO THEN JOIN THE SEARCH_METADATA TABLE TO THE QUERY SO YOU CAN FIND ALL THE POSSIBLE FRUITS
if (!empty($_GET['fl-Fruit'])) {
$query .= ' INNER JOIN search_metadata ON search_id = search.id';
}

//START THE WHERE CLAUSE HERE
$query .= ' WHERE ';

//FIRST LOOK FOR THE SEARCH TERM THE USER ENTERED
foreach ($terms as $each){
$i++;
if ($i == 1)

$query .= " keywords LIKE '%$each%' ";
else
$query .= " OR keywords LIKE '%$each%' ";

}

//ONCE THE SEARCH TERM HAS BEEN FOUND
//TODO ==== RUN CHECKS FOR VEG AND TYPE OPTIONS
if (isset($_GET['fl-Fruit'])) {

//SET ALL THE GET VARIABLES TO NEW VARIABLES JUST FOR MAKING IT EASIER TO READ
$fruits = $_GET['fl-Fruit'];


//FOREACH FRUITS SELECTED FROM THE FACET SEARCH
//RUN THROUGH EACH ONE IN THE WHERE CLAUSE.
foreach ($fruits as $fruit) {
$query .= " XOR value = '$fruit' ";
}

}
if (isset($_GET['fl-veg'])) {

//SET ALL THE GET VARIABLES TO NEW VARIABLES JUST FOR MAKING IT EASIER TO READ
$vegetables = $_GET['fl-veg'];


//FOREACH FRUITS SELECTED FROM THE FACET SEARCH
//RUN THROUGH EACH ONE IN THE WHERE CLAUSE.
foreach ($vegetables as $veg) {
$query .= " XOR value = '$veg' ";
}
}
if (isset($_GET['fl-s-type'])) {

//SET ALL THE GET VARIABLES TO NEW VARIABLES JUST FOR MAKING IT EASIER TO READ
$types = $_GET['fl-s-type'];


//FOREACH FRUITS SELECTED FROM THE FACET SEARCH
//RUN THROUGH EACH ONE IN THE WHERE CLAUSE.
foreach ($types as $type) {
$query .= " XOR value = '$type' ";
}
}

var_dump($query);


echo '<h1>' ."Your search results for $k". '</h1>';
//CONNECT TO DATABASE

mysql_connect("$dbhost", "$dbuser", "$dbpass");
mysql_select_db("$dbname");

$query = mysql_query($query);
$numrows = mysql_num_rows($query);

if ($numrows > 0) {

while ($row = mysql_fetch_assoc($query)) {
$id = $row ['id'];
$title = $row ['title'];
$description = $row ['description'];
$keywords = $row ['keywords'];
$link = $row ['link'];

echo "<div class='result'><img src='images/$id.jpg'><div class='result-text'><h2><a href='$link'>$title</a></h2>
<p>$description</p></div></div>";
}
}

else
echo "No results for <b>$k</b>";

?>`


HTML Form



<form class='form-wrapper' action='./search.php' method='get'>
<input id='search' type='text' name='k' value='<?php echo $_GET['k']; ?>' />
<input type='submit' id="submit" value='search'>

<div class="menu">
<strong><p class="menu-toggle"> Filter your search </p></strong>
</div>
<section class="filters">
<h2>Filter smoothies by Fruit:</h2>

<p>
<input type="checkbox" name="fl-Fruit[]" value="apple" id="apple">
<label for="apple">Apple</label>
</p>
...
<p>
<input type="checkbox" name="fl-Fruit[]" value="strawberries" id="strawberries">
<label for="strawberries">Strawberries</label>
</p>



<h2>Filter smoothies by veg:</h2>
<p>
<input type="checkbox" name="fl-veg[]" value="beetroot" id="beetroot">
<label for="beetroot">Beetroot</label>
</p>
...
<p>
<input type="checkbox" name="fl-veg[]" value="spinach" id="spinach">
<label for="spinach">Spinach</label><br>
</p>


<h2>Filter by smoothie type:</h2>

<p>
<input type="checkbox" name="fl-s-type[]" value="detox" id="detox">
<label for="detox">Supet Detox</label>
</p>
...
<p>
<input type="checkbox" name="fl-s-type[]" value="muscle" id="muscle">
<label for="muscle">Muscle Building</label>
</p>
</form>


Tables


I currently have two tables "search" and "search_metadata". The "search" table contains the keywords for the keyword search and the "search_metadata" table contains the properties for the filters and has the following columns "search_id" (foreign key), "type" (fruit, veg, type), "value" (apple, carrot, detox).


Just to reiterate what I am asking:



  1. How do I incorporate Array_unique() to stop duplicate results appearing

  2. How I make it so that if a user searches for "apple" then selects "mango" and "passionfruit" filters, that only smoothies with those 3 ingredients in will show (not showing smoothies with one of those ingredients in)


I hope there is enough information/not too much information, if I can improve this question please let me know, as this is the first time of me posting on here.


Thanks


Check while iterating through an array that certain "divider elements" are regularly spaced?

I'm having trouble coming up with the efficient algorithm that must exist for this problem:


Iterate through an array checking for elements which are "markers". Set a flag if I notice any marker that doesn't divide the rest of the elements into runs of the same length. Except the final run, which is the remainder.


Example that shouldn't set the flag:



*....*....*....*..*


Example that should set the flag:



*....*....*...*...*


Intuition says it should be possible to do online pretty trivially and that it's probably equivalent to some well-known problem whose usual name I don't know.


Type cast a multidimensional object array to multidimensional array

I have the following object returned from a function



stdClass::__set_state(array(
0 =>
stdClass::__set_state(array(
'term_id' => '175',
'name' => 'a term',
'slug' => 'a-term',
'term_group' => '0',
'term_taxonomy_id' => '177',
'taxonomy' => 'category',
'description' => '',
'parent' => '174',
'count' => '1',
)),
1 =>
stdClass::__set_state(array(
'term_id' => '182',
'name' => 'aciform',
'slug' => 'aciform',
'term_group' => '0',
'term_taxonomy_id' => '184',
'taxonomy' => 'category',
'description' => '',
'parent' => '0',
'count' => '1',
)),
))


If I type cast this to an array, I get the following



array (
0 =>
stdClass::__set_state(array(
'term_id' => '175',
'name' => 'a term',
'slug' => 'a-term',
'term_group' => '0',
'term_taxonomy_id' => '177',
'taxonomy' => 'category',
'description' => '',
'parent' => '174',
'count' => '1',
)),
1 =>
stdClass::__set_state(array(
'term_id' => '182',
'name' => 'aciform',
'slug' => 'aciform',
'term_group' => '0',
'term_taxonomy_id' => '184',
'taxonomy' => 'category',
'description' => '',
'parent' => '0',
'count' => '1',
)),
)


The problem is, I need the inner objects to be type cast to arrays as well. I can do this by using a foreach loop and then type casting every value to an array and build a new array out of that, something like



foreach ($a as $b) {
$c[] = (array) $b;
}
?><pre><?php var_dump($c); ?></pre><?php


which does give me what I want



array(75) {
[0]=>
array(9) {
["term_id"]=>
string(3) "175"
["name"]=>
string(6) "a term"
["slug"]=>
string(6) "a-term"
["term_group"]=>
string(1) "0"
["term_taxonomy_id"]=>
string(3) "177"
["taxonomy"]=>
string(8) "category"
["description"]=>
string(0) ""
["parent"]=>
string(3) "174"
["count"]=>
string(1) "1"
}
[1]=>
array(9) {
["term_id"]=>
string(3) "182"
["name"]=>
string(7) "aciform"
["slug"]=>
string(7) "aciform"
["term_group"]=>
string(1) "0"
["term_taxonomy_id"]=>
string(3) "184"
["taxonomy"]=>
string(8) "category"
["description"]=>
string(0) ""
["parent"]=>
string(1) "0"
["count"]=>
string(1) "1"
}
}


My PHP knowledge are still quite limited, what I need to know is, is there another shorter better way to achieve this, or is this the only way.


EXTRA BACKGROUND




  • I cannot unfortunately change the output from the function. This is a function in Wordpress which only returns an object of objects and does not have an option to return an array of an array of values




  • I need to search for a specific term_id and returns its position. Again, I can use a foreach loop do do this, but PHP 5.5 + has a function array_column where you can use array_search to search for a specific value (in this case term_id) in a multidimensional array and return the key of that specific array.




Javascript: Find douplicated values from array with keys

Title is pretty much self explanatory...


I want to be able to find duplicated values from JavaScript array.


The array keys can be duplicated so I need to validate only the array values.


Here is an example :



var arr=[
Ibanez: 'JoeSatriani',
Ibanez: 'SteveVai',
Fender: 'YngwieMalmsteen',
Fender: 'EricJohnson',
Gibson: 'EricJohnson',
Takamine: 'SteveVai'
];


In that example:


the key is the guitar brand the value is the guitar player name.


So:


If there is duplicated keys (like: Ibanez or Fender) as on that current example that is OK :-)


But


If there is duplicated values (like: EricJohnson or SteveVai) I'm expecting to get (return) that error:



EricJohnson,SteveVai

Android json parse of nested array

I have a json of the following format



{
key1:value1,
key2:3,
test0:{
info:{
title:1
}
},
test2:{
info:{
title:2
}
},
test3:{
info:{
title:3
}
}
}


Now, depending upon the value of key2, I want to access all the values of the keys test0, test1 and test2 using a for loop.


How can I achieve this in Android?


Making a copy of an array with Arrays.asList

so I have an int array, and want to have another array that points to the same values as the original array so that when original array changes the second array would point to to the new value.


I tried with



List<Integer> secondList = new ArrayList<>(Arrays.asList(original array));
secondList = secondList.subList(start,finish);


But I get an error that says that .asList returns - list of type int[] Am I doing something wrong? Or is there any good way to do this?


How to sort an array and then save to database in Android

I'm trying to sort an array of numbers, then take the output to save it to my database. Any help would be appreciated, thank! I can sometimes get the sort to work, but I'm having trouble accessing the array to get specific numbers to then save.



Integer[] toSortArray = {saveInt1, saveInt2, saveInt3, saveInt4, saveInt5};

Arrays.toString(new Integer[]{toSortArray[2]})

Wrangle cell array of various-sized cell arrays into cell array of cell arrays of size {1xN}

I'm trying to wrangle combnk to generate all the combinations of strings in a cell. E.g.:



someStrings = {'a','b','dog','goat'};
results = arrayfun(@(k) combnk(someStrings,k),1:length(someStrings),'UniformOutput',0);


This gives me a 4*1 cell array of cell arrays with the following dimensions:



{4x1 cell} {6x2 cell} {4x3 cell} {1x4 cell}


What I want is a 15*1 cell array of cell arrays, each of size {1xN}; i.e. 4 cell arrays of size {1,1}, 6 of size {1,2}, etc. How can I do this efficiently?


EDIT: Okay, now I'm here:



results = transpose(arrayfun(@(k) num2cell(combnk(someStrings,k),2),1:length(someStrings),'UniformOutput',0));
finalResults = vertcat(results{:});


Is it possible to turn that into one line? How do you index into a cell array like "{:}", but in the line the cell array was created?


Algorithm to distribute N elements into X groups exponentially

I have 600 elements in an array. I would like to distribute them across 100 groups. Any clues on how could I create an algorithm (function or method) that takes the number of elements (600) and the number of groups (100) and distributes those elements exponentially in such groups.


The idea is to create a game where the difficulty increases. There are 600 enemies and 100 levels. First level will have 2 enemies, second level also 2, third level 3 enemies... level 99 will have 20 enemies.


Input array:



var enemies = [
[enemy1],
[enemy2],
[enemy3]
...
]


Output array:



var levels = [
[level1
[enemy1],
[enemy2]
],
[level2
[enemy3],
[enemy4]
],
[level3
[enemy4],
[enemy6],
[enemy7]
],
]


Is this even possible to do? Or should I look for other solutions? At this point I think I will do some kind of manual distribution, but I'm curious if this problem is as hard as it seems.


Fortran ordered (column-major) numpy recarray possible?

I am looking for a way to more efficiently assign column of a numpy structured array.


Example:



my_col = fn_returning_1D_array(...)


executes more than two times faster on my machine than the same assignment to the column of a structured array:



test = np.ndarray(shape=(int(8e6),), dtype=dtype([('column1', 'S10'), ...more columns...]))
test['column1'] = fn_returning_1D_array(...)


I tried creating test with fortran ordering but it did not help. Presumably the fields stay interleaved in memory.


Does anybody have any idea here? I would be willing to use low-level numpy interfaces and cython if they could help.




Edit 1: in response to hpaulj's answer


The apparent equivalence of recarray column assignment and "normal" array column assignment results only if the latter is created with row-major order. With column-major ordering the two assignments are far from equivalent:


Row-major



In [1]: import numpy as np

In [2]: M,N=int(1e7),10

In [4]: A1=np.zeros((M,N),'f')

In [9]: dt=np.dtype(','.join(['f' for _ in range(N)]))

In [10]: A2=np.zeros((M,),dtype=dt)

In [11]: X=np.arange(M+0.0)

In [13]: %timeit for n in range(N):A1[:,n]=X
1 loops, best of 3: 2.36 s per loop

In [15]: %timeit for n in dt.names: A2[n]=X
1 loops, best of 3: 2.36 s per loop

In [16]: %timeit A1[:,:]=X[:,None]
1 loops, best of 3: 334 ms per loop

In [8]: A1.flags
Out[8]:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False


Column-major



In [1]: import numpy as np

In [2]: M,N=int(1e7),10

In [3]: A1=np.zeros((M,N),'f', 'F')

In [4]: dt=np.dtype(','.join(['f' for _ in range(N)]))

In [5]: A2=np.zeros((M,),dtype=dt)

In [6]: X=np.arange(M+0.0)

In [8]: %timeit for n in range(N):A1[:,n]=X
1 loops, best of 3: 374 ms per loop

In [9]: %timeit for n in dt.names: A2[n]=X
1 loops, best of 3: 2.43 s per loop

In [10]: %timeit A1[:,:]=X[:,None]
1 loops, best of 3: 380 ms per loop

In [11]: A1.flags
Out[11]:
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False


Note that for column-major ordering the two buffers are no longer identical:



In [6]: A3=np.zeros_like(A2)

In [7]: A3.data = A1.data

In [20]: A2[0]
Out[20]: (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)

In [21]: A2[1]
Out[21]: (1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)

In [16]: A3[0]
Out[16]: (0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)

In [17]: A3[1]
Out[17]: (10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0)

Adding empty lines between sentences in text file

So I have the following sentences in a text file:



Something I don't know
Something else as well
And this here
And that


And I want to make it look like this



Something I don't know

Something else as well

And this here

And that


I know the code up to the point that I copy the content in a character array but I don't know how to add the extra '\n' character in between the array.


Printing out 2D array from function C++

Ive been trying this for hours no and have made no progress, the programme should create a 2D array in the function of a 16 by 16 grid of x's and then in the main programme i should be able to print this grid on the console but when run i get no result, any help would be apreciated (newbie)



#include <iostream>
#include <cstdlib>

char **create2DArray(); //function prototype

#define WIDTH 16
#define HEIGHT 16

char** myArray; //global array


char **create2DArray(){

int i,j;
char **array = (char **) malloc(sizeof(char *) * WIDTH);

for(i=0; i<WIDTH; i++)
array[i] = (char *) malloc(sizeof(char) * HEIGHT);

for(i=0; i<WIDTH; i++)
for(j=0; j<HEIGHT; j++)
array[i][j] = 'x';
return array;
}


int main(int argc, char** argv) {

char **create2DArray();
myArray = create2DArray();
void printArray(char** array);

return 0;
}

Sort JSON array by an Array within Array

I need to sort my json by an array within the array (hopefully that makes sense). In the JSON below, i need to sort all items by Distance/Miles. So my code is as follows but i get a crash where noted.



_arrAllKeys = [jsonDictionary objectForKey:@"items"];


NSMutableArray *names = [[NSMutableArray alloc] init];

for (NSDictionary *proj in jsonDictionary) {
NSArray *ids = [proj objectForKey: @"distance"]; //CRASHES HERE UNRECOGNIZED SELECTOR

for (NSDictionary *name in ids)
{
[names addObject: [name objectForKey: @"miles"]];
}
}

_arrAllKeys = [names sortedArrayUsingSelector: @selector(localizedCaseInsensitiveCompare:)];


And my JSON snippet:



{
"items": [
{
"ID": "794",
"title": "Here is a title",
"price": "450.00",
"date_time": "2015-04-18 15:24:23",
"description": "Here is description",
"category_id": "8",
"distance": {
"miles": 6465.5731978902,
"kilometers": 10405.331432585
},
"images": [
"http://myimageurl.com"
],
"latitude": "00.00000",
"longitude": "-00.0000",
"location": "Kansas City KS",
"creationdate": "Posted: Apr 18, 2015",
"sellerUserID": "393",
"seller_email": "email@email.com",
"is_deleted": "0"
},


Any help would be greatly appreciated.


Putting large strings of data into ExpandableListView with string-array


Problem: I want to create an ExpandableListView that when you click on a parent, it displays a child that is a stored list made in a string-array in your strings.xml file. The strings are a few sentences each.



Lots of ExpandableListView tutorials and samples online have smaller bits of data being stored. Also they are all storing them in java. That kind of sucks because what if you want to translate your app and you are handling a list of longer strings? It would be easier to have it in your strings.xml file. How would I display that data using code like that? I don't want to edit the data at all, it's going to remain static like reference material.


Like this one, I can see how it is doing it in java. http://ift.tt/1e1h4JP


It's using an arraylist in java to store and display data:



listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

// setting list adapter
expListView.setAdapter(listAdapter);
}

/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();

// Adding child data
listDataHeader.add("Top 250");
listDataHeader.add("Now Showing");
listDataHeader.add("Coming Soon..");

// Adding child data
List<String> top250 = new ArrayList<String>();

// Adding child data
List<String> top250 = new ArrayList<String>();
top250.add("The Shawshank Redemption");
top250.add("The Godfather");
top250.add("The Godfather: Part II");
top250.add("Pulp Fiction");
top250.add("The Good, the Bad and the Ugly");
top250.add("The Dark Knight");
top250.add("12 Angry Men");

List<String> nowShowing = new ArrayList<String>();
nowShowing.add("The Conjuring");
nowShowing.add("Despicable Me 2");
nowShowing.add("Turbo");
nowShowing.add("Grown Ups 2");
nowShowing.add("Red 2");
nowShowing.add("The Wolverine");

List<String> comingSoon = new ArrayList<String>();
comingSoon.add("2 Guns");
comingSoon.add("The Smurfs 2");
comingSoon.add("The Spectacular Now");
comingSoon.add("The Canyons");
comingSoon.add("Europa Report");

How to access elements of this array?

huge javascript noob here. I made a function that is returning me a very weird array. This array has all the information I need but I can't seem to access any data in it. This is the array when I console log it:


http://ift.tt/1D2rRPS


[Array[0]] 0: Array[0] 1: Object 2: Object proto: Array[0]


When I try to call this "test" variable that holds this array, using test[0] I get [] and when I use test[1] I get undefined.


How do I randomly select a string from an array in swift?

I have started programming with swift and I was wondering how I randomly select a string from an array.


I have the array part figured out and how to take something from the array but I don't know how to randomly take something from the array. I've tried searching for it but its always in another programming language.


Any help would be great!


javascript sorting array of objects in a specific order

I have the following array:



[{"cod_nivel":"INC2","cod_modelo":"D"},
{"cod_nivel":"PRIM1","cod_modelo":"B"},
{"cod_nivel":"INC2","cod_modelo":"B"},
{"cod_nivel":"INC1","cod_modelo":"D"},
{"cod_nivel":"PRIM1","cod_modelo":"D"},
{"cod_nivel":"BAC2","cod_modelo":"B"},
{"cod_nivel":"BAC2","cod_modelo":"D"},
{"cod_nivel":"BAC2","cod_modelo":"A"}]


I need to order this array of objects by "cod_modelo" ascending grouped by "cod_nivel". So the result should be:



[{"cod_nivel":"INC1","cod_modelo":"D"},
{"cod_nivel":"INC2","cod_modelo":"B"},
{"cod_nivel":"INC2","cod_modelo":"D"},
{"cod_nivel":"PRIM1","cod_modelo":"B"},
{"cod_nivel":"PRIM1","cod_modelo":"D"},
{"cod_nivel":"BAC2","cod_modelo":"A"},
{"cod_nivel":"BAC2","cod_modelo":"B"},
{"cod_nivel":"BAC2","cod_modelo":"D"}]


Ok I made this code that orders the array first by cod_nivel and then by cod_modelo:



var sortedArray = array.sort(function (a, b) {
return (a["cod_nivel"] > b["cod_nivel"]) ? 1 : -1;
}).sort(function (a, b) {
if (a["cod_nivel"] == b["cod_nivel"])
return (a["cod_modelo"] > b["cod_modelo"]) ? 1 : -1;
else
return 0;
});


The thing is that this code is ordering also by "cod_nivel" so the obtained array would be:



[{"cod_nivel":"BAC2","cod_modelo":"A"},
{"cod_nivel":"BAC2","cod_modelo":"B"},
{"cod_nivel":"BAC2","cod_modelo":"D"},
{"cod_nivel":"INC1","cod_modelo":"D"},
{"cod_nivel":"INC2","cod_modelo":"B"},
{"cod_nivel":"INC2","cod_modelo":"D"},
{"cod_nivel":"PRIM1","cod_modelo":"B"},
{"cod_nivel":"PRIM1","cod_modelo":"D"}]


Note that BAC2 cod_nivel objects are at the beginning.


What I need is to order first by cod_nivel but in a given order, which is:



  1. INC1

  2. INC2

  3. PRIM1

  4. PRIM2

  5. BAC1

  6. BAC2


I assume I need an array with the fixed order of "cod_nivel" and use it while ordring but I don't know how to use it so I did not include in my approach.



var order_arr = ['INC1', 'INC2', 'PRIM1', 'PRIM2', 'BAC1', 'BAC2']


And after that, order then by cod_modelo (grouped by each cod_nivel).


I hope I have explained myself clearly and someone can help me.


Perl: insert elements of array in file by substitution

1) I have a textfile. The file contains a STRING that needs to be substituted with multiple lines, those lines are elements of an array.


Contents of file:



line 1
line 2
line 3
STRING
line 4
...


2.)I have an array



@array = qw (ele1 ele2 ele3);


This array can have 2 or more elements.


3.)I want to open the file, substitute the STRING with following pseudocode:



s/STRING/@array/;


and write results in a new file.


4.) The new file with result should look like this :



line 1
line 2
line 3
ele1
ele2
ele3
line 4
...


Here a piece of pseudocode:



open (FILE "< file.txt");
open (OUTPUT "> new.txt");
@array=qw(ele1 ele2 ele3);
for $line (<FILE>) {
s/STRING/@array/;
print OUTPUT "$line\n";
}
close FILE;
close OUTPUT;


Any suggestions on how to insert elements of an array into this file using substitution?


I am not looking for solutions based on sed, awk, cat or Unix shell tools.


Rest parameter problems

I'm attempting to have a class inherit a rest parameter from a parent class. Unfortunately for some reason the inherited rest parameter's inputs are treated as one whole index rather than each one acting like its own index.


Here's the code for the parent class with a rest parameter that works properly:



package {
import flash.events.MouseEvent;
import flash.display.Stage;

public class SubClassText extends ClassText {
protected var parentText:ClassText;
protected var setStatValues;
protected var className:String;
protected var classType:int;

public function SubClassText(textKey:String, textName:String, stageInstance:Stage, isVisible:Boolean, alignToObject:Object, direction:String, xDistance:Number, yDistance:Number, onOverText:String, parentText:ClassText, className:String, classType:int, ... setStatValues) {
super(textKey, textName, stageInstance, isVisible, alignToObject, direction, xDistance, yDistance, onOverText);
this.parentText = parentText;
this.parentText.subClassArray.push(this);
this.setStatValues = setStatValues;
this.className = className;
this.classType = classType;
}

//Called when the player clicks this object
override protected function onClick(e:MouseEvent) {
trace(this.setStatValues.length);
Entity.getEntity("entityName", "player").setStat("className", this.className);
Entity.getEntity("entityName", "player").setStat("classType", this.classType);

for(var i:int = 0; i < this.setStatValues.length; i++) {
Entity.getEntity("entityName", "player").setStat(Main.statArray[i], this.setStatValues[i]);
}
Main.setClassVisibility(this.parentText.subClassArray, true);
}

//Adds this object to it's parent's class array
override protected function addToArray() {
Main.subClasses.push(this);
}
}
}


I have the trace() call in the onClick listener to see the length of the rest parameter. In all instances of this class the rest parameter returns the proper amount of inputs (in this case, 5 since that's how many stats an entity has).


And here's the class that extends this parent class:



package {
import flash.events.MouseEvent;
import flash.display.Stage;

public class AllySubClassText extends SubClassText {
private var displayName:String;

public function AllySubClassText(textKey:String, textName:String, stageInstance:Stage, isVisible:Boolean, alignToObject:Object, direction:String, xDistance:Number, yDistance:Number, onOverText:String, parentText:ClassText, displayName:String, className:String, classType:int, ... setStatValues) {
super(textKey, textName, stageInstance, isVisible, alignToObject, direction, xDistance, yDistance, onOverText, parentText, className, classType, setStatValues);
this.displayName = displayName;
}

//Called when the player clicks this object
override protected function onClick(e:MouseEvent) {
trace(this.setStatValues.length);
Main.tryAddAlly(this.displayName, this.className, this.classType, this.setStatValues);
Main.setAllyVisibility(this.parentText.subClassArray, true);
}

//Adds this object to it's parent's class array
override protected function addToArray() {
Main.allySubClasses.push(this);
}
}
}


As you can see, I have the same rest parameter and the same trace() call.


For a better understanding here's an example piece of an instance of SubClassText:



var beserker:SubClassText = new SubClassText("beserker", "Beserker", stage, false,
warrior, "downCenter", 0, 0, "Beserkers are crazy strong fighters", warrior, "Beserker",
0, 15, 5, 10, 10, 10);


Then I can go into that SubClassText and trace its rest parameter length (setStatValues, I'm going to trace it from the fla document so for now I'm going to make that parameter public instead of protected):



trace(beserker.setStatValues.length); //5


Now here's an example of an instance of AllySubClassText:



var knight:AllySubClassText = new AllySubClassText("knight", "War: The Knight",
stage, false, warriors, "downCenter", 0, 0, "War is a strong Knight", warriors, "War",
"Knight", 0, 15, 5, 10, 10, 10);


Then when I trace the knight instance's rest parameter length:



trace(knight.setStatValues.length); //1


The example pieces were taken directly from my code, I just shortened the onHover string so it's easier to read. Sorry for the huge amount of inputs on the classes, UI code quickly took a lot of parameters to work correctly. I'm not sure why all inputs are being treated as one index rather than individual indexes. I even know it's doing this because here's what happens when I trace just the rest parameter:



trace(knight.setStatValues + ", " + knight.setStatValues.length); //15,5,10,10,10, 1


Any help would be greatly appreciated. It could be a minor oversight, but I'm stumped right now.


org.json.simple - How to iterate through individual objects in a JSONArray, and arrays within the individual objects?

Using the org.json.simple library, how can I iterate through a JSONArray, processing its individual objects and arrays inside the individual objects?


I have found answers on how to do this for different JSON libraries but in my situation I am required to use org.json.simple.


Here is an example of what the JSONArray i need to process looks like:





[
{
"versions":[
{
"rocket_version":"3.3.0.0",
"pluginVersion":"1.0.1.0",
"uploaded":1429350563,
"changelog":"<ul>\r\n\t<li>ADDED: anti-suicide.imune permission<\/li>\r\n<\/ul>",
"url":"https:\/\/dev.rocket.foundation\/wp-content\/uploads\/AntiSuicide3.zip"
},
{
"rocket_version":"3.3.0.0",
"pluginVersion":"1.0.0.2",
"uploaded":1429283276,
"changelog":"<ul>\r\n\t<li>FIXED: hopefully fixed the allocated memory (needs testing)<\/li>\r\n<\/ul>",
"url":"https:\/\/dev.rocket.foundation\/wp-content\/uploads\/AntiSuicide2.zip"
},
{
"rocket_version":"3.3.0.0",
"pluginVersion":"1.0.0.1",
"uploaded":1429196020,
"changelog":"<ul>\r\n\t<li>FIXED: small exception every time someone suicide.<\/li>\r\n<\/ul>",
"url":"https:\/\/dev.rocket.foundation\/wp-content\/uploads\/AntiSuicide1.zip"
},
{
"rocket_version":"3.3.0.0",
"pluginVersion":"1.0.0.0",
"uploaded":1428923374,
"changelog":"",
"url":"https:\/\/dev.rocket.foundation\/wp-content\/uploads\/AntiSuicide.zip"
}
],
"author":"ApokPT",
"name":"Anti-Suicide",
"id":910,
"development_stage":"Release",
"headline":"Anti-Suicide relocation",
"url":"https:\/\/dev.rocket.foundation\/?post_type=rplugin&#038;p=910"
},
{
"versions":[
{
"rocket_version":"3.3.0.0",
"pluginVersion":"1.0.0.0",
"uploaded":1429113571,
"changelog":"Updated needed libraries",
"url":"https:\/\/dev.rocket.foundation\/wp-content\/uploads\/ZaupWhitelist_1.0.0.02.zip"
},
{
"rocket_version":"3.3.0.0",
"pluginVersion":"1.0.0.0",
"uploaded":1429047352,
"changelog":"First release",
"url":"https:\/\/dev.rocket.foundation\/wp-content\/uploads\/ZaupWhitelist_1.0.0.01.zip"
}
],
"author":"Zamirathe",
"name":"Zaup Mysql Whitelist",
"id":929,
"development_stage":"Release",
"headline":"Whitelist in Mysql",
"url":"https:\/\/dev.rocket.foundation\/?post_type=rplugin&#038;p=929"
},
{
"versions":[
{
"rocket_version":"3.3.0.0",
"pluginVersion":"1.3.5.0",
"uploaded":1429284290,
"changelog":"<ul>\r\n\t<li>FIXED: Possible memory leak (needs testing);<\/li>\r\n\t<li>FIXED: Reactivated strip on give kit;<\/li>\r\n\t<li>ADDED: Cooldown check for permission givekit.onjoin.&lt;kitname&gt;<\/li>\r\n<\/ul>",
"url":"https:\/\/dev.rocket.foundation\/wp-content\/uploads\/GiveKit27.zip"
},
{
"rocket_version":"3.3.0.0",
"pluginVersion":"1.3.4.0",
"uploaded":1429192200,
"changelog":"<ul>\r\n\t<li>ADDED: givekit.onjoin.&lt;kit name&gt; permission<\/li>\r\n<\/ul>",
"url":"https:\/\/dev.rocket.foundation\/wp-content\/uploads\/GiveKit26.zip"
}
],
"author":"ApokPT",
"name":"Give Kit",
"id":858,
"development_stage":"Release",
"headline":"Give a Kit to another player or yourself",
"url":"https:\/\/dev.rocket.foundation\/?post_type=rplugin&#038;p=858"
}
]



Each individual object in the whole array has a versions array and an "id" attribute. For each individual object, I need to:



  1. Get the 'id' attribute's value

  2. Iterate through each object in the 'versions' array and get the value of its attributes, such as 'url', 'changelog', 'pluginVersion', etc.


For each object in each versions array, I just need to call a method that accepts the id attribute, and the url/changelog/pluginVersion attributes.


How can I do this task in Java with the org.json.simple library?


Shared Empty Arrays

Say I have utility class like this:



public class IntArrays
{
public static final int[] EMPTY = new int[0];

public static int[] empty() { return EMPTY; }

// ...
}


Is it save to distribute and re-use such a shared array with length 0, or should I get rid of the field and replace the method with



public static int[] empty() { return new int[0]; }

PHP/MySQL Sort Multi-dimensional array

I'm trying to sort an array in to a three-deep array. This is my current query:



SELECT * FROM question
INNER JOIN category ON question.category_id = category.id
INNER JOIN difficulty ON question.difficulty_id = difficulty.id


This works fine but how can I get this to be sorted in an array with 3 levels category.id -> difficulty.id -> question.*


Expected result is something like:



array(
'1' => array( // category id 1
'1' => array( // difficulty id 1
'1' => array('...'), // question id 1
'2' => array('...') // question id 2
),
'2' => array(
'3' => array('...'),
'4' => array('...')
)
)
)

Poker Program in c Programming

I've put together a program that deals out a hand poker perfectly. Now I want the program to realize when the hand that is dealt is straight, flush, pair, 3 of a kind, and 4 of kind. The program runs but never prints the right condition when needed to, I believe I have some placement or logic error that I can't find. Here's what I have so far.



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

#define SUITS 4
#define FACES 13
#define CARDS 52
#define HAND 5//draw only 5
#define TRUE 1//positive print condition
#define FALSE 0//negative print condition

//prototypes
shuffle( unsigned int wDeck[][FACES]);//shuffling modifies wDeck
deal(unsigned int wDeck[][FACES], const char *wFace[],
const char *wSuit[] );//dealing doesn't modify the arrays


//true/false conditions
typedef int bool;
bool straight, flush, four, three;
int pairs; //0,1, or 2



int main()
{
//initialize suit array
const char *suit[ SUITS ] =
{
"Hearts", "Diamonds", "Clubs", "Spades"
};

//initialize face array
const char *face[ FACES ] =
{
"Ace", "Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King"
};

int suitInHand[SUITS], facesInHand[FACES];

analyzeHand(suitInHand, facesInHand);

//initialize deck array
unsigned int deck[SUITS][FACES] = { 0 };

srand( time( NULL ) );//seed random-number generator

shuffle( deck );//shuffle the deck
deal( deck, face, suit );//deal the deck

}//end main

//shuffle cards in deck
shuffle( unsigned int wDeck[][FACES])
{
size_t row;//row number
size_t column;//column number
size_t card;//counter

//for each of the cards, choose slot of deck randomly
for( card = 1; card <= CARDS; ++card) {

//choose new random location until unoccupied slot found
do {
row = rand() % SUITS;
column = rand() % FACES;
}
while( wDeck[ row ][ column ] !=0);
//end do-while

//pace card number in chosen slot of deck
wDeck[ row ][ column ] = card;
}//end for
}//end function shuffle

//deal cards in deck
deal(unsigned int wDeck[][FACES], const char *wFace[],
const char *wSuit[] )
{
size_t card;//card counter
size_t row;//row counter
size_t column;//column counter

//deal each of the cards
for( card = 1; card <= HAND; ++card) {

//loop through rows of wDeck
for( row = 0; row < SUITS; ++row) {

//loop through column of wDeck for current row
for( column = 0; column < FACES; ++column) {

//if slot contains current card, display card
if( wDeck[ row ][ column ] == card ) {
printf("%5s of %-8s%c", wFace[ column ], wSuit[ row ],
card % 2 == 0 ? '\n' : '\t' );//2 column format
}//end if
}//end for
}//end for
}//end for
}//end function deal

analyzeHand(int suitsInHand[], int facesInHand[])
{
int num_consec = 0;
int rank, suit;

straight = FALSE;
flush = FALSE;
four = FALSE;
three = FALSE;
pairs = 0;

for (suit = 0; suit < SUITS; suit++)
if ( suitsInHand[suit] == 5)
flush = TRUE;

rank = 0;
while ( facesInHand[rank] == 0)
rank++;

for (; rank < FACES && facesInHand[rank]; rank++)
num_consec++;

if(num_consec == 5){
straight = TRUE;
return;
}

for(rank = 0; rank < FACES; rank++) {
if(facesInHand[rank] == 4)
four = TRUE;
if(facesInHand[rank] == 3)
three = TRUE;
if(facesInHand[rank] == 2)
pairs++;
}

if(four)
printf("Four of a kind\n");
else if(straight)
printf("Straight\n");
else if(pairs == 2)
printf("Two Pairs\n");
else if(pairs == 1)
printf("Pair\n");
else
printf("Better Luck Next Time\n");
}

2 dimensional arrays for loops statements java programming

I am trying to write a for statement that sums up the rows and columns of a 2 dimensional array one at a time, and determines if all the sums are the same. I have done the following, and I can't figure out what I am doing wrong.



public static int isMagic(int mat[][])
{
int row = mat.length;
int col = mat[0].length;
int sum = row + col;
if(row == col)
{
System.out.println("The matrix is a magic square.");
}
else
{
System.out.println("The matrix is not a magic square.");
}
return sum;
for(int sumR = 0; sumR < mat.length; sumR++)
{
int total = 0;
for(int sumC = 0; sumC < mat[sumR].length; sumC++)
{
total += mat[sumR][sumC];
if(sumR == 34 && sumC == 34)
{
System.out.println("The sum of all rows and columns is 34.");
}
else
{
System.out.println("The matrix is not a magic square.");
}
}
return total;
}
}


example of the matrix.


1 2 3 4 5 6 7 8 9


Swift Cannot invoke 'find' with an argument list of type '([Score], Score)' where Score is a struct

While find(["a", "b"], "c") works with no problems, I get an error when trying to find the index of a structure inside an array of structures:



struct Score
{
//...
}

var scores: [Score] = //...
var score: Score = //...

find(self.scores, score) // Error: Cannot invoke 'find' with an argument list of type '([Score], Score)'


I though it could be a problem with structures that can't be compared to each other by default. But changing Scores definition to class gives me the same error.


Javascript:: Validate duplicate(d) value(s) within array that contains key(s)

Before I will explain what my goal is let me start with my code:



var arr=['Hezi','Gangina','HeziGangina','Hezi-Gangina'];

function iUnique(v,i,s)
{
return s.indexOf(v)===i;
}

if(arr.length!==arr.filter(iUnique).length)
{

var arrayDup=
arr.filter(iUnique).filter
(
function(item,index)
{
return arr.indexOf(item)!==arr.lastIndexOf(item)
}
);

var dupVal=arrayDup.length;
throw new Error("Opps! Duplicate"+(dupVal>1?"d":"")+" value"+(dupVal>1?"s":"")+" : "+arrayDup);

}

arr.forEach(function(e)
{
document.writeln(e+"<br>");
});

arr=[];


Now,


Up until this point everything is working perfectly (no need to touch)...


BUT


I want to be able to append keys to my current array.


The array keys will be duplicated so there is no reason to validate duplicated values to the array keys.


IOW... I expect that :



var arr=[A:'Hezi',A:'Gangina',A:'HeziGangina',B:'Hezi-Gangina']; // This would NOT throw a new error.
var arr=[A:'Hezi',A:'Gangina',A:'HeziGangina',B:'Hezi']; // This WOULD throw a new error.


Here is the JSFiddle (I changed document.writeln to console.log):


http://ift.tt/1DzjPBK


So basically my goal is to keep the exact same proper functionality of my current code but at the same time I to be able to append keys to my current array.


I need fresh brain to take a look at this :)


Divide an array into Three parts

Problem Link:


http://ift.tt/1EdbMhl


Can someone explain me the editorial solution. I was able to solve it using dynamic programming. But I want to understand the editorial solution.


Editorial Solution:



#include<cstdio>
#include<cstdio>
#include<queue>
#include<cstring>
#include<vector>
#include<iostream>
#include<string>
#include<algorithm>
#include<fstream>
#include<sstream>
using namespace std;
typedef long long int int64;
int64 n,a[40],ans,vl;
void fn(int64 i,int64 j,int64 k,int64 ptr){
if(ptr==n){
vl = max(max(i,j),k);if(vl<ans)ans=vl;
}
else{
fn(i+a[ptr],j,k,ptr+1);
fn(i,j+a[ptr],k,ptr+1);
fn(i,j,k+a[ptr],ptr+1);
}
}
int main(){
//freopen("in3.txt","r",stdin);
//freopen("out3.txt","w",stdout);
int64 i,j,k,l,m,t,vl,fl;ans=1000000;
cin>>n;for(i=0;i<n;i++)cin>>a[i];
fn(0,0,0,0);
printf("%lld\n",ans);

return 0;
}

Fetch a javascript object from a website in Java [on hold]

I have a java program. I want to access a remote webiste and access an object which is between script tags. The object looks like this:



var anObject = {
"1": {
"1": {
"a": 1,
"b": -1,
"c": false,
"something": false,
"moresomething": [],
"evenmoresomething": {}
},
}}


But it is roughly 50 thousand lines long. How does one do it most efficiently? I looked at htmlUnit and thought about injecting javascript to the website and parsing it to json, which I can then easily create an array with in java, but I am not sure how would I do that.


Edit: Question has been marked as unclear, so I will try to ask again. There is a website, which holds certain game's map in javascript. If you access it through browser it displays a table with different values. If you access the site's source through browser, you can see the 50-thousand lines long javascript object holding all the values describing the map. Items laying in every zone, players which are in the zone, etc. What I want to do, is that I have an IRC bot, which I want to be able to access the map. I want it to be able to list buildings, items or just describe certain zones. I thought that manually iterating over whole object and converting it to a java array after somehow accessing the site's source is a bad way to do that. I thought about somehow simulating the behavior of a browser (which htmlUnit does) and injecting javascript which would convert the object to json, which I can then easily load back into java. Is this anyhow helpful? I am confused on how to describe my problem better.


Loop through a 2d array backwards

I need to loop through a 2d array backwards for a little map project I'm doing. I tried doing so based off of what I've read online, but my 2d array is different. How can I loop through this backwards?



for(int i = 0; i < map.length; i++)
for(int j = 0; j < map[i].length; j++) {
switch (nmap[j][i]) {
map[i][j] = new Tile();
}
}

Dice Rolling - ArrayOutofBounds

I am just starting with Java programming and wrote a program to roll an x-sided dice x-times. The sides and the number of rolls are defined by user input. The program gives out the absolute and relative frequencies of each number in a JTable format. Everything works well until you choose large numbers for the sides and number of rolls. I get an ArrayOutOfBoundsException but can't find any respective errors in the code.



package rolling;

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.JOptionPane;

public class RollDice extends JPanel {

private static final long serialVersionUID = -6332129624300946462L;
JTable jt;
int i, k, j; //Counter for loops

/*========== CONSTRUCTOR CREATES TABLE OBJECT ==========*/
public RollDice(int[] trial, int[] outcomes, int[] dice_numbers,
int[] count, float[] Rel_frequencies){

String[] columnNames = {"Number of trial", "Outcome", "Dice Numbers",
"Absolute Frequencies", "Relative Frequencies"};

Object[][] input = new Object[trial.length][columnNames.length];

for (i=0; i<trial.length; i++){
input[i][0] = trial[i];
}
for (i=0; i<outcomes.length; i++){
input[i][1] = outcomes[i];
}
for (i=0; i<dice_numbers.length; i++){
input[i][2] = dice_numbers[i];
}
for (i=0; i<count.length; i++){
input[i][3] = count[i];
}
for (i=0; i<Rel_frequencies.length; i++){
input[i][4] = Rel_frequencies[i];
}

/*Checking the outcome!
for (i=0; i<trial.length; i++){
System.out.println();
for (k=0; k<columnNames.length; k++){
System.out.printf("%d\t", input[i][k]);
}
}*/
jt = new JTable(input,columnNames)
{
/**
*
*/
private static final long serialVersionUID = 1L;

public boolean isCellEditable(int input, int columns)
{
return false;
}
public Component prepareRenderer(TableCellRenderer r, int input,
int columns){
Component c = super.prepareRenderer(r, input, columns);

if (input %2 == 0){
c.setBackground(Color.WHITE);
}
else{
c.setBackground(Color.LIGHT_GRAY);
}
if (isCellSelected(input, columns)){
c.setBackground(Color.YELLOW);
}
return c;
}
};

jt.setPreferredScrollableViewportSize(new Dimension(450, 600));
jt.setFillsViewportHeight(true);

JScrollPane jps = new JScrollPane(jt);
add(jps);
}

public static int[] roll_dice(int sides, int rolls){
int[] outcomes = new int[rolls];
int i; //Counter for accessing array position (element)
for (i=0; i<rolls; i++){
outcomes[i] = (int)(1 + Math.random() * sides);
}
return outcomes;
}

public static int[] Frequency_count(int[] outcomes, int sides){
int[] count = new int[sides];
int i;
int j, k = 0;
for(i=1; i<=sides; i++){
for(j=0; j<outcomes.length; j++){
if (outcomes[j] == i){
count[k]++;
}
}
//System.out.printf("%d \t %d\n",i, count[k]);
k++;
}
return count;
}

public static float[] Relative_frequencies(int[] count, int sides,
int rolls){
int i;
float[] Array = new float [sides];
for(i=0; i<sides; i++){
Array[i] = (float)count[i] / rolls * 100;
//String.format("%.3f", (float)Array[i]);
//System.out.printf("%d \t %.2f\n",i+1, Array[i]);
}
return Array;
}

public static void main(String[] args) {
/*=========USER INPUT via GUI: DECISION ON HOW MANY TIMES
THE DICE IS ROLLED===*
*========= AND HOW MANY SIDES THE DICE HAS ===*/

String fn = JOptionPane.showInputDialog("Enter the number of sides
of the dice");
String sn = JOptionPane.showInputDialog("Enter the number of rolls");

int sides = Integer.parseInt(fn); // number of sides
int rolls = Integer.parseInt(sn); // number of rolls

JOptionPane.showMessageDialog(null, "You rolled a " + sides + "
sided dice " + rolls + " times!", "User Input",
JOptionPane.INFORMATION_MESSAGE );

/*=========GENERATING RANDOM NUMBERS (ROLLING THE DICE) WITH
"roll_dice" method==========
*========= AND COUNTING THE NO. OF TRIALS ==========*/
int[] outcomes = roll_dice(sides, rolls);
int[] trial = new int[rolls];
int[] dice_numbers = new int[sides];

int i, k;
k = 1;
for(i=0; i<rolls; i++){
trial[i] = k;
//System.out.println(i + " " + k);
k++;
}
k = 1;
for(i=0; i<sides; i++){
dice_numbers[i] = k;
//System.out.println(i + " " + k);
k++;
}
/*=========COUNTING THE FREQUENCIES OF EACH NUMBER==========*/
//System.out.println("ABSOLUTE Frequencies plotted in FUNCTION:");
int[] count = Frequency_count(outcomes, sides);
//System.out.println("RELATIVE Frequencies plotted in FUNCTION:");
float[] Rel_frequencies = Relative_frequencies(count, sides, rolls);


/*=========CREATING A TABLE FORMAT WITH A JAVA
LIBRARY (JTABLE)==========*/
JFrame jf = new JFrame();
RollDice table1 = new RollDice(trial, outcomes, dice_numbers,
count, Rel_frequencies);
jf.setTitle("Absolute and Relative Frequencies of numbers for
an arbitrary Dice");
jf.setSize(500, 700);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(table1);
}
}

Construct array from binary search tree with recursion

I have written a class for a binary search tree and I now would like to even it out by placing all of the elements in a sorted array and then work my way from there. Since I have used a recursive function to print out the elements of the tree in inorder, I figured I could use a similar function to fill the array. I have found a method to do it using an ArrayList which is very similar to my function used to print the tree.



private void toArray(BinaryNode<E> n, ArrayList<E> a) {
if (n == null) return;
toArray(n.left, a);
a.add(n.element);
toArray(n.right, a);
return;
}


Now, I would prefer to fill an array and hence I have to keep track of the index of where to put the next element. I could use an attribute of type int to keep track of the index. However, since attributes should describe properties of the object, which an index-attribute doesn't, I would prefer to do it all using a recursive function. I've tried the following:



private int toArray(BinaryNode<E> n, E[] a, int index) {
if (n == null) return 0;
toArray(n.left, a, index);
a[index++] = n.element;
toArray(n.right, a, index);
return 0;
}


The function doesn't keep track of the index and only works for some special kinds of trees. However, I just can't figure out how I could solve this problem. I think a good way would be to return (index of last inserted element) + 1. I have tried drawing a few pictures but I'm stuck...


Read .txt file into a multi dimensional array in php

The example .txt data is:



20|Charlotte Aaaa|XXXX*SALE*O9
60|Peggy Bbbbb|XXXX*SALE*O8
25|Ashley Ccccc|XXXX*SALE*O7
103|Andrew Ddddd|XXXX*SALE*O1
51|Sally EEeee|XXXX*SALE*O6
9|Richard Fffff|XXXX*SALE*O3
23|Charlotte Aaaaaaaa|XXXX*SALE*O10
150|James Ggggggg|XXXX*SALE*O1
101|Connor Hhhhhhh|XXXX*SALE*O2
90|Barbara Iiiiiiii|XXXX*SALE*O2
23|Richard Ffffff|XXXX*DROP*O4
10|Holly Jjjjjjjj|XXXX*SALE*O5
90|Barbara Iiiiiii|XXXX*SALE*10


The code I currently have is:



$handle = fopen("lock.txt", "r");
if ($handle) {
$i=1;
while (($line = fgets($handle)) !== false) {
$data = explode("|", $line);
$locks = array($i, $data);
$i++;
var_dump($locks);

}
fclose($handle);
} else {
// error opening the file.
}


The output is currently:



array(2) { [0]=> int(1) [1]=> array(3) { [0]=> string(2) "20" [1]=> string(14) "Charlotte Aaaa" [2]=> string(14) "XXXX*SALE*O9 " } } array(2) { [0]=> int(2) [1]=> array(3) { [0]=> string(2) "60" [1]=> string(11) "Peggy Bbbbb" [2]=> string(14) "XXXX*SALE*O8 " } } array(2) { [0]=> int(3) [1]=> array(3) { [0]=> string(2) "25" [1]=> string(12) "Ashley Ccccc" [2]=> string(14) "XXXX*SALE*O7 " } } array(2) { [0]=> int(4) [1]=> array(3) { [0]=> string(3) "103" [1]=> string(12) "Andrew Ddddd" [2]=> string(14) "XXXX*SALE*O1 " } } array(2) { [0]=> int(5) [1]=> array(3) { [0]=> string(2) "51" [1]=> string(11) "Sally EEeee" [2]=> string(14) "XXXX*SALE*O6 " } } array(2) { [0]=> int(6) [1]=> array(3) { [0]=> string(1) "9" [1]=> string(13) "Richard Fffff" [2]=> string(14) "XXXX*SALE*O3 " } } array(2) { [0]=> int(7) [1]=> array(3) { [0]=> string(2) "23" [1]=> string(18) "Charlotte Aaaaaaaa" [2]=> string(15) "XXXX*SALE*O10 " } } array(2) { [0]=> int(8) [1]=> array(3) { [0]=> string(3) "150" [1]=> string(13) "James Ggggggg" [2]=> string(14) "XXXX*SALE*O1 " } } array(2) { [0]=> int(9) [1]=> array(3) { [0]=> string(3) "101" [1]=> string(14) "Connor Hhhhhhh" [2]=> string(14) "XXXX*SALE*O2 " } } array(2) { [0]=> int(10) [1]=> array(3) { [0]=> string(2) "90" [1]=> string(16) "Barbara Iiiiiiii" [2]=> string(14) "XXXX*SALE*O2 " } } array(2) { [0]=> int(11) [1]=> array(3) { [0]=> string(2) "23" [1]=> string(14) "Richard Ffffff" [2]=> string(14) "XXXX*DROP*O4 " } } array(2) { [0]=> int(12) [1]=> array(3) { [0]=> string(2) "10" [1]=> string(14) "Holly Jjjjjjjj" [2]=> string(14) "XXXX*SALE*O5 " } } array(2) { [0]=> int(13) [1]=> array(3) { [0]=> string(2) "90" [1]=> string(15) "Barbara Iiiiiii" [2]=> string(12) "XXXX*SALE*10" } }


What I would like to do is as follows, create an array which I can later use for an ajax search for the third part of each row


Therefore the array format would be



$locks[0][1] = 20
$locks[0][2] = Charlotte Aaaa
$locks[0][3] = XXXX*SALE*O9


I haven't looked at integrating ajax yet as I am failing at this. Any help would be appreciated.


nodejs loops and arrays

Hey everyone i cant seem to grasp the arrays function in nodejs and am having a few problems programming it to work the way i want


what i am doing is getting json info from an api and using that for the arrays.


i would like it formatted like so



array = [ { Coin:{Balance: 0, Available: 0, Pending: 0, Exchange: 0} ]


the output from the API looks like this



[ { Currency: 'BTC',
Balance: 3.0000000000000004e-8,
Available: 3.0000000000000004e-8,
Pending: 0,
CryptoAddress: '1G29t11ioGa5cmWJKLeanbNz1TA77eS1gK' },
{ Currency: 'DGB',
Balance: 0,
Available: 0,
Pending: 0,
CryptoAddress: 'DTcrZApNRDmq41bhcPcZdhhApaLQGr7nfj' }
] }


and the script im using to try and add them to a new array is





var redis = require('redis');
client = redis.createClient()

var bittrex = require('node.bittrex.api');
bittrex.options({
'apikey': 'KEY',
'apisecret': 'SECRET',
'stream': true,
'verbose': true,
'cleartext': true,
'baseUrl': 'http://ift.tt/1MiVHVL'
});


bittrex.getbalances(function(data) {
console.log(data);
array = [];
for (var coin in data.result) {
Name = data.result[coin].Currency;
array.push(Name);

array[Name].Balance.push(data.result[coin].Balance);

array[Name].Available.push(data.result[coin].Available);
array[Name].Pending.push(data.result[coin].Pending);


client.hget("Exchange_Rates", data.result[coin].Currency, function(err, exchange) {
array[Name].Exchange.push(exchange);
});

};

console.log(array);


for (var sell in array) {
bittrex.sendCustomRequest('http://ift.tt/1Hm0ciZ' + sell + '&quantity=' + array[Name].Available + '&rate=' + array[Name].Exchange, function(data) {
console.log(data);
}, true);
};


});



This is the current error returned

/home/alastair/cryptsy.js:22 array[Name].Balance.push(data.result[coin].Balance); ^ TypeError: Cannot read property 'Balance' of undefined at /home/alastair/cryptsy.js:22:12 at /home/alastair/node_modules/http://ift.tt/1G7fS8o at Stream.write (/home/alastair/node_modules/http://ift.tt/1Hm0cj1) at Stream.stream.write (/home/alastair/node_modules/http://ift.tt/1G7fR4g) at Stream.ondata (stream.js:51:26) at Stream.EventEmitter.emit (events.js:95:17) at drain (/home/alastair/node_modules/http://ift.tt/1Hm09Uu) at Stream.stream.queue.stream.push (/home/alastair/node_modules/http://ift.tt/1G7fR4i) at Parser.parser.onToken (/home/alastair/node_modules/http://ift.tt/1Hm09Uy) at Parser.proto.write (/home/alastair/node_modules/http://ift.tt/1G7fR4k)


Java object access overwriting previous entries

first question attempt here. Trying some interview preparation challenges on parenthesis logging - ie: log the open and close bracket positions of a string. I have tried to use a bracket object, to then use a single array with an open and close position at each entry. The conditions all seem to catch but then the array just duplicates the last results to all entries in the array. Any idea what I'm doing wrong? Have left the printing to screen for my attempts to debug this already and know I'm only considering the basic case so far with my algorithm. Thanks in advance.



class ParanthesisMatch {

static final char leftBracket = '(';
static final char rightBracket = ')';

public static void main(String[] args) {

String str = "(I (am (the) basic) case)";
char[] input = str.toCharArray();

int opens = 0;
int closes = 0;
int brackets = 0;

Bracket[] bracketArray = new Bracket[10];

System.out.println(input.length);

for (int i = 0; i < input.length; i++) {
System.out.println(input[i]);
if (input[i] == leftBracket) {
bracketArray[opens] = new Bracket();
System.out.println("Open trigger: " + i);
bracketArray[brackets].openBracket = i;
System.out.println("Open bracket is: " + bracketArray[opens].openBracket);
brackets++;
opens++;
}
if (input[i] == rightBracket) {
System.out.println("Close trigger: " + i);
bracketArray[brackets - closes].closeBracket = i;
System.out.println("Pos: " + (brackets - closes)
+ "Close bracket is: " + bracketArray[brackets - closes].closeBracket);
closes++;
}
}

for (int i = 0; i < brackets; i++) {
System.out.println("Bracket: " + i + " Open is " + bracketArray[i].openBracket + ", Close is " + bracketArray[i].closeBracket);
}
}
}

class Bracket {

public static int openBracket;
public static int closeBracket;

Bracket() {
openBracket = 0;
closeBracket = 0;
}

public void setOpen(int open) {
this.openBracket = open;
}

public void setClose(int close) {
this.closeBracket = close;
}
}

Arrays on a class

I want to insert variables in a integer array on this class This is the website


And i would like to know if is possible because every time i get an error and i try to set and a get some variables but nothing works


this is the part that i want to insert into a int array and then print it



if(processNow.getBurstTime()==1)
{
System.out.println(processNow.getName()+" executed from: "+startProcessing+"--> "+Time );


// here i want to have my array for example like
//int[] startTime2 = new int[];
//startTime2[]=startProcessing;


startProcessing=Time;
inQueue.remove(0);
}


It would be of great help


Sort bidimentional numpy array

The numpy arrays symbols and ocurrence both have the same size/len.



bidimentional_array = np.array([symbols,occurrence])


What I want is, do a descending sort in ocurrence and make it so that symbols index will change in function of the sort. What's the most effective way?


How can I add data from a file inside a vector in Java?

First of all, I am programming in Java. I am doing a program that can manage a few vehicles and clients data for a small car rent Shop. It's a basic program since I am only in my 1st year of Computer Engeneering. My problem is that the information about the clients is in a text file. I already have a method that reads this information but I don't know how to add it to a vector so it is stored and ready to be invoked by another method for it's use. If someone could help me it would be great! Thank you all.


NUnit. Using the 'TestCase' attribute and two dimensional array

I'm using NUnit and trying to implement tests for the following method: It should accept two integers and returns two dimensional array. So, header of my test looks like:



[TestCase(5, 1, new int[,]{{1}, {2}, {3}, {4}, {5}})]
public void MyTestMethod(int a, int b, int[][] r)


During compilation I've got the following error:



Error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type (CS0182)



Do we have any ways how to do that without applying the following: How do I put new List<int> {1} in an NUNIT TestCase?


jQuery Autocomplete, 3 values or more

I have a very basic html with jQuery and jQuery UI, I'm using the autocomplete function, so far so good, the problem is that I have an array with 3 values each block something like:



Array
(
[0] => stdClass Object
(
[product_id] => 5
[product_number] => AGD-ACRBD001
[product_name] => Title 1
)

[1] => stdClass Object
(
[product_id] => 6
[product_number] => AGD-ACRBD002
[product_name] => Title 6
)

[2] => stdClass Object
(
[product_id] => 7
[product_number] => AGD-ACRBD003
[product_name] => Title 34
)
)


So that is my array, with that array I only need the [product_number] to build my array for the auto complete, that is NOT a problem, the problem is that how do I use the other values when the [product_number] has been selected?... the HTML is as follow:



<form>
<input type="text" id="ids" name="ids" placeholder="Product ID">
<input type="text" id="codes" name="codes" placeholder="Code">
<input type="text" id="names" name="names" placeholder="Names">
</form>


So when a user type something on id="codes" it displays the list of codes that is extracted from the array value [product_number], that is working... what I do not know is how do I add the value to id="ids" and id="names" after the selection from the list... the jQuery for the autocomplete is:



(function($) {
$(function() {
var availableTags = [
"AGD-ACRBD001",
"AGD-ACRBD002",
"AGD-ACRBD003"
];
$("#codes").autocomplete({
source: availableTags
});
});
})(jQuery);

AngularJS orderBy - crazy Array.prototype.sort behaviour in Chromium browsers - Cannot clear sort

There is something that drives me nuts in a project of mine.


I have some code pretty similar to this (I have tried to make it as similar to mine as possible, with all the JS files I use, etc, but the code in this Plnkr doesn't seem to matter anyway as you will see because I cannot reproduce it there...): http://ift.tt/1O2SDDi


My issue is that when I set predicate='' the sorting is not 100% cleared. Angular seemed to change the order of my elements like that (this picture is with predicate=''):


enter image description here


When I removed the orderBy, everything was in its order (like it was serverd from my repository). After trying millions of different things with orderBy I could not make it clear the sort entirely.


I have found this case that had some similarities to mine: AngularJS ngRepeat orderBy in Chrome, but it turns out that my case is not related to that issue.


I am a patient guy, so I went into the angular.js file (AngularJS v1.3.15) and started debugging. This is the most crucial line:



return slice.call(array).sort(reverseComparator(comparator, reverseOrder));


Up until slice.call(array) the array is well ordered. When sort was executed the result was wrong. So I did this:



function comparator(o1, o2) {
for (var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0){
console.log(7); // <---------------------
return comp;
}
}
console.log(0); // <---------------------
return 0;
}

function reverseComparator(comp, descending) {
return descending
? function(a, b) {return comp(b,a);}
: comp;
}


And guess what: All I get in my console when the predicate='' is zeros. Also, typing :



slice.call(array).sort


...returns:



function sort() { [native code] }


So, I have no idea why this sorting happens. And it seems that it only happens in Chromium-based browsers (I have tried Chrome and Opera). FF and IE11 clear the sort as expected.


Now, I would think that this was a Chromium bug, but I still haven't managed to reproduce it in that Plnkr and I wonder why (perhaps something different in the data?)...


I have also tried disabling my Chrome extensions, but that didn't seem to make a difference either.


Chromium and Angular are both famous now. Has anyone else noticed this before?


Does anyone have ANY idea what's wrong here?


UPDATE:


OK. I think I have managed to reproduce it by adding more items to my array. See here: http://ift.tt/1O2SDDi


(party time! :D)


I'm gonna go and report it to the Angular team. They're Google. They might fix Chromium as well. :D