问:
How to stop a value from going into negative value
I'm developing an incremental game here is the link for visual reference:

https://code.sololearn.com/WF65X6DEns7o/#css

The problem i have is that buttons can be clicked unlimited times and INCOME value will go into the negative.

How can disable the button if the player doesn't have enough INCOME to click the button

function buttonOne() {
  a++;
  document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
  income -= 500;
  document.getElementById("HeaderLabel").innerHTML = " OK, good, now let's   watch as your money starts to generate slowly but surely.
 After all no   empire was built in a day.
 When you have enough money you can buy more   units. " ;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar1");
    var width = 1;
    var id = setInterval(frame, 4);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 1000)
}

function buttonTwo() {
  b++;
  document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
  income -= 1000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar2");
    var width = 1;
    var id = setInterval(frame, 9);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 2000)
}

function buttonThree() {
  c++;
  document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
  income -= 2000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar3");
    var width = 1;
    var id = setInterval(frame, 19);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 3000)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="gameMoneyBG">
  <div id="gameMoney"> Income : $ 500 </div</div>

    <button id="buttonOne" onclick="buttonOne()">
          <b>Small Units</b></button>
    <div id="progbar1">
      <div id="myprogbar1"> </div>
    </div>
    <br /> <br />
    <div id="btnLabel1"> Units Owned : 0 </div>
    <div id="costLabel1">
      Unit Cost : $ 500 </div>

    <br /><br />

    <button id="buttonTwo" onclick="buttonTwo()"><b>Large Units</b></button>
    <div id="progbar2">
      <div id="myprogbar2"> </div>
    </div>
    <br /><br />
    <div id="btnLabel2"> Units Owned : 0 </div>
    <div id="costLabel2"> Unit Cost : $ 1000 </div>

    <br /><br />

    <button id="buttonThree" onclick="buttonThree()"><b>City Lofts</b></button>
    <div id="progbar3">
      <div id="myprogbar3"> </div>
    </div>
    <br /><br />
    <div id="btnLabel3"> Lofts Owned : 0 </div>
    <div id="costLabel3"> Loft Cost : $ 2000 </div></code>```

答:
paste the code with each function after income -=num .It will restrict the value below 0 .its ternary operator

```<code> income= income < 0 ? 0 :income;
</code>```

Js Code

```<code> var income = 500;
    var a = 0;
    var b = 0;
    var c = 0;

    alert("Welcome to my game. It took me 2 days to create it.  I hope you enjoy it. \n\nPlease note that you get best experience on a PC not on a mobile. \n\n Also please ignore any bugs you may find, but feedback on improvement is welcome.")

    function buttonOne() {

        a++;
        document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
        income-=500;
         income= income < 0 ? 0 :income;
        document.getElementById("HeaderLabel").innerHTML = "<b> OK, good, now lets watch as your money starts to generate slowly but surely. <p> After all no empire was built in a day. <p> When you have enough money you can buy more units." ;

        window.setInterval (function move() {
        var elem = document.getElementById("myprogbar1");
        var width = 1;
        var id = setInterval(frame, 4);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
                width++;
                elem.style.width = width + '%';
            }
        }
    }, 1000)
    }

    function buttonTwo() {
        b++;
        document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
        income-=1000;
             income= income < 0 ? 0 :income;
        window.setInterval (function move() {
        var elem = document.getElementById("myprogbar2");
        var width = 1;
        var id = setInterval(frame, 9);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
                width++;
                elem.style.width = width + '%';
            }
        }
    }, 2000)
    }

    function buttonThree() {
        c++;
        document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
        income-=2000;
         income= income < 0 ? 0 :income;
        window.setInterval (function move() {
        var elem = document.getElementById("myprogbar3");
        var width = 1;
        var id = setInterval(frame, 19);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
                width++;
                elem.style.width = width + '%';
            }
        }
    }, 3000)
    }

    window.setInterval(function() {
        if (a >= 1)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=a*5);

        if(a>=25)
        document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=a *10);

        if(a>=50)
        document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=a *20);

    }, 1000)

    window.setInterval(function() {
        if (b >= 1)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=b+49*b);

        if (b >= 25)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=b+49*b*4);

        if (b >= 50)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=b+49*b*8);

    }, 2000)

    window.setInterval(function() {
        if (c >= 1)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=c+99*c);

        if (c >= 25)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=c+99*c*4);

        if (c >= 50)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=c+99*c*8);
    }, 3000)

    function income(){
        if (income >= 1000000)
        document.getElementById("HeaderLabel").innerHTML = "You have been caught for tax evasion. The Government will now take $500 000." ;
    }
