dimanche 28 juin 2015

Populate a JCombo Box with each element of Array in Java

Please forgive me, I'm new to Java.

Basically I'm trying to display every element of an Array (i.e. peopleInfo[0], peopleInfo[1], and peopleInfo[2] ) into a JComboBox. I have added elements to the Array from a text file. However when I try to display the elements of the array in the JComboBox only the first element is displayed which is not what I want.

I have attempted to correct this by using a for loop however when I did this it didn't seem to correct my problem however I don't know whether I coded it correctly.

My code currently is:

private JComboBox mainComboBox;
private JComboBox subComboBox;
private Hashtable subItems = new Hashtable();

public SplitFile() throws FileNotFoundException, IOException
{

    BufferedReader bReader = new BufferedReader(new FileReader("organisms.txt"));

    bReader.readLine(); // this will read the first line


    String line = null;
    while ((line = bReader.readLine()) != null){

        //removes the first space 
        String test = line.replaceFirst("\\s+", "");

        //used regex lookaround to split wherever there are 3 capital letters present, or where any of the tree are present
        String[] peopleInfo = test.split("(\\p{Upper}(?=\\p{Upper})\\p{Upper}\\p{Upper})|(?=Chromalveolata)|(?=Metazoa)|(?=Mycetozoa)|(?=Viridiplantae)|(?=Viruses)|\\;");

        //creates arrays for id, organism and tree
        String id = ">" + peopleInfo[0];
        String organism = peopleInfo[1];
        String tree = peopleInfo[2].replaceAll(";", "").replaceAll("\\d+.*", "");
       System.out.println(tree);
       ArrayList<String> testArray = new ArrayList<String>();
    String[] items = { tree , "Color", "Shape", "Fruit" };


    mainComboBox = new JComboBox( items );
    mainComboBox.addActionListener( this );

    getContentPane().add( mainComboBox, BorderLayout.WEST );

    //  Create sub combo box with multiple models

    //this code displays values dependent on what element is selected from the mainComboBox

    subComboBox = new JComboBox();
    subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
    getContentPane().add( subComboBox, BorderLayout.EAST );

    String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
    subItems.put(items[1], subItems1);

    String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
    subItems.put(items[2], subItems2);

}}

@Override
public void actionPerformed(ActionEvent e)
{
    String item = (String)mainComboBox.getSelectedItem();
    Object o = subItems.get( item );

    if (o == null)
    {
        subComboBox.setModel( new DefaultComboBoxModel() );
    }
    else
    {
        subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
    }
}

Any help would be much appreciated!

Thanks :)

How do I find all word combinations that add up to a certain length?

I need a little help with coming up with an algorithm to traverse through a sorted word array and finding all the possible combinations that add up to a certain length. Any help is greatly appreciated! Thanks :)

Fast array manipulation based on element inclusion in binary matrix

For a large set of randomly distributed points in a 2D lattice, I want to efficiently extract a subarray, which contains only the elements that, approximated as indices, are assigned to non-zero values in a separate 2D binary matrix. Currently, my script is the following:

lat_len = 100 # lattice length
input = np.random.random(size=(1000,2)) * lat_len
binary_matrix = np.random.choice(2, lat_len * lat_len).reshape(lat_len, -1)

def landed(input):
    output = []
    input_as_indices = np.floor(input)
    for i in range(len(input)):
        if binary_matrix[input_as_indices[i,0], input_as_indices[i,1]] == 1:
            output.append(input[i])
    output = np.asarray(output)
    return output   

However, I suspect there must be a better way of doing this. The above script can take quite long to run for 10000 iterations.

Add value in specific index array

i have array data like this.

[0] => Array (
    [id] => 1
    [id_requestor] => 1
    [jam_input] => 2015-06-20 06:00:00
    [jam_pakai] => 2015-06-28 08:00:00
    [total_poin] => 30
    )
[1] => Array (
    [id] => 2
    [id_requestor] => 2
    [jam_input] => 2015-06-20 07:00:00
    [jam_pakai] => 2015-06-28 08:00:00
    [total_poin] => 10
    )
[2] => Array (
    [id] => 3
    [id_requestor] => 3
    [jam_input] => 2015-06-20 06:30:00
    [jam_pakai] => 2015-06-28 08:00:00
    [total_poin] => 5
    )

In above data, there is total_poin. This total_poin that i use later. I want to sort total_poin array descending. But i wont to use php built in array function. Cause i have to use method from research paper like this.

for i=0 to i<main queue.size
   if jobi+1 length > jobi length then
    add jobi+1 in front of job i in the queue
end if
   if main queue.size = 0 then
    add job i last in the main queue
end if

And here is my implementation :

function LJFAlgorithm($time_str) {
        $batchData = getBatch($time_str);

        $ljf = [];
        for ($i=0; $i < count($batchData)-1; $i++) { 
            echo $batchData[$i+1]['total_poin'] ." >= ". $batchData[$i]['total_poin'] . " = " . ($batchData[$i+1]['total_poin'] >= $batchData[$i]['total_poin']);

            if ($batchData[$i+1]['total_poin'] >= $batchData[$i]['total_poin']) {
                echo ", Add " . $batchData[$i+1]['total_poin'] . " in front of " . $batchData[$i]['total_poin'];
            } else {
                echo ", Add " . $batchData[$i]['total_poin'] . " in front of " . $batchData[$i+1]['total_poin'];
            }

            echo '<br/>';
        }

        print_r($ljf);
    }

But it not work perfectly, i get one data missing. Here is my output code :

10 >= 30 = , Add 30 in front of 10
5 >= 10 = , Add 10 in front of 5

5 value not added in array. How to fix that?

Thank you very much.

How to sum two dimensional arrays in Java?

I've created a short code to practice two-dimensional arrays but I've stumbled upon a problem that I can't solve in my code. Hope you guys can help me.

Desired Output:

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

But instead I'm seeing this:

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 12

______________________________________________________

It's adding up every number that I input instead of just adding three numbers in each iteration. Please check the code below:

PART I

package Test;

 public class Test1 {
   private int[][] number;
   private int number1;
   public Test1(int[][]n){
      number = new int[2][3];
    for(int dx = 0;dx < number.length;dx++){
        for(int ix = 0;ix < number[dx].length;ix++){
            number[dx][ix]=n[dx][ix];
        }

    }
}

public Test1(int n){
    number1 = n;
}

public int getTotal(){
    int total = 0;

    for(int dx = 0;dx < number.length;dx++){
        for(int ix = 0;ix < number[dx].length;ix++){
            total += number[dx][ix];
        }

    }

    return total;
}

public int getNumbers(){

    return number1;
}

}

PART II

  package Test;
  import java.util.Scanner;
  public class TestMain {
  public static void main(String[]args){
    final int DIVS = 2;
    final int NUM_INSIDE = 3;
    Test1[][] t1 = new Test1[DIVS][NUM_INSIDE];
    int[][]numbers = new int[DIVS][NUM_INSIDE];
    getValues(numbers,DIVS,NUM_INSIDE,t1);

}

public static void getValues(int[][]numbers,int DIVS,int NUM_INSIDE,Test1[][] t1){
    Scanner hold = new Scanner(System.in);
    int num;
    for(int div = 0;div < DIVS;div++){
        for(int ins = 0;ins < NUM_INSIDE;ins++){
            System.out.print("Enter number:");
            numbers[div][ins]=hold.nextInt();
            num = numbers[div][ins];
            t1[div][ins] = new Test1(num);

        }
        Test1 t = new Test1(numbers);
        display(t,t1,div);

    }
}

public static void display(Test1 t,Test1[][] t1,int div){
    System.out.print("****************************\n");
    System.out.print("NUMBERS THAT YOU ENTERED:\n");

    for(int y = 0; y < t1[div].length;y++){
        System.out.print(t1[div][y].getNumbers() + "\n");
    }

    System.out.print("****************************\n");
    System.out.print("TOTAL: " + t.getTotal() + "\n");
    System.out.print("****************************\n");
}
}