</code>```

Body:
I'm developing an incremental game here is the link for visual reference:

https://code.sololearn.com/WF65X6DEns7o/#css

The problem i have is that buttons can be clicked unlimited times and INCOME value will go into the negative.

How can disable the button if the player doesn't have enough INCOME to click the button

function buttonOne() {
  a++;
  document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
  income -= 500;
  document.getElementById("HeaderLabel").innerHTML = " OK, good, now let's   watch as your money starts to generate slowly but surely.
 After all no   empire was built in a day.
 When you have enough money you can buy more   units. " ;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar1");
    var width = 1;
    var id = setInterval(frame, 4);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 1000)
}

function buttonTwo() {
  b++;
  document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
  income -= 1000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar2");
    var width = 1;
    var id = setInterval(frame, 9);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 2000)
}

function buttonThree() {
  c++;
  document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
  income -= 2000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar3");
    var width = 1;
    var id = setInterval(frame, 19);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 3000)
}

 Income : $ 500 </div

    <button id="buttonOne" onclick="buttonOne()">
          Small Units</button>

 Units Owned : 0

      Unit Cost : $ 500

    <button id="buttonTwo" onclick="buttonTwo()">Large Units</button>

 Units Owned : 0

 Unit Cost : $ 1000

    <button id="buttonThree" onclick="buttonThree()">City Lofts</button>

 Lofts Owned : 0

 Loft Cost : $ 2000

Body:
paste the code with each function after income -=num .It will restrict the value below 0 .its ternary operator

 income= income < 0 ? 0 :income;

Js Code

 var income = 500;
    var a = 0;
    var b = 0;
    var c = 0;

    alert("Welcome to my game. It took me 2 days to create it.  I hope you enjoy it. \n\nPlease note that you get best experience on a PC not on a mobile. \n\n Also please ignore any bugs you may find, but feedback on improvement is welcome.")

    function buttonOne() {

        a++;
        document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
        income-=500;
         income= income < 0 ? 0 :income;
        document.getElementById("HeaderLabel").innerHTML = "<b> OK, good, now lets watch as your money starts to generate slowly but surely. <p> After all no empire was built in a day. <p> When you have enough money you can buy more units." ;

        window.setInterval (function move() {
        var elem = document.getElementById("myprogbar1");
        var width = 1;
        var id = setInterval(frame, 4);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
                width++;
                elem.style.width = width + '%';
            }
        }
    }, 1000)
    }

    function buttonTwo() {
        b++;
        document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
        income-=1000;
             income= income < 0 ? 0 :income;
        window.setInterval (function move() {
        var elem = document.getElementById("myprogbar2");
        var width = 1;
        var id = setInterval(frame, 9);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
                width++;
                elem.style.width = width + '%';
            }
        }
    }, 2000)
    }

    function buttonThree() {
        c++;
        document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
        income-=2000;
         income= income < 0 ? 0 :income;
        window.setInterval (function move() {
        var elem = document.getElementById("myprogbar3");
        var width = 1;
        var id = setInterval(frame, 19);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
                width++;
                elem.style.width = width + '%';
            }
        }
    }, 3000)
    }

    window.setInterval(function() {
        if (a >= 1)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=a*5);

        if(a>=25)
        document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=a *10);

        if(a>=50)
        document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=a *20);

    }, 1000)

    window.setInterval(function() {
        if (b >= 1)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=b+49*b);

        if (b >= 25)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=b+49*b*4);

        if (b >= 50)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=b+49*b*8);

    }, 2000)

    window.setInterval(function() {
        if (c >= 1)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=c+99*c);

        if (c >= 25)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=c+99*c*4);

        if (c >= 50)
          document.getElementById("gameMoney").innerHTML = " Income : $ " + (income+=c+99*c*8);
    }, 3000)

    function income(){
        if (income >= 1000000)
        document.getElementById("HeaderLabel").innerHTML = "You have been caught for tax evasion. The Government will now take $500 000." ;
    }


来源: stackexchange

问:
DWH from multiple schemas
I have a project in postgresql to create a DWH from multiple schemas. The schemas have the same structure(tables, constrains).
I am stuck on this problem : I have a table "employees" in all the schemas that i will use in DWH. The first entry in schema1 table employees is 1 John Dow, the first entry in schema2 table employees is 1 Mary Jane (the id column is auto increment).
Is there a way to create a DWH with this structure ? Is there a way to partition the schemas data ?
Thank you.</p>

答:
The easiest way will probably be to assign a number of the most significant bits of the key to become a source ID, thereby making your keys unique across all of your source databases. E.g. Let's assume you will never have more than 100 databases that you're warehousing, so a 7 bit database identifier will be sufficient.

Ensure all tables in your database that have sequential integer primary keys, or foreign keys referencing those, use the same data type. This data type must be large enough to hold values for all rows on any table without touching the most significant 8 bits. So INTEGER (32 bit) keys would leave 24 bits remaining allowing up to 16777215 insertions, and BIGINT (64 bit) keys will leave 56 bits remaining, allowing up to 72057594037927935 insertions. (Beware that ALTER TABLE ... ALTER COLUMN SET DATA TYPE requires a full table rewrite and can be very slow for high volume tables.)

Assign each DB a unique, 7 bit database identifier that will occupy the most significant 8 bits of each key. You only get 7 bits, not 8, because the top bit is the signing bit, and you can't touch that.

For every integer primary key and foreign key referencing it in the database, update it, adding DB_ID << 24 (for 32 bit keys) or DB_ID << 56 (for 64 bit keys) to it. E.g. For a DB with ID 13 and 32 bit keys, you would add 218103808 to every key value.

Optionally, add CHECK CONSTRAINTs to each table, ensuring their key is in the range [(DB_ID << 24) + 1, ((DB_ID+1) << 24) - 1].

Restart each table's PK sequence using: ALTER SEQUENCE :seq_name MINVALUE :min_val MAXVALUE :max_val START WITH :start_val RESTART WITH :start_val, where min_val = (DB_ID << 24) + 1, max_val = ((DB_ID+1) << 24) - 1, and start_val = currval(SEQUENCE_NAME).

ContentLicense: CC BY-SA 3.0

Title: DWH from multiple schemas


问:
How to read from Registry under LOCAL_MACHINE
I am prepairing an Windows form application which will show the Bitness of currently installed office(2016). I have placed a Button(ChkBtn) and a Label(BitnessLbl) in my form, that will help to accomplish my task.
    The problem is that even though I can find the value of the 'Bitness'('x64' in my case) by searching in the registary, the program fails to locate the specified registary. I have added an image that will further explain my problem. And the code that I am using is as follows

```<code>using System;
using System.Windows.Forms;
using Microsoft.Win32;

namespace GetOfficeBitness
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void ChkBtn_Click(object sender, EventArgs e)
        {
            var arg = @"SOFTWARE\Microsoft\Office\16.0\Outlook";
            var key = Registry.LocalMachine.OpenSubKey(arg, false);//OpenSubKey(arg);
            /*var p = Registry.LocalMachine.GetSubKeyNames();
            var l = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Office\16.0\Common");
            var n = l.GetSubKeyNames();*/
            if (key != null)
            {
                if (key.GetValue("Bitness").ToString() == "x86" || key.GetValue("Bitness").ToString() == "X86")
                    BitnessLbl.Text = @"32 Bit Office";
                //Environment.Exit(1);
            }
            else
            {
                //Environment.Exit(0);
                BitnessLbl.Text = @"64 Bit Office";
            }

        }
    }
}
</code>```

Image link goes here:-
  https://i.stack.imgur.com/XUcuX.png

答:
As I indicated in a comment, when your code is running as a 32-bit process, you're experiencing the effects of the Registry Redirector.

When it looks like your code is accessing HKEY_LOCAL_MACHINE\Software, it is in fact accessing HKEY_LOCAL_MACHINE\Software\Wow6432Node.

To counter the effects, make sure you open your key using an appropriate method/overload that accepts a RegistryView and request the 64-bit view. E.g. you may need to use OpenBaseKey rather than using the built-in LocalMachine property as your starting point.

So, something along the lines of:

```<code>var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine
                                 ,RegistryView.Registry64).OpenSubKey(arg, false);
</code>```

Body:
I am prepairing an Windows form application which will show the Bitness of currently installed office(2016). I have placed a Button(ChkBtn) and a Label(BitnessLbl) in my form, that will help to accomplish my task.
    The problem is that even though I can find the value of the 'Bitness'('x64' in my case) by searching in the registary, the program fails to locate the specified registary. I have added an image that will further explain my problem. And the code that I am using is as follows

using System;
using System.Windows.Forms;
using Microsoft.Win32;

namespace GetOfficeBitness
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void ChkBtn_Click(object sender, EventArgs e)
        {
            var arg = @"SOFTWARE\Microsoft\Office\16.0\Outlook";
            var key = Registry.LocalMachine.OpenSubKey(arg, false);//OpenSubKey(arg);
            /*var p = Registry.LocalMachine.GetSubKeyNames();
            var l = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Office\16.0\Common");
            var n = l.GetSubKeyNames();*/
            if (key != null)
            {
                if (key.GetValue("Bitness").ToString() == "x86" || key.GetValue("Bitness").ToString() == "X86")
                    BitnessLbl.Text = @"32 Bit Office";
                //Environment.Exit(1);
            }
            else
            {
                //Environment.Exit(0);
                BitnessLbl.Text = @"64 Bit Office";
            }

        }
    }
}

Image link goes here:-
  https://i.stack.imgur.com/XUcuX.png

Body:
As I indicated in a comment, when your code is running as a 32-bit process, you're experiencing the effects of the Registry Redirector.

When it looks like your code is accessing HKEY_LOCAL_MACHINE\Software, it is in fact accessing HKEY_LOCAL_MACHINE\Software\Wow6432Node.

To counter the effects, make sure you open your key using an appropriate method/overload that accepts a RegistryView and request the 64-bit view. E.g. you may need to use OpenBaseKey rather than using the built-in LocalMachine property as your starting point.

So, something along the lines of:

var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine
                                 ,RegistryView.Registry64).OpenSubKey(arg, false);


问:
Need a way around this JSON Null exception
I fire a query and the result comes in JSON.I set it using setters.here is my Dataclass:

```<code>private String userstory;
private String task;
private int actual;
private int estimate;
private String ref;
private String uid;
private String tid;
--setters--
</code>```

Here is my main class:

```<code>for(JsonElement result : taskresponse.getResults())
    {
        JsonObject results = result.getAsJsonObject();
        MyData myData = new MyData(results.get("WorkProduct").getAsJsonObject().get("Name").getAsString(),results.get("Name").getAsString(),
        (int) Double.parseDouble(results.get("Actuals").getAsString()),
        (int) Double.parseDouble(results.get("Estimate").getAsString()),
        results.get("_ref").getAsString(),
        results.get("WorkProduct").getAsJsonObject().get("FormattedID").getAsString(),results.get("FormattedID").getAsString());
        data_list.add(myData);
    }
</code>```

When I get value int in fields "Actuals" and "Estimate" it is working well. But sometimes I get values null as the result from query. Thus I get JSONNULLEXCEPTION.
How should i handle this exception.I ultimately want the fields to be set 0 when query returns null.
Thanks

答:
As you have your Dataclass ,you  create a another ArrayList Data Class like

```<code>public class ListdataClass {
private ArrayList<Dataclass>  listdata;
//getter and setter for listdata`

}
</code>```

now you Add ObjectMapper Library to read and write Json Data to or from Dataclass

```<code>ListDataClass listrecord=new ObjectMapper().readValue(taskresponse.getResults().toString(),ListdataClass.class);
</code>```

Now you can loop through Listrecord like

```<code>    for(Dataclass val:listrecord){
    //get any property value from val Object
    //There cannot be nullPointerException

    int estimate=val.getEstimate();
    int actual=val.getActual();
    //etc
    //if json Object has empty value for any element then ObjectMapper will
// fill the default value for that element

    }
</code>```

Body:
I fire a query and the result comes in JSON.I set it using setters.here is my Dataclass:

private String userstory;
private String task;
private int actual;
private int estimate;
private String ref;
private String uid;
private String tid;
--setters--

Here is my main class:

for(JsonElement result : taskresponse.getResults())
    {
        JsonObject results = result.getAsJsonObject();
        MyData myData = new MyData(results.get("WorkProduct").getAsJsonObject().get("Name").getAsString(),results.get("Name").getAsString(),
        (int) Double.parseDouble(results.get("Actuals").getAsString()),
        (int) Double.parseDouble(results.get("Estimate").getAsString()),
        results.get("_ref").getAsString(),
        results.get("WorkProduct").getAsJsonObject().get("FormattedID").getAsString(),results.get("FormattedID").getAsString());
        data_list.add(myData);
    }

When I get value int in fields "Actuals" and "Estimate" it is working well. But sometimes I get values null as the result from query. Thus I get JSONNULLEXCEPTION.
How should i handle this exception.I ultimately want the fields to be set 0 when query returns null.
Thanks

Body:
As you have your Dataclass ,you  create a another ArrayList Data Class like

public class ListdataClass {
private ArrayList<Dataclass>  listdata;
//getter and setter for listdata`

}

now you Add ObjectMapper Library to read and write Json Data to or from Dataclass

ListDataClass listrecord=new ObjectMapper().readValue(taskresponse.getResults().toString(),ListdataClass.class);

Now you can loop through Listrecord like

    for(Dataclass val:listrecord){
    //get any property value from val Object
    //There cannot be nullPointerException

    int estimate=val.getEstimate();
    int actual=val.getActual();
    //etc
    //if json Object has empty value for any element then ObjectMapper will
// fill the default value for that element

    }


问:
How to get the previous value of int[] to be added by two int values using java 5
I want to get the sum of the stored int values of int[] array. the code still have errors. are there any codes that would make this line of codes look simplified? I want to make the 52 weeks money challenge app without database.

I have this formula: iA + sum = total[] + aA = tA;

I am having an error of the previous value not being added by preceding value.

PS. weeks, iA (Initial Amount), aA (Adding Amount), sum, sT are int. the tA's are now being added to the total[].

PSS: For everyone who flagged this question which have duplicate question, I already saw that question and it doesn't answer what my question is. The post have its own values created by the programmer/coder, I am asking for how to add the previous element to the values of two added integer values. I already tried the solution given in that question, and it's not working for my code. It gives different value (the unwanted value).

```<code>int[] total = new int[weeks + 1];
        int sum = 0;
        int tA = 0;
        int ai = 0;

        for(int sT = 1 ; sT <= weeks; sT++){ // error
            sum += iA;
            System.out.println("The payable for the week " + sT + " is: " + sum);
            total[sT] = sum;
            tA = total[sT];
            if(sT == 1){
                System.out.println("if: " + tA);
            }
            else if(sT == 2){
                tA += iA;
                System.out.println("else if: " + tA);
            }
            else{
                tA += aA;
                System.out.println("else: " + tA);
            }
        }
    System.out.println(Arrays.toString(total)); //print stored values of array
</code>```

答:
the question already has an answer.</p>