Remove subarray from array when one of it's value match another arrays value (PHP)

I have two arrays:

$to_import = Array(
  [0] => Array(['native_id'] => 35339920, ['type'] => product)
  [1] => Array(['native_id'] => 22045872, ['type'] => product)
  [2] => Array(['native_id'] => 25913185, ['type'] => profile)
  [3] => Array(['native_id'] => 14354407, ['type'] => profile)
)

$existing = Array(
  [0] => Array(['native_id'] => 22045872)
  [1] => Array(['native_id'] => 25913185)
  [2] => Array(['native_id'] => 30836971)
)

I need to remove the record from the first array when the id is found in the second array, and when type matches 'profile'. So in this example, three remain:

$to_import = Array(
  [0] => Array(['native_id'] => 35339920, ['type'] => product)
  [1] => Array(['native_id'] => 22045872, ['type'] => product)
  [3] => Array(['native_id'] => 14354407, ['type'] => profile)
)

I have found similar questions, but I can't work out how to apply them to my requirements. This answer looks like it is close to what I want, but I can't get it to work, my knowledge is failing me.

Splitting NSString doesn't work in Swift

I have a long string i need split into an array by splitting when "|||" is found

I can split a String using two ways i found at SO

First one is this

 func split(splitter: String) -> Array<String> {
    let regEx = NSRegularExpression(pattern: splitter, options: NSRegularExpressionOptions(), error: nil)!
    let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
    let modifiedString = regEx.stringByReplacingMatchesInString (self, options: NSMatchingOptions(),
        range: NSMakeRange(0, count(self)),
        withTemplate:stop)
    return modifiedString.componentsSeparatedByString(stop)
}

Second one is this

var splt = str.componentsSeparatedByString("[\\x7C][\\x7C][\\x7C]")

I tried using the delimiter as both "[\x7C][\x7C][\x7C]" and "|||" and i tried using both String and NSString

Nothing seems to work though, i just get an array with the original string in it

Bash: Is ${@:2} the same as $2?

Is ${@:2} the same as $2 in Bash when my second argument is an array? My script does work with ${@:2} replaced by $2, but is there any downside?

Steve

Creating large arrays in Swift

I have an array in Swift that has 1000+ strings inside it. I am getting an error that looks like this: Command failed due to signal: Segmentation fault: 11

Is there a place I can store a lot of strings in a way that won't break xcode, and if there is, how do I put them in and get the strings from it?

Take sentence from user input with C

I wana take input from user and then print, I think I should also allocate memory could someone show me how to do that properly?

Here is my try:

    int days = 1;
    char * obligation[1500];
    char * dodatno[1500];

    puts("Enter nuber of days till obligation:\n");
    scanf(" %d", &days);
    puts("Enter obligation:\n");
    scanf(" %s", obligation);
    puts("Sati:\n");
    scanf(" %s", dodatno);

printf("%s|%s|%s \n",days,obligation,dodatno);

Alternative for #subList() for String array?

So I modified an API (for command management) to use String[] instead of a list of Strings.

My problem is here:strings.subList(1, strings.length) So I need to change this to a different alternative that would do the same job.

What exactly could I do here?

Why doesn't byte[] b = new byte[8](); work? [duplicate]

I already know that byte[] b = new byte[8]; works fine. But why doesn't byte[] b = new byte[8]; work?

For example, byte b = new byte(); works fine, so an array style also should work but it doesn't. I have no exact idea of this reason. Could someone please explain?

AS3: hitTestObject turning up null for no apparent reason

I'm currently coding a game, and in one part of the code, it's checking to see if the player is close enough to a monster in mArray for its health bar to appear. I use hitTestObject for this with var i incrementing to go through the list. However, I will randomly get this error message:

TypeError: Error #2007: Parameter hitTestObject must be non-null.

After seeing this for the first time, I put the test all under the conditional if (mArray.length > 0) to make sure the Array() was filled before even attempting the test... but it still occurs at random times. I even used trace(i) to see if it happened on a certain part of the list, but it's completely random each debug session! I know the player portion can't be null since it is on the screen at all times during the hitTest, so I'm at a loss for words right now.

The portion of code in question (nothing else is related to this except for the use of mArray[i] in different places):

for (var i:int = 0; i < mArray.length; i++) {
    if (mArray.length > 0) {

        trace(i); //my attempt to see if it occurred at a specific incrementation of i

        if (player.hitTestObject(mArray[i])) {
            mArray[i].healthBar.visible = true;
        } else {
            mArray[i].healthBar.visible = false;
        }

    }
}

Again, it works perfectly for everything all of the time except for random cases it gives me the TypeError. Is this just a hiccup in my code, is there some obvious problem that I'm overlooking, or does the code just like to throwback to 2007?

EDIT: The debug session ALWAYS points to the line with if (player.hitTestObject(mArray[i])).

The left hand side must be a variable (ArrayList and Array)

I'm a little confused between an ArrayList and an Array, I understand what a variable is but I don't understand why I can't convert the ArrayList to an Array and have the same effect.

This piece of code I currently have when using an ArrayList

import java.util.Objects;

import com.google.gson.Gson;
import com.google.gson.JsonObject;


public final class NpcDefinitionLoader extends JsonLoader {

    /**
     * Creates a new {@link NpcDefinitionLoader}.
     */
    public NpcDefinitionLoader() {
        super(DefinitionEditor.fileChooser.getSelectedFile().getAbsolutePath());
    }

    @Override
    public void load(JsonObject reader, Gson builder) {
        int index = reader.get("id").getAsInt();
        String name = Objects.requireNonNull(reader.get("name").getAsString());
        String description = Objects.requireNonNull(reader.get("examine").getAsString());
        int combatLevel = reader.get("combat").getAsInt();
        int size = reader.get("size").getAsInt();
        boolean attackable = reader.get("attackable").getAsBoolean();
        boolean aggressive = reader.get("aggressive").getAsBoolean();
        boolean retreats = reader.get("retreats").getAsBoolean();
        boolean poisonous = reader.get("poisonous").getAsBoolean();
        int respawnTime = reader.get("respawn").getAsInt();
        int maxHit = reader.get("maxHit").getAsInt();
        int hitpoints = reader.get("hitpoints").getAsInt();
        int attackSpeed = reader.get("attackSpeed").getAsInt();
        int attackAnim = reader.get("attackAnim").getAsInt();
        int defenceAnim = reader.get("defenceAnim").getAsInt();
        int deathAnim = reader.get("deathAnim").getAsInt();
        int attackBonus = reader.get("attackBonus").getAsInt();
        int meleeDefence = reader.get("defenceMelee").getAsInt();
        int rangedDefence = reader.get("defenceRange").getAsInt();
        int magicDefence = reader.get("defenceMage").getAsInt();

        NPCDefinitions.definitions.get(index) = new NPCDefinitions(index, name, description, combatLevel, size, attackable, aggressive, retreats,
            poisonous, respawnTime, maxHit, hitpoints, attackSpeed, attackAnim, defenceAnim, deathAnim, attackBonus, meleeDefence,
            rangedDefence, magicDefence);
    }
}

I get an error here

NPCDefinitions.definitions.get(index) = new NPCDefinitions(index, name, description, combatLevel, size, attackable, aggressive, retreats,
        poisonous, respawnTime, maxHit, hitpoints, attackSpeed, attackAnim, defenceAnim, deathAnim, attackBonus, meleeDefence,
        rangedDefence, magicDefence);

Saying the left side must be a variable. When I use an Array like this

NPCDefinitions.definitions[index] = new NPCDefinitions(index, name, description, combatLevel, size, attackable, aggressive, retreats,
        poisonous, respawnTime, maxHit, hitpoints, attackSpeed, attackAnim, defenceAnim, deathAnim, attackBonus, meleeDefence,
        rangedDefence, magicDefence);

Code works perfect.

I'm confused about this, how would I make this work by using an ArrayList?

Parse object containing array elements

I have a Parse object called Recipes and a column called ingredients, which is an array. I want to query my object list and retrieve a recipe based on some ingredients that I select.

If I use the whereKey:containsAllObjectsInArray: message on the query object, I will get recipes with more ingredients. Also, whereKey:containedIn: does not solve my problem. The retrieved objects should have an array of ingredients containing all my selected ingredients or only some of them. It should never have more ingredients than those I've selected.

Any ideas?

Cannot Assign Converted Value To Array

I would like to assign the integer value which is included in a string to an array.

The code:

int s[10][10];
string line="1asd";
char z=line[0];
s[0][0]=z-'0';

Error:

  `Invalid types 'char[int]' for array subscript`

How to declare a static array with variable length in delphi?

I need an array, that is optimized for one-time-initialization at runtime, with a given length. So memory should be allocated at runtime, but I don't need to change its length.

Is there a array-type other than the pure dynamic array? (it seems to be not the optimal choice for this task)

Bonus would be, if the initialized array is indexable via pointer-iteration, so all it's elements are allocated consecutive in memory.

Is this all just a daydream of a non-experienced programmer, or is there a possibility to achieve this?

I could imagine to do this with manual memory allocation, but maybe there's another way.

Binding a generic list with knockout.js in MVC5

I am using knockout.js to display the amount of articles I have in my shopping cart. The shopping cart information are saved in a List of the Model ShoppingCartItem. Because I did not read about a way to bind a list with knockout.js directly I am pushing my list items into an array and bind this array afterwards.

But no matter what I am trying the output is always "You have Articles in your shopping cart.". So the length of my array is not displayed.

I added knockout.js in the bundle config file:

bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                        "~/Scripts/knockout-3.3.0.js"));

            bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                        "~/Scripts/knockout-3.3.0.debug.js"));

            bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                        "~/Scripts/knockout.validation.js"));

            bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                        "~/Scripts/knockout.validation.debug.js"));

My view Model ShoppingCartItem:

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

namespace OnlineShop.Models
{
    public class ShoppingCartItem
    {
        public Products product { get; set; }
        public int amount { get; set; }
    }
}

My partial view where I want to use model binding with knockout.js:

@model List<OnlineShop.Models.ShoppingCartItem>

<script type="text/javascript">
    var myArray = [];

    @foreach (var d in Model)
    {
        @:myArray.push("@d");

    }

    var viewModel = {
        cartItems: ko.observableArray(myArray)
    };

    ko.applyBindings(cartItems, document.getElementById("test"));
</script>

<div id="top-cart" class="clearfix">
    <div class="shoppingcart-txt">
        @if (Model != null && Model.Count() > 0)
        {
            double sum = 0.0F;

            for (int i = 0; i < Model.Count(); i++)
            {
                sum = sum + (Model[i].amount * Model[i].product.PurchasePrice);
            }

            <p>
                You have <span id = "test" data-bind="text: cartItems().length">&nbsp;</span> articles in your shopping cart. <br /> 
                <strong>
                    Sum: @sum.ToString("#,##0.00") EUR <br />
                    excl. 3.00 EUR shipping costs
                </strong> 
            </p>
        }
        else
        {
            <p>
                You have no articles in your shopping cart.



            </p>
        }
    </div>
    <div class="shoppingcart-img">
        <a href="@Url.Action("ShoppingCart", "Home")">
            <img src="~/Photos/shoppingcart.png" alt="" border="0" />
        </a>
    </div>
</div>

I also tried to apply the bindings with the following:

ko.applyBindings(cartItems, document.body);

With the same result. The length of my array is not displayed.

I would really appreciate if anyone can tell me what I am doing wrong.

How to get checkbox value in angularjs?

I have a 10(or n)checkbox in my ng-view. Now I would like to ask here that What is the most efficient or simple way to check if checkbox is checked and if checked get the value of checkbox.

<ul>
  <li ng-repeat="album in albums">
   <input type="checkbox" ng-model="folder.Selected" value={{album.name}} />
   </li>
  </ul>

I have ng-controller(getAlbumsCtrl), in that I have an array in which I want to push all the checkedbox albums names into albumNameArray

2D MATRIX statement for 5 x 5 Grid

Given a 5 x 5 Grid comprising of tiles numbered from 1 to 25 and a set of 5 start-end point pairs. For each pair,find a path from the start point to the end point. The paths should meet the below conditions:

a) Only Horizontal and Vertical moves allowed.

b) No two paths should overlap.

c) Paths should cover the entire grid

Input consist of 5 lines. Each line contains two space-separated integers,Starting and Ending point.

Output: Print 5 lines. Each line consisting of space-separated integers,the path for the corresponding start-end pair. Assume that such a path Always exists. In case of Multiple Solution,print any one of them.

Sample Input

1 22

4 17

5 18

9 13

20 23

Sample Output

1 6 11 16 21 22

4 3 2 7 12 17

5 10 15 14 19 18

9 8 13

20 25 24 23

Split String into Array of Words to find Longest

I am working on a task to search any given string for the longest word. I am thinking the ideal way to do this is to split the string into an array consisting of each word then looping through that array and comparing each length to return the longest. I am stuck on just separating the string into an array of words. The questions I have seen answered similar in topic seem to use much to complicated methods for such a simple task. I am looking for help on a beginner level as this is my first time incorporating regular expressions into my code.