```<code>for(int sT = 1 ; sT <= weeks; sT++){
            sum += iA;
            System.out.println("The payable for the week " + sT + " is: " + sum);
            tA = sum;
            if(sT == 1){
                System.out.println("if: " + tA);
                total[sT] = tA;
            }
            else if(sT == 2){
                tA = iA + sum;
                System.out.println("else if: " + tA);
                total[sT] = tA;
            }
            else{
                tA = sum + total[sT - 1];
                System.out.println("else: " + tA);
                total[sT] = tA;
            }
        }
    System.out.println(Arrays.toString(total)); //print stored values of array
</code>```

Body:
I want to get the sum of the stored int values of int[] array. the code still have errors. are there any codes that would make this line of codes look simplified? I want to make the 52 weeks money challenge app without database.

I have this formula: iA + sum = total[] + aA = tA;

I am having an error of the previous value not being added by preceding value.

PS. weeks, iA (Initial Amount), aA (Adding Amount), sum, sT are int. the tA's are now being added to the total[].

PSS: For everyone who flagged this question which have duplicate question, I already saw that question and it doesn't answer what my question is. The post have its own values created by the programmer/coder, I am asking for how to add the previous element to the values of two added integer values. I already tried the solution given in that question, and it's not working for my code. It gives different value (the unwanted value).

int[] total = new int[weeks + 1];
        int sum = 0;
        int tA = 0;
        int ai = 0;

        for(int sT = 1 ; sT <= weeks; sT++){ // error
            sum += iA;
            System.out.println("The payable for the week " + sT + " is: " + sum);
            total[sT] = sum;
            tA = total[sT];
            if(sT == 1){
                System.out.println("if: " + tA);
            }
            else if(sT == 2){
                tA += iA;
                System.out.println("else if: " + tA);
            }
            else{
                tA += aA;
                System.out.println("else: " + tA);
            }
        }
    System.out.println(Arrays.toString(total)); //print stored values of array

Body:
the question already has an answer.

for(int sT = 1 ; sT <= weeks; sT++){
            sum += iA;
            System.out.println("The payable for the week " + sT + " is: " + sum);
            tA = sum;
            if(sT == 1){
                System.out.println("if: " + tA);
                total[sT] = tA;
            }
            else if(sT == 2){
                tA = iA + sum;
                System.out.println("else if: " + tA);
                total[sT] = tA;
            }
            else{
                tA = sum + total[sT - 1];
                System.out.println("else: " + tA);
                total[sT] = tA;
            }
        }
    System.out.println(Arrays.toString(total)); //print stored values of array


问:
method in class can not be applied to given type
I made a class called that creates a constructer and a method.

```<code>public class Car
{
private double speed;
private String make;
private int year;

public Car(int year, String make, double speed) {
this.year = year;
this.make = make;
this.speed = speed;
}

public String getMake(){
  return make;
}
public double getSpeed(){
  return speed;
}
public int getYear(){
     return year;
}

  public void accelerate (double speed)
{
        speed = speed + 1.00;
}

}
</code>```

the only problem i am having here is that when I go to my driver class to try and run it, this is the error I'm receiving

```<code>public class CarTester
{
public static void main (String[] args){

Car p1 = new Car(2010, "toyota", 4.50);
Car.accelerate();
Car.accelerate();

}
}
</code>```

"error: method accelerate in class Car cannot be applied to given types"

why is that so? because it says "required: double" but the "speed" variable is a double?

答:
```<code>public static void main (String[] args)
</code>```

{ Car c = new Car(2010, "toyota", 4.50); c.accelerate(); System.out.println(c.getSpeed()); }

The code should be like this, called through any object c instead of class Car.

Body:
I made a class called that creates a constructer and a method.

public class Car
{
private double speed;
private String make;
private int year;

public Car(int year, String make, double speed) {
this.year = year;
this.make = make;
this.speed = speed;
}

public String getMake(){
  return make;
}
public double getSpeed(){
  return speed;
}
public int getYear(){
     return year;
}

  public void accelerate (double speed)
{
        speed = speed + 1.00;
}

}

the only problem i am having here is that when I go to my driver class to try and run it, this is the error I'm receiving

public class CarTester
{
public static void main (String[] args){

Car p1 = new Car(2010, "toyota", 4.50);
Car.accelerate();
Car.accelerate();

}
}

"error: method accelerate in class Car cannot be applied to given types"

why is that so? because it says "required: double" but the "speed" variable is a double?

Body:
public static void main (String[] args)

{ Car c = new Car(2010, "toyota", 4.50); c.accelerate(); System.out.println(c.getSpeed()); }

The code should be like this, called through any object c instead of class Car.


问:
Linux: remove file extensions for multiple files
I have many files with .txt extension.
How to remove .txt extension for multiple files in linux?

I found that

```<code>rename .old .new *.old
</code>```

substitutes .old extension to the .new

Also I want to do this for files in sub-folders.

答:
In case it helps, here's how I do it with zsh:

```<code>for f in ./**/*.old; do
    mv "${f}" "${f%.old}"
done
</code>```

The ${x%pattern} construct in zsh removes the shortest occurence of pattern at the end of $x. Here it is abstracted as a function:

```<code>function chgext () {
    local srcext=".old"
    local dstext=""
    local dir="."

    [[ "$#" -ge 1 ]] && srcext="$1"
    [[ "$#" -gt 2 ]] && dstext="$2" dir="$3" || dir="${2:-.}"

    local bname=''
    for f in "${dir}"/**/*"${srcext}"; do
        bname="${f%${srcext}}"
        echo "${bname}{${srcext} → ${dstext}}"
        mv "${f}" "${bname}${dstext}"
    done
}
</code>```

Usage:

```<code>chgext
chgext src
chgext src dir
chgext src dst dir

Where `src` is the extension to find (default: ".old")
      `dst` is the extension to replace with (default: "")
      `dir` is the directory to act on (default: ".")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have many files with .txt extension.
How to remove .txt extension for multiple files in linux?

I found that

rename .old .new *.old

substitutes .old extension to the .new

Also I want to do this for files in sub-folders.

Body:
In case it helps, here's how I do it with zsh:

for f in ./**/*.old; do
    mv "${f}" "${f%.old}"
done

The ${x%pattern} construct in zsh removes the shortest occurence of pattern at the end of $x. Here it is abstracted as a function:

function chgext () {
    local srcext=".old"
    local dstext=""
    local dir="."

    [[ "$#" -ge 1 ]] && srcext="$1"
    [[ "$#" -gt 2 ]] && dstext="$2" dir="$3" || dir="${2:-.}"

    local bname=''
    for f in "${dir}"/**/*"${srcext}"; do
        bname="${f%${srcext}}"
        echo "${bname}{${srcext} → ${dstext}}"
        mv "${f}" "${bname}${dstext}"
    done
}

Usage:

chgext
chgext src
chgext src dir
chgext src dst dir

Where `src` is the extension to find (default: ".old")
      `dst` is the extension to replace with (default: "")
      `dir` is the directory to act on (default: ".")


问:
C#: Merge uniform with figure code?
I have a figure code which detects what pieces of clothing a user is wearing. Here are some examples of some random figure codes.

```<code>lg-285-76.hr-155-31.sh-300-92.ca-1819-63.hd-209-2.ch-3030-76.
he-3149-1331.sh-3035-110.hr-170-61.fa-3276-72.ch-255-110.hd-209-2.lg-280-1331.
ch-210-110.hd-209-7.hr-828-1407.he-3082-63.lg-280-1408.cp-3309-77.sh-290-92.
</code>```

The two-letter codes indicate the type of clothing, for example:

lg = leg

ch = chest

sh = shoes

he = head

hr = hair

What I want to do is to merge that figure code with a uniform code. Lets say I have a uniform code that I wanted the figure code to be merged with, and that this uniform contained a tshirt and trousers. It would contain the lg tag for leg and the ch tag for chest.

Uniform string: lg-285-76.sh-300-92.ch-3030-76.

What I want to do is to replace the legs, chest etc in the main figure code, and replace them with the one in the uniform string, here is what I have tried so far:

```<code>public static string ReturnUniform(string uniform, string figure)
{
    string[] uniformParts = uniform.Split('.');
    string[] figureParts = uniform.Split('.');

    foreach (string uniformPart in uniformParts)
    {
        string[] childUniformParts = uniformPart.Split('-');

        if (figure.Contains("." + childUniformParts[0]))
        {
            // remove it from figure parts and replace it with the uniform one here
        }
    }

    return string.Join("", figureParts);
}
</code>```

答:
I suggest using Linq and regular expressions (to parse each line):

```<code>  string[] figures = new string[] {
    "lg-285-76.hr-155-31.sh-300-92.ca-1819-63.hd-209-2.ch-3030-76.",
    "he-3149-1331.sh-3035-110.hr-170-61.fa-3276-72.ch-255-110.hd-209-2.lg-280-1331.",
    "ch-210-110.hd-209-7.hr-828-1407.he-3082-63.lg-280-1408.cp-3309-77.sh-290-92.",
  };

  // we want "lg", "sh", "ch" in this particular order
  string[] itemsToGet = new string[] { "lg", "sh", "ch" };

  var result = figures
    .Select(figure => Regex
       // Parse each line into name  (e.g. "sh")
       //                      value (e.g. "3035-110")
       //                      index in the itemsToGet (-1 if absent)
       // with a help of regular expression
      .Matches(figure, @"(?<name>[a-z]+)-(?<value>[0-9]+-[0-9]+)\.")
      .OfType<Match>()
      .Select(match => new {
         name = match.Groups["name"].Value,
         value = match.Groups["value"].Value,
         index = Array.IndexOf(itemsToGet, match.Groups["name"].Value) })
       // we want items' names that are presented in itemsToGet only...
      .Where(item => item.index >= 0)
       // ... and in the right order (as they mentioned in itemsToGet)
      .OrderBy(item => item.index)
       // item format: "name.value."
       // $"..." (string interpolation) is a C# 6.0 syntax; C# 5.0- alternative
       // .Select(item => string.Format("{0}.{1}.", item.name, item.value))
      .Select(item => $"{item.name}.{item.value}."))
     // concat all the items back into a string e.g. "lg.285-76.sh.300-92.ch.3030-76."
    .Select(items => string.Concat(items))
     // finally, let's materialize records into an array
    .ToArray();
</code>```

Test:

```<code>   Console.Write(string.Join(Environment.NewLine, result));
</code>```

Outcome (extracted itemsToGet names, order preserved):

```<code>lg.285-76.sh.300-92.ch.3030-76.
lg.280-1331.sh.3035-110.ch.255-110.
lg.280-1408.sh.290-92.ch.210-110.
</code>```

Title: C#: Merge uniform with figure code?

Body:
I have a figure code which detects what pieces of clothing a user is wearing. Here are some examples of some random figure codes.

lg-285-76.hr-155-31.sh-300-92.ca-1819-63.hd-209-2.ch-3030-76.
he-3149-1331.sh-3035-110.hr-170-61.fa-3276-72.ch-255-110.hd-209-2.lg-280-1331.
ch-210-110.hd-209-7.hr-828-1407.he-3082-63.lg-280-1408.cp-3309-77.sh-290-92.

The two-letter codes indicate the type of clothing, for example:

lg = leg

ch = chest

sh = shoes

he = head

hr = hair

What I want to do is to merge that figure code with a uniform code. Lets say I have a uniform code that I wanted the figure code to be merged with, and that this uniform contained a tshirt and trousers. It would contain the lg tag for leg and the ch tag for chest.

Uniform string: lg-285-76.sh-300-92.ch-3030-76.

What I want to do is to replace the legs, chest etc in the main figure code, and replace them with the one in the uniform string, here is what I have tried so far:

public static string ReturnUniform(string uniform, string figure)
{
    string[] uniformParts = uniform.Split('.');
    string[] figureParts = uniform.Split('.');

    foreach (string uniformPart in uniformParts)
    {
        string[] childUniformParts = uniformPart.Split('-');

        if (figure.Contains("." + childUniformParts[0]))
        {
            // remove it from figure parts and replace it with the uniform one here
        }
    }

    return string.Join("", figureParts);
}

Body:
I suggest using Linq and regular expressions (to parse each line):

  string[] figures = new string[] {
    "lg-285-76.hr-155-31.sh-300-92.ca-1819-63.hd-209-2.ch-3030-76.",
    "he-3149-1331.sh-3035-110.hr-170-61.fa-3276-72.ch-255-110.hd-209-2.lg-280-1331.",
    "ch-210-110.hd-209-7.hr-828-1407.he-3082-63.lg-280-1408.cp-3309-77.sh-290-92.",
  };

  // we want "lg", "sh", "ch" in this particular order
  string[] itemsToGet = new string[] { "lg", "sh", "ch" };

  var result = figures
    .Select(figure => Regex
       // Parse each line into name  (e.g. "sh")
       //                      value (e.g. "3035-110")
       //                      index in the itemsToGet (-1 if absent)
       // with a help of regular expression
      .Matches(figure, @"(?<name>[a-z]+)-(?<value>[0-9]+-[0-9]+)\.")
      .OfType<Match>()
      .Select(match => new {
         name = match.Groups["name"].Value,
         value = match.Groups["value"].Value,
         index = Array.IndexOf(itemsToGet, match.Groups["name"].Value) })
       // we want items' names that are presented in itemsToGet only...
      .Where(item => item.index >= 0)
       // ... and in the right order (as they mentioned in itemsToGet)
      .OrderBy(item => item.index)
       // item format: "name.value."
       // $"..." (string interpolation) is a C# 6.0 syntax; C# 5.0- alternative
       // .Select(item => string.Format("{0}.{1}.", item.name, item.value))
      .Select(item => $"{item.name}.{item.value}."))
     // concat all the items back into a string e.g. "lg.285-76.sh.300-92.ch.3030-76."
    .Select(items => string.Concat(items))
     // finally, let's materialize records into an array
    .ToArray();

Test:

   Console.Write(string.Join(Environment.NewLine, result));

Outcome (extracted itemsToGet names, order preserved):

lg.285-76.sh.300-92.ch.3030-76.
lg.280-1331.sh.3035-110.ch.255-110.
lg.280-1408.sh.290-92.ch.210-110.


答:
Ok i fix the button events, if you put these it works perfectly perfectly

```<code>function buttonOne() {
    if (income-500>=0){
    a++;
    document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
    income-=500;
    document.getElementById("HeaderLabel").innerHTML = "<b> OK, good, now lets watch as your money starts to generate slowly but surely. <p> After all no empire was built in a day. <p> When you have enough money you can buy more units." ;

    window.setInterval (function move() {
    var elem = document.getElementById("myprogbar1");
    var width = 1;
    var id = setInterval(frame, 4);
    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
        }
    }
}, 1000)
}
}