function findLongestWord(str) {
     str = str.toLowerCase().split("/\w+");
     return str;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

Pass a string into an array PHP

I have list of strings like this:

'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110 CL68035 release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'

It looks like elements of an array, But when i use

<?php
    $string = "'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110 CL68035 release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'";
    $arr = array($string);
    print_r($arr);

 ?>

It doesnt work as I want:

Array ( [0] => 'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110 CL68035 release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys')

Instead of:

Array ( [0] => PYRAMID, [1] => htc_europe, [2] => htc_pyramid, ...

I dont want to use explode() because my strings are already in array format and many strings have the ',' character. Please help me, thanks.

Making a quick padding/margin library with loops + arrays in Less

I'm trying to understand the loop and array function in Less (css). But it seems like I can't find any good tutorials on the topic.

More specifically, I'm trying to code a quick padding- & margin class library for Bootstrap 3 using Less. The coder should only change som global variables and the library will rebuild the padding/margin functionality. I want the padding/margin to be responsive. Giving a more spaciesh design on big devices, and not so spaciesh on smaller devices.

I know that the current code is extremly repetitive and will, if I expand it to every device, an extremely long document with code, that isn't gracies nor giving an outside coder a good overview of the function.

So, what can I do to minimize the code into smaller loops and arrays?

//Global variables for space calculation in a mixin
// Variables for padding and margin sections - also refered to as mixin-space-value
   @base-top-space: 100px;
 @base-right-space: 100px;
@base-bottom-space: @base-top-space;
  @base-left-space: @base-right-space;

// Variables for different Types of sizes of space - also refered to in mixin-space as @mixin-space-size
 @space-small:      0.75;
@space-medium:      1;
 @space-large:      1.75;
@space-xlarge:      2.5;

// Variables for different types of devices - also refered to in mixin-space as @mixin-space-device
@space-xs:  0.5;
@space-sm:  1;
@space-md:  1.25;
@space-lg:  1.5;

//Variables of types of space in mixin
// Padding
@space-type-padding-top:    escape('padding:');
@space-type-padding-top:    escape('padding-top:');
@space-type-padding-right:  escape('padding-right:');
@space-type-padding-bottom: escape('padding-bottom:');
@space-type-padding-left:   escape('padding-left:');

// Margin
@space-type-margin:         escape('margin:');
@space-type-margin-top:     escape('margin-top:');
@space-type-margin-right:   escape('margin-right:');
@space-type-margin-bottom:  escape('margin-bottom:');
@space-type-margin-left:    escape('margin-left:');



// Mixin of padding space
// mixin-space-type: eg. padding-top, margin-right...
// 
//      Local variables         Global variables:
//      ===============         ================
// Eg.: mixin-space-type    =   @space-type-padding-top
// Eg.: mixin-space-value   =   @base-top-space
// Eg.: mixin-space-size    =   @space-small, @space-medium, @space-large, @space-xlarge
// Eg.: mixin-space-device  =   @space-xs, @space-sm, @space-md, @space-lg

.mixin-space(@mixin-space-type, @mixin-space-value, @mixin-space-size, @mixin-space-device) {
    @mixin-space-type abs(@mixin-space-value * @mixin-space-size * @mixin-space-device);
}



// The following media queries beloow generates different types of padding sizes.
//    Top: .pad-top-s,      .pad-top-m,     .pad-top-l,     .pad-top-xl
//  Right: .pad-right-s,    .pad-right-m,   .pad-right-l,   .pad-right-xl
//   Left: .pad-left-s,     .pad-left-m,    .pad-left-l,    .pad-left-xl
// Bottom: .pad-bottom-s,   .pad-bottom-m,  .pad-bottom-l,  .pad-bottom-xl

// The following media queries beloow generates different types of margin sizes.
//    Top: .mar-top-s,      .mar-top-m,     .mar-top-l,     .mar-top-xl
//  Right: .mar-right-s,    .mar-right-m,   .mar-right-l,   .mar-right-xl
//   Left: .mar-left-s,     .mar-left-m,    .mar-left-l,    .mar-left-xl
// Bottom: .mar-bottom-s,   .mar-bottom-m,  .mar-bottom-l,  .mar-bottom-xl

@media (max-width: @screen-xs-max) {
    .lg-md-content-margin {
        margin-top: 0px;
    }

    .pad {
        &-top {
            &-s {
                .mixin-space(@space-type-padding-top, @base-top-space, @space-small, @space-xs);
            }

            &-m {
                .mixin-space(@space-type-padding-top, @base-top-space, @space-medium, @space-xs);
            }

            &-l {
                .mixin-space(@space-type-padding-top, @base-top-space, @space-large, @space-xs);
            }

            &-xl {
                .mixin-space(@space-type-padding-top, @base-top-space, @space-xlarge, @space-xs);
            }
        }

        &-bot {
            &-s {
                .mixin-space(@space-type-padding-bottom, @base-bottom-space, @space-small, @space-xs);
            }

            &-m {
                .mixin-space(@space-type-padding-bottom, @base-bottom-space, @space-medium, @space-xs);
            }

            &-l {
                .mixin-space(@space-type-padding-bottom, @base-bottom-space, @space-large, @space-xs);
            }

            &-xl {
                .mixin-space(@space-type-padding-bottom, @base-bottom-space, @space-xlarge, @space-xs);
            }
        }

        &-right {
            &-s {
                .mixin-space(@space-type-padding-right, @base-right-space, @space-small, @space-xs);
            }

            &-m {
                .mixin-space(@space-type-padding-right, @base-right-space, @space-medium, @space-xs);
            }

            &-l {
                .mixin-space(@space-type-padding-right, @base-right-space, @space-large, @space-xs);
            }

            &-xl {
                .mixin-space(@space-type-padding-right, @base-right-space, @space-xlarge, @space-xs);
            }
        }

        &-left {
            &-s {
                .mixin-space(@space-type-padding-left, @base-left-space, @space-small, @space-xs);
            }

            &-m {
                .mixin-space(@space-type-padding-left, @base-left-space, @space-medium, @space-xs);
            }

            &-l {
                .mixin-space(@space-type-padding-left, @base-left-space, @space-large, @space-xs);
            }

            &-xl {
                .mixin-space(@space-type-padding-left, @base-left-space, @space-xlarge, @space-xs);
            }
        }
    }

    .mar {
        &-top {
            &-s {
                .mixin-space(@space-type-margin-top, @base-top-space, @space-small, @space-xs);
            }

            &-m {
                .mixin-space(@space-type-margin-top, @base-top-space, @space-medium, @space-xs);
            }

            &-l {
                .mixin-space(@space-type-margin-top, @base-top-space, @space-large, @space-xs);
            }

            &-xl {
                .mixin-space(@space-type-margin-top, @base-top-space, @space-xlarge, @space-xs);
            }
        }

        &-bot {
            &-s {
                .mixin-space(@space-type-margin-bottom, @base-bottom-space, @space-small, @space-xs);
            }

            &-m {
                .mixin-space(@space-type-margin-bottom, @base-bottom-space, @space-medium, @space-xs);
            }

            &-l {
                .mixin-space(@space-type-margin-bottom, @base-bottom-space, @space-large, @space-xs);
            }

            &-xl {
                .mixin-space(@space-type-margin-bottom, @base-bottom-space, @space-xlarge, @space-xs);
            }
        }

        &-right {
            &-s {
                .mixin-space(@space-type-margin-right, @base-right-space, @space-small, @space-xs);
            }

            &-m {
                .mixin-space(@space-type-margin-right, @base-right-space, @space-medium, @space-xs);
            }

            &-l {
                .mixin-space(@space-type-margin-right, @base-right-space, @space-large, @space-xs);
            }

            &-xl {
                .mixin-space(@space-type-margin-right, @base-right-space, @space-xlarge, @space-xs);
            }
        }

        &-left {
            &-s {
                .mixin-space(@space-type-margin-left, @base-left-space, @space-small, @space-xs);
            }

            &-m {
                .mixin-space(@space-type-margin-left, @base-left-space, @space-medium, @space-xs);
            }

            &-l {
                .mixin-space(@space-type-margin-left, @base-left-space, @space-large, @space-xs);
            }

            &-xl {
                .mixin-space(@space-type-margin-left, @base-left-space, @space-xlarge, @space-xs);
            }
        }
    }
}

@media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {
    // redo the whole process and changing some global variables
}

@media (min-width: @screen-md-min) and (max-width: @screen-md-max) {
    // redo the whole process and changing some global variables
}

@media (min-width: @screen-lg-min) {
    // redo the whole process and changing some global variables
}

Give array elements unique IDs

I am trying to multiply every element in an array by the next 12 elements:

array.each do |n|
    a = array.index(n)
    b = a + 12
    product = 1
    array[a..b].each { |i| product *= i }
    highest = product if product > highest
end

I run into a problem when there are multiple occurrences of the same integer in the array:

[1, 2, 3, 7, 5, 4, 7] # this is not the actual array

When the second 7 runs through my block, its array.index(n) becomes 3 (the index of the first 7) when I want it to be 6 (the index of the particular 7 I am working with). I'm pretty sure this can be solved by giving each element of the array a unique 'id', but I'm not sure how I would go about doing this.

My question is, how do I give every element in an array a unique id? The Array#uniq method is not what I am looking for.

mysqli_real_escape_string foreach function db_array_update

Someone wrote a PHP program many times ago for me, and now I got this error when I run the code :

mysqli_real_escape_string() expects parameter 2 to be string, array given in....

I cannot fix this here is the code :

function db_array_update($table, $a, $where) 
{    
    $q = "update $table set ";
    $b = NULL;  

    foreach($a as $key => $value)   
    {   
        if (is_int($key))
            continue;   

        $con = mysqli_connect("localhost", MYSQLUSER , MYSQLPASS, MYSQLDB);
        $b[] = "$key='".mysqli_real_escape_string($con, $value)."'";        
    }

    $q .= implode(",", $b);
    $q .= " where ".$where;

    db_query($q);

}

and I use it like this :

db_array_update("all_data",array('last_fetched' =>date("Y/m/d H:i:s"),'name'=>$name, 'creation'=>$creat, 'expiration' =>$expire,"id=".$res['id']);

Can someone help me how should I fix this ? Tried many things but not work...

How to use Arrays, with Strings

I'm a C++ programmer, who's still in the nest, and not yet found my wings. I was writing a Calendar program, and I discovered, that C++ does not support a string type. How do I make an Array, that will be able to store strings of characters?

I've thought of creating an enumerated data type, as the array type. While, it will work, for my Calendar, it won't work if say I was creating a database of the names of students in my class.

http://ift.tt/1NnnPZv I got; "error, 'string' does not name a type."

Input EditText(Type:Number) into array[]

I have an EditText (input type:numberDecimal),that i want to keep adding values with save them to an Array. how can i do this ?
for an example:

EditText:"1234"
Array[0]=1;
Array[1]=2;
Array[2]=3;
Array[3]=4;

Thanks...

Java Standard Search Joptionpane

im learning Java and encounter some problem. Tried many hours but still cant solve. Pls bear with me. Thank you all.

How can i do a search result like shown in enter image description here

and when user press enter, will go next search result? Sori for pasting all my code here. Thanks all.

    import javax.swing.JOptionPane;

public class Makan {

static int[] count;
static String[] foodName;
static String[] country;
static String[] type;
static String[] description;
static String[] price;

public static void main(String[] args) {
    // TODO Auto-generated method stub

    count = new int[7];
    count[0] = 1;
    count[1] = 2;
    count[2] = 3;
    count[3] = 4;
    count[4] = 5;
    count[5] = 6;
    count[6] = 7;

    foodName = new String[7];
    foodName[0] = "Fish and Chips";
    foodName[1] = "Chicken Cutlet";
    foodName[2] = "Oyako Don";
    foodName[3] = "Nasi Goreng";
    foodName[4] = "Seafood Hor Fun";
    foodName[5] = "Ice Kachang";
    foodName[6] = "Ice cream Waffles";

    country = new String[7];
    country[0] = "Western";
    country[1] = "Western";
    country[2] = "Asian";
    country[3] = "Asian";
    country[4] = "Asian";
    country[5] = "Asian";
    country[6] = "Asian";

    type = new String[7];
    type[0] = "Main";
    type[1] = "Main";
    type[2] = "Main";
    type[3] = "Main";
    type[4] = "Main";
    type[5] = "Dessert";
    type[6] = "Dessert";

    description = new String[7];
    description[0] = "Fish fillets in tartar sauce, served with fried chips";
    description[1] = "Breaded chicken cutlet with melted cheese, served with potato and fries";
    description[2] = "Chicken in Japanese rice, served with a bowl of Miso Soup";
    description[3] = "Fried Rice with Satay";
    description[4] = "Flat rice noodles in a tasty gravy with prawns, fish cakes and sliced fish.";
    description[5] = "Shaved ice dessert with jelly, red beans, sweet corn and palm seeds, topped with sweet syrup";
    description[6] = "Freshly baked waffles topped with 2 scoops icecream of your choice";

    price = new String[7];
    price[0] = "16.80";
    price[1] = "15.90";
    price[2] = "13.90";
    price[3] = "10.20";
    price[4] = "10.50";
    price[5] = "5.60";
    price[6] = "8.20";

    String menu = "Main Menu\n";
    menu += "==================\n";
    menu += "1. Display all Menu Items\n";
    menu += "2. Display Menu Item names for selection\n";
    menu += "3. Search Food Type\n";
    menu += "0. Quit\n";
    menu += "==================";

    String input;
    int optionSelected;
    do {

        input = JOptionPane.showInputDialog(menu);
        optionSelected = Integer.parseInt(input);
        System.out.println(optionSelected);

        if (optionSelected == 1) {

            displayAllMenuItems();

        } else if (optionSelected == 2) {

            showAllSelections();
        }

        else if (optionSelected == 3) {
            searchBox();
        }

        else if (optionSelected == 0) {
            System.exit(0);

        }

    } while (optionSelected != 0);
}

// handle option 1...
public static void displayAllMenuItems() {

    String hotkey = "";
    hotkey += "==================\n";
    hotkey += "Enter N for next menu item\n";
    hotkey += "Enter P for previous menu item\n";
    hotkey += "Enter M to return main menu\n";

    int index = 0;
    String input = "";
    do {
        String menu = "Menu Item " + count[index] + " of " + count.length;
        menu += "\n================\n";
        menu += "Name: " + foodName[index] + "\nCountry: " + country[index]
                + "\nType: " + type[index] + "\nDescription: "
                + description[index] + "\nPrice: " + price[index] + "\n";
        menu += hotkey;

        input = JOptionPane.showInputDialog(menu);

        if (input.equalsIgnoreCase("n")) {

            index++;

        }

        else if (input.equalsIgnoreCase("p")) {

            index--;

        }

    } while (!input.equalsIgnoreCase("M"));

}

// handle option 2
public static void showAllSelections() {
    int index;
    String input = "";
    String menu = "";
    menu += "Menu Item Selection Menu\n";
    menu += "==================\n";

    for (index = 0; index < foodName.length; index++) {

        menu += index + 1 + ". " + (foodName[index]) + "\n";

    }
    menu += "Please enter your selection\n";

    input = JOptionPane.showInputDialog(menu);
    int optionSelected;
    optionSelected = Integer.parseInt(input);
    listSpecificItems(optionSelected);

}

// list specific items
public static String listSpecificItems(int index) {
    String menu = "";
    String input = "";

    menu = "Menu Item " + count[index - 1] + " of " + count.length;
    menu += "\n================\n";
    menu += "Name: " + (foodName[index - 1]) + "\nCountry: "
            + (country[index - 1]) + "\nType: " + (type[index - 1])
            + "\nDescription: " + (description[index - 1]) + "\nPrice: "
            + (price[index - 1]) + "\n";
    menu += "================\n";
    menu += "Enter M to return to main menu\n";

    if (input.equalsIgnoreCase("m")) {

        displayAllMenuItems();
    }
    input = JOptionPane.showInputDialog(menu);

    return input;
}


// Handle Search Box
public static void searchBox() {
    String menu = "";
    String input = "";

    menu = "Search By\n";
    menu += "================\n";

    input = JOptionPane.showInputDialog(menu);
    showSearchResult(input);
}

/** stuck here how define search n show results **/
public static String showSearchResult(String input) {


}

}

Updating nested arrays with Laravel

First sorry, i am only developing in php for a month and i do not know how to update this with laravel

I would like to update multiple photos.

Photos have a title description, etc.

My problem is i have no clue how to do it.

I tried the following

public function update(Request $request, Photo $photo)
    {
         // loop throug array of id's
         foreach ($request->photo_id as $id) 
         {
            // find 
             $photos = $photo->find($id);

             // loop throug input fields
             foreach ($request->except('_token', 'tags', 'photo_id') as $key => $value) 
             {
                $photos->$key = $value
                $photos->save();
             }

         }

         die();
    }   

I get the following error

preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

So i figured out the problem is with the value

And the results are like this

Key variable

string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"

Value variable results

array(2) {
  [0]=>
  string(9) "title one"
  [1]=>
  string(9) "title two"
}
array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "1"
}
array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "1"
}
array(2) {
  [0]=>
  string(0) ""
  [1]=>
  string(0) ""
}
array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(0) ""
}
array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(0) ""
}

I tried several other attempts but nothing works

Could please someone help me out with this?

Can't figure out this array [duplicate]

This question already has an answer here:

I have an array:

Array (
    [variants] => Array ( 
        [0] => Array (
            [barcode] => 610373772697
            [compare_at_price] =>
            [created_at] => 2015-06-27T01:56:42-07:00
            [fulfillment_service] => manual
            [grams] => 190
            [id] => 3856358467
            [inventory_management] => shopify
            [inventory_policy] => deny
            [option1] => Default Title
            [option2] =>
            [option3] =>
            [position] => 1
            [price] => 20.99
            [product_id] => 1259972867
            [requires_shipping] => 1
            [sku] => 1125442
            [taxable] => 1
            [title] => Default Title
            [updated_at] => 2015-06-27T01:56:42-07:00
            [inventory_quantity] => 100
            [old_inventory_quantity] => 100
            [image_id] =>
            [weight] => 0.42
            [weight_unit] => lb
        ) 
        [1] => Array (
            [barcode] => 364031530906
            [compare_at_price] =>
            [created_at] => 2015-06-27T01:56:42-07:00
            [fulfillment_service] => manual
            [grams] => 131
            [id] => 3856359043
            [inventory_management] => shopify
            [inventory_policy] => deny
            [option1] => Default Title
            [option2] =>
            [option3] =>
            [position] => 1
            [price] => 17.24
            [product_id] => 1259973059
            [requires_shipping] => 1
            [sku] => 0116350
            [taxable] => 1
            [title] => Default Title
            [updated_at] => 2015-06-27T01:56:42-07:00
            [inventory_quantity] => 100
            [old_inventory_quantity] => 100
            [image_id] =>
            [weight] => 0.29
            [weight_unit] => lb

        ) 
        [2] => Array (
            [barcode] => 364031534003
            [compare_at_price] =>
            [created_at] => 2015-06-27T01:56:43-07:00
            [fulfillment_service] => manual
            [grams] => 390
            [id] => 3856359107
            [inventory_management] => shopify
            [inventory_policy] => deny
            [option1] => Default Title
            [option2] =>
            [option3] =>
            [position] => 1
            [price] => 27.74
            [product_id] => 1259973123
            [requires_shipping] => 1
            [sku] => 0116368
            [taxable] => 1
            [title] => Default Title
            [updated_at] => 2015-06-27T01:56:43-07:00
            [inventory_quantity] => 100
            [old_inventory_quantity] => 100
            [image_id] =>
            [weight] => 0.86
            [weight_unit] => lb
        )
    )
) 
) 