function buttonTwo() {
    if (income-1000>=0){
    b++;
    document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
    income-=1000;

    window.setInterval (function move() {
    var elem = document.getElementById("myprogbar2");
    var width = 1;
    var id = setInterval(frame, 9);
    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
        }
    }
}, 2000)
}
}

function buttonThree() {
    if (income-2000>=0){
    c++;
    document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
    income-=2000;

    window.setInterval (function move() {
    var elem = document.getElementById("myprogbar3");
    var width = 1;
    var id = setInterval(frame, 19);
    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
        }
    }
}, 3000)
}
}
</code>```

I just checked if your money less the unit cost would be static greater or equal to zero

```<code>if (income-2000>=0){ ... }
</code>```

Title: How to stop a value from going into negative value

Body:
Ok i fix the button events, if you put these it works perfectly perfectly

function buttonOne() {
    if (income-500>=0){
    a++;
    document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
    income-=500;
    document.getElementById("HeaderLabel").innerHTML = "<b> OK, good, now lets watch as your money starts to generate slowly but surely. <p> After all no empire was built in a day. <p> When you have enough money you can buy more units." ;

    window.setInterval (function move() {
    var elem = document.getElementById("myprogbar1");
    var width = 1;
    var id = setInterval(frame, 4);
    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
        }
    }
}, 1000)
}
}

function buttonTwo() {
    if (income-1000>=0){
    b++;
    document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
    income-=1000;

    window.setInterval (function move() {
    var elem = document.getElementById("myprogbar2");
    var width = 1;
    var id = setInterval(frame, 9);
    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
        }
    }
}, 2000)
}
}

function buttonThree() {
    if (income-2000>=0){
    c++;
    document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
    income-=2000;

    window.setInterval (function move() {
    var elem = document.getElementById("myprogbar3");
    var width = 1;
    var id = setInterval(frame, 19);
    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
        }
    }
}, 3000)
}
}

I just checked if your money less the unit cost would be static greater or equal to zero

if (income-2000>=0){ ... }


问:
Java ComboBox will not get populated
I have tried everything to figure out why my combobox will not get populated but nothing works.

In my FXML file I have.

```<code><ComboBox fx:id="comboBox" layoutX="162.0" layoutY="15.0" prefHeight="25.0" prefWidth="334.0" promptText="Select past popular pizza" />
</code>```

In my controller I have the following

```<code>public class ServeController {
public ObservableList<String> pizzas1 = FXCollections.observableArrayList();
@FXML public ComboBox<String> comboBox;
private void initialize() {
comboBox.getItems().addAll(
        "jacob.smith@example.com",
        "isabella.johnson@example.com",
        "ethan.williams@example.com",
        "emma.jones@example.com",
        "michael.brown@example.com"
    );
}
</code>```

I have even tried with

```<code>public ObservableList<String> pizzas1 = FXCollections.observableArrayList("1","2","3","4");
</code>```

to try to get some kind of data to show up but nothing seems to be working.

答:
I assume that you are initalizing controller in "standard" way. I'm guesing that private void initialize() method is never invoked. Your ServeController does not implement Initializable interface. Correct code should look as following:

```<code>public class ServeController implements Initializable {

    public ObservableList<String> pizzas1 = FXCollections.observableArrayList();

    @FXML
    public ComboBox<String> comboBox;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        comboBox.getItems().addAll(
                "jacob.smith@example.com",
                "isabella.johnson@example.com",
                "ethan.williams@example.com",
                "emma.jones@example.com",
                "michael.brown@example.com"
        );
    }
}
</code>```

Title: Java ComboBox will not get populated

Body:
I have tried everything to figure out why my combobox will not get populated but nothing works.

In my FXML file I have.

<ComboBox fx:id="comboBox" layoutX="162.0" layoutY="15.0" prefHeight="25.0" prefWidth="334.0" promptText="Select past popular pizza" />

In my controller I have the following

public class ServeController {
public ObservableList<String> pizzas1 = FXCollections.observableArrayList();
@FXML public ComboBox<String> comboBox;
private void initialize() {
comboBox.getItems().addAll(
        "jacob.smith@example.com",
        "isabella.johnson@example.com",
        "ethan.williams@example.com",
        "emma.jones@example.com",
        "michael.brown@example.com"
    );
}

I have even tried with

public ObservableList<String> pizzas1 = FXCollections.observableArrayList("1","2","3","4");

to try to get some kind of data to show up but nothing seems to be working.

Body:
I assume that you are initalizing controller in "standard" way. I'm guesing that private void initialize() method is never invoked. Your ServeController does not implement Initializable interface. Correct code should look as following:

public class ServeController implements Initializable {

    public ObservableList<String> pizzas1 = FXCollections.observableArrayList();

    @FXML
    public ComboBox<String> comboBox;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        comboBox.getItems().addAll(
                "jacob.smith@example.com",
                "isabella.johnson@example.com",
                "ethan.williams@example.com",
                "emma.jones@example.com",
                "michael.brown@example.com"
        );
    }
}


问:
extract certain emails from a given list of email matching few conditions
This question was asked in a recent job interview I gave and I was unable to answer it. Here is the question:

From a given email list (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com) extract only those emails ending with (@noemail.com, @no-email.com, and @no email.com).

I searched and tried to run the code but it didn't ran.

```<code><?php

  $email_list = (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com);

  $pattern = ('@noemail.com', '@no-email.com', '@no email.com' );

  echo preg_match($pattern, $email_list);