And no matter how many For Loops I try, I cannot figure out how to extract the [id] and the [product_id] and pass them to variables using PHP.

My goal is to dump the id and product_id into a mysql database and I once I get the values out I can do that easily.

Can anyone help guide me?

Array stored in a string type : PHP

Today i faced weird problem it is

$stringvar = '["image_link1","Image_link2"]';

Now i want to covert it into type array. <br />
like <br />
Array => [0] Image_link1,<br />
 [1] Image_link2

I tried to juggling the type but it's giving me <br />
Array => [0] '["image_link1","Image_link2"]'

Right now I am using
str_replace() to replace '[', ']' with blank. then explode.

Is there any best workaround for it ???

Check if a String is a Palindrome in JavaScript

The requirements for this task are that the code is returns a 'true' or 'false' for an input string. The string can be a simply word or a phrase. The other question does not address these needs. Please reopen and answer here. I am working on a function to check if a given string is a palindrome. My code seems to work for simple one-word palindromes but not for palindromes that feature capitalization or spaces.

function palindrome(str) 
{
    var palin = str.split("").reverse().join("");

    if (palin === str){
        return true;
    } else {
        return false;
    }
}   

palindrome("eye");//Succeeds
palindrome("Race car");//Fails

samedi 27 juin 2015

Spring MongoDB - Array objects come over null

I have a mongo collection that has an embedded array of ObjectId's, so the general format is this:

{
    "_id" : ObjectId("123abc..."),
    "Active" : [ 
        {
            "Id" : ObjectId("123abc...")
        }, 
        {
            "Id" : ObjectId("123abc...")
        }, 
        ...,
        {
            "Id" : ObjectId("123abc...")
        }
    ],
    "field1" : "blah blah",
    "field2" : "blah blah",
    "field3" : "blah blah",
    "field4" : "blah blah"
    "field5" : ObjectId("123abc...")
}

My Java class is pretty simple:

@Document(collection="MyCollection")
public class MyCollection {

    @Id
    private ObjectId id;
    private String field1;
    ...
    private ObjectId field5;
    @Field("Active")
    private List<Active> active;

    // Getters & Setters here

   public static class Active {
    @Field("Id")
    private ObjectId id;

    public ObjectId getId() {
        return id;
    }

    public void setId(ObjectId id) {
        this.id = id;
    }
  }
}

When I do the query, everything comes over correctly but the "Active" field. If there are 18 entries in that array, I will get a List of size 18, but the 18 entries of Active.class are all null - so it gets that it's a List, it just never pulls over the ObjectId values within the active array.

I'm using Spring and the Spring mongo driver.

getting data from post array using codeigniter

I'm trying to post an array that is "name="std_id[]"" from view page.But in controller while trying to print the array using "print_r($std_id)" I can't find any data. The code is given below..

In view page:

<?php

foreach ($all_student as $v_student) { ?>

std_id ?>" name="std_id[]"> std_name; ?>

In controller function:

    $std_id = $this->input->post("std_id[]", true);
    print_r($std_id);
    exit();

Ruby Instance Array Is Modified in a Separate Object

Lets say I create an object with an array. I then create another object that takes said array and modifies it within its own scope. If I try to access original array from the first object again, shouldn't I have the unmodified version of the array?

Example code:

class Test
    attr_accessor :g

    def initialize
        @g = [1,2,3]
    end

    def do_stuff
        Test_Two.new(@g).modify
    end

end

class Test_Two
    def initialize(h)
        @h = h
    end

    def modify
        @h[0] +=1
    end

end


t = Test.new
puts "#{t.g}"
t.do_stuff #this shouldn't modify t.g
puts "#{t.g}"

Expected output:

[1,2,3]
[1,2,3]

Actual output:

[1,2,3]
[2,2,3]

Weirdly enough, if I make g an integer, I get what I expect:

class Test
    attr_accessor :g

    def initialize
        @g = 1
    end

    def do_stuff
        Test_Two.new(@g).modify
    end

end

class Test_Two
    def initialize(h)
        @h = h
    end

    def modify
        @h +=1
    end

end


t = Test.new
puts "#{t.g}"
t.do_stuff #this shouldn't modify t.g
puts "#{t.g}"

Output:

1
1

variable expansion as a pattern in sed not working

I've a simple script to set several parameters in /etc/ssh/sshd_config :

#! /bin/bash

declare -a param=('Banner' 'ClientAliveInterval' 'ClientAliveCountMax' 'Ciphers' \
'PermitUserEnvironment' 'PermitEmptyPasswords' 'PermitRootLogin' \
'HostbasedAuthentication' 'IgnoreRhosts' 'MaxAuthTries' \
'X11Forwarding' 'LogLevel'\
)

declare -a val=('/etc/issue.net' '300' '0' 'aes128-ctr,aes192-ctr,aes256-ctr' \
'no' 'no' 'no' 'no' 'yes' '4' 'no' 'INFO' \
)

for (( i=0;i<12;i++ ))
do
 #echo "${param[$i]} ${val[$i]}"
  egrep "^[ #]*${param[$i]}.*" /etc/ssh/sshd_config &> /dev/null
   if [ $? -eq 0 ];
    then
       sed -i "s|^[ #]*\$param[$i].*|${param[$i]} ${val[$i]}|1" /etc/ssh/sshd_config
  else
       echo "${param[$i]} ${val[$i]}" >> /etc/ssh/sshd_config
  fi
done;

However the variable expansion in sed pattern match is not working as desired:

sed -i "s|^[ #]*\$param[$i].*|${param[$i]} ${val[$i]}|1" /etc/ssh/sshd_config

Can someone help me. My array expansion and everything in the script is fine though. I've checked the same with an echo printout.

Reading text file of unknown size

I am trying to read in a text file of unknown size into an array of characters. This is what I have so far.

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

    int main()
    {
            FILE *ptr_file;
            char buf[1000];
        char output[];
            ptr_file =fopen("CodeSV.txt","r");
            if (!ptr_file)
                return 1;   

        while (fgets(buf,1000, ptr_file)!=NULL)
            strcat(output, buf);
        printf("%s",output);

    fclose(ptr_file);

    printf("%s",output);
        return 0;
}

But I do not know how to allocate a size for the output array when I am reading in a file of unknown size. Also when I put in a size for the output say n=1000, I get segmentation fault. I am a very inexperienced programmer any guidance is appreciated :)

The textfile itself is technically a .csv file so the contents look like the following : "0,0,0,1,0,1,0,1,1,0,1..."

Adding up values in array

I am trying to count elements in an array separated by one or more zeroes (0) Example: [3,2,1,0,5,4,0,0,8,4]. 3+2+1 , 5+4 , 8+4 Output: [6,9,12] I have written the following function:

function countElementsInArray(){
$array = [1,2,4,0,9,8,4,0,7,1,2,6];

$countArr = [];
$count = 0;
$test = 0;

for($i = 0; $i < count($array); $i++){
    if( $array[$i] != 0 ) {
       $count += $array[$i];
    } 
    //else if($array[$i] == 0 || $array[$i - 1] == 0){
    else{
        $count = 0;
        $test += 1;
    }
    $countArr[$test] = $count;
}
return $countArr;

}

This works fine if I have only one "0" in the array. I can't figure out how to add up the values if I have 2 zeroes. Any idea how to solve this problem?

Server side: Fill form on a webpage

Lets say there's a form on a webpage with URL xyz.com . The form has some text input fields, some drop down selections to be made etc. I need to write a server side script to visit this web page and fill and submit the form. Note that the server doesn't have a browser environment.

What should I do to achieve this? Any techniques in PHP (using cURL) or Python or echoing Java script via PHP ? I'd also have the form field IDs with me.

run function that returns several foreach

I'm developing the script, do a search in an array with one or several keywords, which is the following script:

$url= "http://ift.tt/1JqYyQ7".date('d')."&output=json&groupby=country-adspace&period_group_by=day";


function search($array, $key, $value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}


$json = file_get_contents($url);
$arr = json_decode($json, TRUE);



$my_date_arr = search($arr, 'ADSPACE', '41432');

I then returned the key, containing only that number as keyword. and I do another foreach to show only keys containing the characters.

  <?php
foreach ($my_date_arr as $key=>$value) :
  $country = $value['COUNTRY'];
  $clicks = $value['CLICKS'];
  $fecha = $value['DATE'];
  $adspace = $value['ADSPACE'];



?> 
    <td><?= $country; ?></td>
    <td><?= $clicks; ?></td> 
    <td><?=$fecha;?><td>
   <td><?=$adspace;?><td>

  </tr>

  <?php endforeach;?>

it all works perfectly, the problem is I want to make two requests to the same function with a different value for example:

$my_date_arr = search($arr, 'ADSPACE', '41432');
$my_date_arr = search($arr, 'ADSPACE', '41755');

the goal is to look into an array a predetermined value, then return the key that contains the value and thus only make a foreach of what I find in the foreach, but also need is to make several requests in that foreach to I return the entire result in a single request.

Remove duplicates from PHP array but ignoring one parameter

I have an array comprised of PHP objects as such.

$objects[0] => $object->type => 'President'
               $object->name => 'Joe Blogs'
               $object->address => '123 Harry Street'

$objects[1] => $object->type => 'Secretary'
               $object->name => 'Joe Blogs'
               $object->address => '123 Harry Street'

$objects[2] => $object->type => 'Treasurer'
               $object->name => 'Jane Doe'
               $object->address => '456 Upton Street'

I would like to ignore the 'type' parameter and end up with

$objects[0] => $object->type => 'President'
               $object->name => 'Joe Blogs'
               $object->address => '123 Harry Street'

$objects[2] => $object->type => 'Treasurer'
               $object->name => 'Jane Doe'
               $object->address => '456 Upton Street'

I have tried a few difrent things but not sure how to ignore the type parameter

Maze Solver ArrayIndexOutOfBoundsException

I am working on a Maze Solver, but I encounted an ArrayOutOfBoundsException on this line:

wasHere[row][col] = false;

I don't see how there could possibly be such error, since the width and height (number of rows and columns) as represented in the maze, wasHere, and correctPath are all the same. All arrays show 7 columns and 4 rows.

private static int[][] maze = {{2, 2, 2, 2, 1, 2, 2}, {2, 2, 2, 2, 1, 2, 2}, 
        {2, 2, 2, 2, 1, 2, 2}, {2, 1, 1, 1, 1, 2, 2}}; // The maze
private static boolean[][] wasHere = new boolean[7][4];
private static boolean[][] correctPath = new boolean[7][4]; // Solution