?>
</code>```

答:
```<code><?php

$email_list = array("johndoe@noemail.com", "xyz@no-email.com", "noemail@xyz.com", "answers@no email.com", "jpt@nooooemail.com", "kondoe@nomail.com");
$matchlist = array("@noemail.com", "@no-email.com", "@no email.com");

function str_contains($haystack, $needle) {
    return (strpos($haystack, $needle) !== false);
}

foreach ($email_list as $email) {
    foreach($matchlist as $match) {
        if (str_contains($email, $match)) {
            echo $email . "<br>";
            break;
        }
    }
}
</code>```

Not the perfect way, but works.

Body:
This question was asked in a recent job interview I gave and I was unable to answer it. Here is the question:

From a given email list (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com) extract only those emails ending with (@noemail.com, @no-email.com, and @no email.com).

I searched and tried to run the code but it didn't ran.

<?php

  $email_list = (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com);

  $pattern = ('@noemail.com', '@no-email.com', '@no email.com' );

  echo preg_match($pattern, $email_list);

?>

Body:
<?php

$email_list = array("johndoe@noemail.com", "xyz@no-email.com", "noemail@xyz.com", "answers@no email.com", "jpt@nooooemail.com", "kondoe@nomail.com");
$matchlist = array("@noemail.com", "@no-email.com", "@no email.com");

function str_contains($haystack, $needle) {
    return (strpos($haystack, $needle) !== false);
}

foreach ($email_list as $email) {
    foreach($matchlist as $match) {
        if (str_contains($email, $match)) {
            echo $email . "<br>";
            break;
        }
    }
}

Not the perfect way, but works.


问:
Marker didtap cannot pass data to View Controller
When my marker on click view popup a View Controller to show the detail of the marker.
But now the problem I face is data is no pass to the View Controller.
I am using for loop to loop my marker.

and this is my View Controller for Google Maps:

```<code>class locationViewController: UIViewController, GMSMapViewDelegate {

@IBOutlet weak var googleMapView: UIView!

@IBOutlet weak var menuView: UIView!

var mapView:GMSMapView?
var popUptitle : String?
var popupaddress : String?
var popuptime : String?
var popupphone : String?

struct State {
    let name: String
    let long: CLLocationDegrees
    let lat: CLLocationDegrees
    let phone : String
    let address : String
    let time : String
}

override func viewDidLoad() {

    super.viewDidLoad()

    let A = GMSCameraPosition.camera(withLatitude: 2.1898683, longitude: 102.2464156, zoom: 13)
    mapView = GMSMapView.map(withFrame:self.view.bounds, camera: A)
    mapView?.delegate = self

    let states = [
        State(name: "A", long: 102.2464156, lat: 2.1898683,phone: "1234", address: "A Address",time:"11AM - 10PM"),
        State(name: "B", long: 102.249949, lat: 2.189052,phone: "Tel No: 5678", address: "B Address",time:"11AM - 10PM"),
        State(name: "C", long: 102.252837, lat: 2.205183,phone: "Tel No: 9012", address: "C Address",time:"11AM - 10PM")

    ]
    for state in states {
        let markerPosition = CLLocationCoordinate2DMake(state.lat, state.long)
        let marker = GMSMarker(position:markerPosition)
        marker.icon = UIImage(named: "custom_marker")
        marker.map = mapView
        popUptitle = state.name
        popupaddress = state.address
        popupphone = state.phone
        popuptime = state.time
    }

    self.googleMapView.addSubview(mapView!)
    self.mapView?.addSubview(menuView)
    menuView.isHidden = true
    }

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    let popup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "marker_popup") as! MarkerPopupViewController
    self.addChildViewController(popup)
    popup.view.frame =  self.view.bounds
    self.view.addSubview(popup.view)
    popup.didMove(toParentViewController: self)
    popup.marker_name = popUptitle
    popup.marker_address = popupaddress
    popup.marker_time = popuptime
    popup.marker_pn = popupphone
    return true
}
</code>```

This is my custom info Window View Controller

```<code>import UIKit

class MarkerPopupViewController: UIViewController {

var marker_name : String?
var marker_address : String?
var marker_time : String?
var marker_pn : String?

@IBOutlet weak var outlet_pn: UILabel!
@IBOutlet weak var outlet_time: UILabel!
@IBOutlet weak var outlet_address: UILabel!
@IBOutlet weak var outlet_name: UILabel!
@IBOutlet weak var outlet_img: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    self.outlet_name.text = marker_name
    self.outlet_time.text = marker_time
    self.outlet_address.text = marker_address
    self.outlet_pn.text = marker_pn
    self.outlet_address.sizeToFit()
}
@IBAction func marker_close(_ sender: Any) {
    self.view.removeFromSuperview()
}

@IBAction func callBtn(_ sender: Any) {
}
@IBAction func directionBtn(_ sender: Any) {
}

}
</code>```

答:
Change the order of the lines to

```<code>func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    let popup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "marker_popup") as! MarkerPopupViewController
    popup.marker_name = popUptitle
    popup.marker_address = popupaddress
    popup.marker_time = popuptime
    popup.marker_pn = popupphone
    popup.view.frame =  self.view.bounds
    self.addChildViewController(popup)
    self.view.addSubview(popup.view)
    popup.didMove(toParentViewController: self)
    return true
}
</code>```

Body:
When my marker on click view popup a View Controller to show the detail of the marker.
But now the problem I face is data is no pass to the View Controller.
I am using for loop to loop my marker.

and this is my View Controller for Google Maps:

class locationViewController: UIViewController, GMSMapViewDelegate {

@IBOutlet weak var googleMapView: UIView!

@IBOutlet weak var menuView: UIView!

var mapView:GMSMapView?
var popUptitle : String?
var popupaddress : String?
var popuptime : String?
var popupphone : String?

struct State {
    let name: String
    let long: CLLocationDegrees
    let lat: CLLocationDegrees
    let phone : String
    let address : String
    let time : String
}

override func viewDidLoad() {

    super.viewDidLoad()

    let A = GMSCameraPosition.camera(withLatitude: 2.1898683, longitude: 102.2464156, zoom: 13)
    mapView = GMSMapView.map(withFrame:self.view.bounds, camera: A)
    mapView?.delegate = self

    let states = [
        State(name: "A", long: 102.2464156, lat: 2.1898683,phone: "1234", address: "A Address",time:"11AM - 10PM"),
        State(name: "B", long: 102.249949, lat: 2.189052,phone: "Tel No: 5678", address: "B Address",time:"11AM - 10PM"),
        State(name: "C", long: 102.252837, lat: 2.205183,phone: "Tel No: 9012", address: "C Address",time:"11AM - 10PM")

    ]
    for state in states {
        let markerPosition = CLLocationCoordinate2DMake(state.lat, state.long)
        let marker = GMSMarker(position:markerPosition)
        marker.icon = UIImage(named: "custom_marker")
        marker.map = mapView
        popUptitle = state.name
        popupaddress = state.address
        popupphone = state.phone
        popuptime = state.time
    }

    self.googleMapView.addSubview(mapView!)
    self.mapView?.addSubview(menuView)
    menuView.isHidden = true
    }

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    let popup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "marker_popup") as! MarkerPopupViewController
    self.addChildViewController(popup)
    popup.view.frame =  self.view.bounds
    self.view.addSubview(popup.view)
    popup.didMove(toParentViewController: self)
    popup.marker_name = popUptitle
    popup.marker_address = popupaddress
    popup.marker_time = popuptime
    popup.marker_pn = popupphone
    return true
}

This is my custom info Window View Controller

import UIKit

class MarkerPopupViewController: UIViewController {

var marker_name : String?
var marker_address : String?
var marker_time : String?
var marker_pn : String?

@IBOutlet weak var outlet_pn: UILabel!
@IBOutlet weak var outlet_time: UILabel!
@IBOutlet weak var outlet_address: UILabel!
@IBOutlet weak var outlet_name: UILabel!
@IBOutlet weak var outlet_img: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    self.outlet_name.text = marker_name
    self.outlet_time.text = marker_time
    self.outlet_address.text = marker_address
    self.outlet_pn.text = marker_pn
    self.outlet_address.sizeToFit()
}
@IBAction func marker_close(_ sender: Any) {
    self.view.removeFromSuperview()
}

@IBAction func callBtn(_ sender: Any) {
}
@IBAction func directionBtn(_ sender: Any) {
}

}

Body:
Change the order of the lines to

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    let popup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "marker_popup") as! MarkerPopupViewController
    popup.marker_name = popUptitle
    popup.marker_address = popupaddress
    popup.marker_time = popuptime
    popup.marker_pn = popupphone
    popup.view.frame =  self.view.bounds
    self.addChildViewController(popup)
    self.view.addSubview(popup.view)
    popup.didMove(toParentViewController: self)
    return true
}


问:
How to make this code to loop 10 times per page?
```<code><?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("dbsql", $con);

$result = mysql_query("SELECT * FROM testimonial where approved='Yes'");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Review</th>
<th>Date</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['full_name'] . "</td>";
  echo "<td>" . $row['review'] . "</td>";
    echo "<td>" . $row['date'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>
</code>```

答:
If you are looking for that specific block of data to loop 10 times every time the page is loaded simply use a for() loop

```<code>for($i=0;$i<10;$i++)
{
  // block of data
}
</code>```

But I assume that that is not what you are asking since it would be impractical (as far as I can see).

To print 10 results, add

```<code>limit 10
</code>```

to the end of your query. If you're using pagination, however, you will need to start the limit somewhere (e.g. limit STARTING_NUMBER, NUM_OF_RESULTS)

Good luck!

Dennis M.

Body:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("dbsql", $con);

$result = mysql_query("SELECT * FROM testimonial where approved='Yes'");

echo "

Firstname
Review
Date

";

while($row = mysql_fetch_array($result))
  {
  echo "
";
  echo "" . $row['full_name'] . "	";
  echo "" . $row['review'] . "	";
    echo "" . $row['date'] . "	";
  echo "
";
  }
echo "
";

mysql_close($con);
?>

Body:
If you are looking for that specific block of data to loop 10 times every time the page is loaded simply use a for() loop

for($i=0;$i<10;$i++)
{
  // block of data
}

But I assume that that is not what you are asking since it would be impractical (as far as I can see).

To print 10 results, add

limit 10

to the end of your query. If you're using pagination, however, you will need to start the limit somewhere (e.g. limit STARTING_NUMBER, NUM_OF_RESULTS)

Good luck!

Dennis M.


问:
Get latitude and longitude at 50 miles radius with reference to particular latitude and longitude
I have latitude and longitude value and want to find another lat long value at 50 miles of it. How to do that? Any formula or custom function to get that in php?</p>

答:
In php you could do it by fetching the records and using the below formula.
 But I would like you to use query to solve this problem. It's more efficient.

```<code>function getNearestUsers($givenLat,$givenLng)
{
   $res = [];
   $recs = getAllTheRecordsFromDb();
   foreach($recs as $r)
   {
      $distance = sqrt(POW((69.1 * ($r['lat'] - $givenLat)),2) + POW((69.1 * ($givenLng - $r['lng']) * cos($r['lat'] / 57.3)),2));
      if($distance<=50)  //50 miles
       {
          //some code
       }
   }
}
</code>```

Suppose you have user table which has userId, latitude and longitude. Below is sql query to get users who are in radius of 50 miles from the given latitude and longitude.

```<code>SELECT userId, latitude, longitude, SQRT(
    POW(69.1 * (latitude - [givenLat]), 2) +
    POW(69.1 * ([givenLng] - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM TableName HAVING distance < 50 ORDER BY distance;
</code>```

You could get more answer from referring the below link:
latitude/longitude find nearest latitude/longitude - complex sql or complex calculation

Body:
In php you could do it by fetching the records and using the below formula.
 But I would like you to use query to solve this problem. It's more efficient.

function getNearestUsers($givenLat,$givenLng)
{
   $res = [];
   $recs = getAllTheRecordsFromDb();
   foreach($recs as $r)
   {
      $distance = sqrt(POW((69.1 * ($r['lat'] - $givenLat)),2) + POW((69.1 * ($givenLng - $r['lng']) * cos($r['lat'] / 57.3)),2));
      if($distance<=50)  //50 miles
       {
          //some code
       }
   }
}

Suppose you have user table which has userId, latitude and longitude. Below is sql query to get users who are in radius of 50 miles from the given latitude and longitude.

SELECT userId, latitude, longitude, SQRT(
    POW(69.1 * (latitude - [givenLat]), 2) +
    POW(69.1 * ([givenLng] - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM TableName HAVING distance < 50 ORDER BY distance;

You could get more answer from referring the below link:
latitude/longitude find nearest latitude/longitude - complex sql or complex calculation