for (int row = 0; row < maze.length; row++)
{
    // Sets boolean arrays to false
    for (int col = 0; col < maze[row].length; col++)
    {
        wasHere[row][col] = false;
        correctPath[row][col] = false;
    }
}

Manipulating elements of an array in parallel using node.js?

I have a an array of json objects like this -

var resultsArr = [
{
    "upvotes": "45",
    "postID": "4555",
    "numberOfComments": "45",
    "shares":"22"
},
{
    "upvotes": "21",
    "postID": "4665",
    "numberOfComments": "20",
    "shares":"24"
},
{
    "upvotes": "4",
    "postID": "77366",
    "numberOfComments": "0",
    "shares":"4"
},
{
    "upvotes": "49",
    "postID": "6565",
    "numberOfComments": "22",
    "shares":"54",

}];

I need to compute a value score based on upvotes,numberOfComments,sharesand then push it back into the JSON dictionary so that every object in array looks like this -

var resultsArr= [{
....
},
{
    "upvotes": "49",
    "postID": "6565",
    "numberOfComments": "22",
    "shares":"54",
    "score":"20"
}]

I can access the json objects in this array using a for loop but from my understanding goes, it accesses each element in sequence.

Given that I will have roughly 100-200 items in the array, how can I speed up the score computation process to access each element parallelly and thus reduce the time it takes to compute the score for every element in the array?

P.S I'm coding this, with the assumption, that the elements in the array might grow to have 300-400 elements in the future.

How can you read a CSV file in c# with different number of columns

I'm a beginner with c#, I have a csv file of integer data with 140 rows and every row has different number of columns csv file looks like this:

1,1,2,2,3

1,2,2,2,4,4,4,4

6,7

how can i load every row into a new array using a loop which has similar action like

int[][] inputSequences = {

    new[] { 1, 1, 2, 2, 3 },        
    new[] { 1, 2, 2, 2, 4, 4, 4, 4 },     
    new[] { 6, 7 },     

}

How to merge three sorted arrays without using any unnecessary space?

For example I've written C++ code to merge three arrays, but here you can see that first I had to merge first two arrays and then merge its resulting array to third array..

while (p < n1 && q < n2)    // n1,n2,n3 are sizes of a,b,c respectively 
{
    if (a[p] < b[q])    
    {
        res[r] = a[p];  // res is array is intermediate merged array
        r++;
        p++;
    }
    else
    {
        res[r] = b[q];
        r++;
        q++;
    }
}

while (q < n2)
{
    res[r] = b[q];
    r++;
    q++;
}

while (p < n1)
{
    res[r] = a[p];
    r++;
    p++;
}

while (s < r && t < n3)
{
    if (res[s] < c[t])
    {
        res2[r2] = res[s];  // res2 is finally merged array
        r2++;
        s++;
    }
    else
    {
        res2[r2] = c[t];
        r2++;
        t++;
    }
}

while (s < r)
{
    res2[r2] = res[s];
    s++;
    r2++;
}

while (t < n3)
{
    res2[r2] = c[t];
    r2++;
    t++;
}

I don't want to use intermediate array in my program.Is there any way I can do it?

Also, Is there any methodology using which we can merge any number of sorted arrays in one go ?

How to create a Ruby array slice which shares the same instance of the original array?

So that if the slice gets changed, the original array will also change?

a = [1, 2, 3]
b = a[1, 2]
b[0] = 42 # due to COW, only b changes, a remains unchanged

Expected result: when run b[0] = 42, a[1] will also changed to 42.

error in creating array of linked list

I have to put nodes of binary search tree of every level in a linked list. That is if the height of the tree is 'h' then 'h+1' linked lists would be created and then each linked list would have all the nodes of each level. For this I have thought of creating an array of linked list. But the nodes are not being inserted in the list I guess. The code is as follows:-

struct node{ 
    int data;
    struct node *left;
    struct node *right;
    };

struct linked_list
{

    int data;
    struct linked_list *next;
};

    linkedlistofbst(struct node *new,struct linked_list *n1[], int level)
    {
    //printf("%d ",new->data);
    if(new==NULL)
    {
        return;
    }

    if(n1[level]==NULL)
    {
        struct linked_list *a =(struct linked_list *)malloc(sizeof(struct linked_list));
        a->data=new->data;
        a->next=NULL;
        n1[level]=a;
        printf("%d ",a->data);
    }
    else
    {
        struct linked_list *b =(struct linked_list *)malloc(sizeof(struct     linked_list));
        while(n1[level]->next!=NULL)
        {
            n1[level]=n1[level]->next;
        }
        b->data=new->data;
        b->next=NULL;
        n1[level]=b;
    }
    linkedlistofbst(new->left,n1,level+1);
    linkedlistofbst(new->right,n1,level+1);
    }

    main()

{
    struct linked_list *l=(struct linked_list *)malloc((a+1)*sizeof(struct    linked_list));//'a' is the height of the tree
    linkedlistofbst(new,&l, 0);//new is the pointer to the root node of the tree.
}

Unexpected behavior of Array.prototype.splice

While implementing an internal EventEmitter for a project I was working on, I came across a strange quirk when using Array.prototype.splice inside a for... in loop. The function does not successfully remove the indeces from the array within the loop:

var array = [1, 2, 3, 4, 5], index;

for (index in array) {
    if (index === 2) {
        array.splice(index, 1);
    }

    console.log(array[index]);
}

console.log(array);

Running on Google Chrome version 43, this outputs

1
2
3
4
5
[1, 2, 3, 4, 5]

when I'm expecting something like

1
2
4
5
undefined†
[1, 2, 4, 5]

Is this intential behavior or a bug? I cannot find any documented reference to this behavior.

Possibly, if length is not calculated during each iteration of Array.prototype.splice implementation

Using arrays in regular expressions (ruby)?

Does anyone know if there is a way to use an array in a regular expression? suppose i want to find out if "somefile.txt" contains one of an array's elements. Obviously the code below doesn't work, but is there something similar that does work?

array = [thing1 thing2 thing3]
file = File.open("somefile.txt")

file.each_do |line|
if /array/.match(line)
puts line
end

basically i've got a big list of words to search for, and i'd like to avoid something like this:

($somefile =~ /(thing1|thing2|thing3)/)

Thanks in advance!

How would I optimize this search function?

I'm having a tough time thinking through how I can make my search function more optimal. So I have a situation where I load an array of objects from a SQLITE database. Essentially one element in the array has multiple properties that can be accessed. Inside one element of the array, you have properties like time and rooms. I want to make the search flexible without having the user to filter what they are searching for. What I don't like about my implementation is that I filter through both time and room, then I for loop the filtered arrays and add them to a general "searchArrayToDisplay." I think the for loop is wasteful. I was wondering if there is a way I can append the filtered elements to the general "searchArrayToDisplay" without having to for loop? The method below is generally fast, but I think there's a better way that I'm just not seeing. Hopefully I am clear. Thanks for any help!

let filteredTime = searchArray.filter { (time: ProductModel) -> Bool in
               if time.customText1 == nil {
                 return false
                  } else {
                  return  time.customText1.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil

                }   
            }
            var m : ProductModel
            for m in filteredTime {

                searchArrayToDisplay.append(m)

            }

            let filteredRooms = searchArray.filter { (session: ProductModel) -> Bool in

                if session.roomName == nil {
                    return false
                } else {
                return session.roomName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil
                }   
            }
            for pm in filteredRooms {
                searchArrayToDisplay.append(pm)
            }