问:
How can I add drag n Drop functionality in image android?
I have three buttons in the main XML which contain add a table, and chair, reset.when I clicked add table it will add a table in second layout same for add chair.I want to move both images after adding in the second layout just like Drag and Drop.

Main activity which contains three buttons.on each button click, it will pass to second.java through intent

MainActivity.Java

```<code>public class MainActivity extends AppCompatActivity {

    private ArrayList<String> mSelecetdItems = new ArrayList<>();

    public static final String SELECETD_ITEMS = "SELECETD_ITEMS";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public  void addtable(View v){
        this.mSelecetdItems.add("table");
        showSecondActivity();
    }
    public  void addchair(View v){
        this.mSelecetdItems.add("chair");
        showSecondActivity();
    }

    private void showSecondActivity()
    {
        Intent i = new Intent(this,Second.class);
        i.putStringArrayListExtra(SELECETD_ITEMS,this.mSelecetdItems);
        startActivity(i);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putStringArrayList(SELECETD_ITEMS , mSelecetdItems);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        this.mSelecetdItems = savedInstanceState.getStringArrayList(SELECETD_ITEMS);
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andiroot.restaurantbook.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="#ff1e8622"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
      >
    </android.support.v7.widget.Toolbar>

    <RelativeLayout
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="64dp">

        <Button
            android:id="@+id/btn_addtbl"
            style="@style/Widget.AppCompat.Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="76dp"
            android:text="Add Table"
            android:onClick="addtable"/>

        <Button
            android:id="@+id/btn_addchairs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="addchair"
            android:layout_marginTop="27dp"
            android:text="Add Chair"
            android:layout_below="@+id/btn_addtbl"
            android:layout_alignEnd="@+id/btn_addtbl" />

        <Button
            android:id="@+id/btn_reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/btn_addchairs"
            android:layout_below="@+id/btn_addchairs"
            android:layout_marginTop="51dp"
            android:text="Reset" />
    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

Second.java

public class Second extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Toolbar toolbar = (Toolbar) findViewById(R.id.second_toolbar);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);

        /*toolbar.setNavigationIcon((R.drawable.back_arrow));

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });*/

        LinearLayoutCompat hall = (LinearLayoutCompat) findViewById(R.id.hall_layout);
        Intent i = getIntent();

        ArrayList<String> selecetdItems = i.getStringArrayListExtra(MainActivity.SELECETD_ITEMS);
        for (String selecetdItem : selecetdItems) {
            if (selecetdItem.equals("table")) {
                addImageView(R.drawable.table, hall);
            } else if (selecetdItem.equals("chair")) {
                addImageView2(R.drawable.chair2, hall);
            }
        }

    }

    private void addImageView(int imageRes, LinearLayoutCompat hall) {
        ImageView iv = new ImageView(this);
        iv.setImageResource(imageRes);
        iv.setLayoutParams(new android.view.ViewGroup.LayoutParams(250, 250));
        iv.setMaxHeight(180);
        iv.setMaxWidth(120);
        iv.setPadding(15,15,0,0);
        hall.addView(iv);
    }

    private void addImageView2(int imageRes, LinearLayoutCompat hall) {
        ImageView iv2 = new ImageView(this);
        iv2.setImageResource(imageRes);
        iv2.setLayoutParams(new android.view.ViewGroup.LayoutParams(150, 150));
        iv2.setMaxHeight(30);
        iv2.setMaxWidth(30);

        iv2.setPadding(25,0,0,0);
        hall.addView(iv2);
    }

activity_second.java

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/hall_layout"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andiroot.restaurantbook.Second">

    <android.support.v7.widget.Toolbar
        android:id="@+id/second_toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="#ff1e8622"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.widget.Toolbar>
<!--
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/hall_layout2">
    </RelativeLayout>
-->
</android.support.v7.widget.LinearLayoutCompat>
</code>```

答:
You need to implement onTouchListener on those images.</p>

```<code>  @Override
public boolean onTouch(View v, MotionEvent event) {
int width=cropperLayout.getLayoutParams().width;;
    int height=cropperLayout.getLayoutParams().height;
    switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:

            dX = v.getX() - event.getRawX();
            dY = v.getY() - event.getRawY();

            return true;

        case MotionEvent.ACTION_MOVE:

            if (width == windowWidth && height == windowHeight){}
            else {
                v.animate()
                        .x(event.getRawX() + dX)
                        .y(event.getRawY() + dY)
                        .setDuration(0)
                        .start();

                if (event.getRawX() + dX + width > windowWidth) {
                    v.animate()
                            .x(windowWidth - width)
                            .setDuration(0)
                            .start();
                }
                if (event.getRawX() + dX < 0) {
                    v.animate()
                            .x(0)
                            .setDuration(0)
                            .start();
                }
                if (event.getRawY() + dY + height > windowHeight) {
                    v.animate()
                            .y(windowHeight - height)
                            .setDuration(0)
                            .start();
                }
                if (event.getRawY() + dY < 0) {
                    v.animate()
                            .y(0)
                            .setDuration(0)
                            .start();
                }

                return true;
            }
  }
  }
</code>```

Body:
I have three buttons in the main XML which contain add a table, and chair, reset.when I clicked add table it will add a table in second layout same for add chair.I want to move both images after adding in the second layout just like Drag and Drop.

Main activity which contains three buttons.on each button click, it will pass to second.java through intent

MainActivity.Java

public class MainActivity extends AppCompatActivity {

    private ArrayList<String> mSelecetdItems = new ArrayList<>();

    public static final String SELECETD_ITEMS = "SELECETD_ITEMS";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public  void addtable(View v){
        this.mSelecetdItems.add("table");
        showSecondActivity();
    }
    public  void addchair(View v){
        this.mSelecetdItems.add("chair");
        showSecondActivity();
    }

    private void showSecondActivity()
    {
        Intent i = new Intent(this,Second.class);
        i.putStringArrayListExtra(SELECETD_ITEMS,this.mSelecetdItems);
        startActivity(i);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putStringArrayList(SELECETD_ITEMS , mSelecetdItems);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        this.mSelecetdItems = savedInstanceState.getStringArrayList(SELECETD_ITEMS);
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andiroot.restaurantbook.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="#ff1e8622"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
      >
    </android.support.v7.widget.Toolbar>

    <RelativeLayout
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="64dp">

        <Button
            android:id="@+id/btn_addtbl"
            style="@style/Widget.AppCompat.Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="76dp"
            android:text="Add Table"
            android:onClick="addtable"/>

        <Button
            android:id="@+id/btn_addchairs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="addchair"
            android:layout_marginTop="27dp"
            android:text="Add Chair"
            android:layout_below="@+id/btn_addtbl"
            android:layout_alignEnd="@+id/btn_addtbl" />

        <Button
            android:id="@+id/btn_reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/btn_addchairs"
            android:layout_below="@+id/btn_addchairs"
            android:layout_marginTop="51dp"
            android:text="Reset" />
    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

Second.java

public class Second extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Toolbar toolbar = (Toolbar) findViewById(R.id.second_toolbar);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);

        /*toolbar.setNavigationIcon((R.drawable.back_arrow));

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });*/

        LinearLayoutCompat hall = (LinearLayoutCompat) findViewById(R.id.hall_layout);
        Intent i = getIntent();

        ArrayList<String> selecetdItems = i.getStringArrayListExtra(MainActivity.SELECETD_ITEMS);
        for (String selecetdItem : selecetdItems) {
            if (selecetdItem.equals("table")) {
                addImageView(R.drawable.table, hall);
            } else if (selecetdItem.equals("chair")) {
                addImageView2(R.drawable.chair2, hall);
            }
        }

    }

    private void addImageView(int imageRes, LinearLayoutCompat hall) {
        ImageView iv = new ImageView(this);
        iv.setImageResource(imageRes);
        iv.setLayoutParams(new android.view.ViewGroup.LayoutParams(250, 250));
        iv.setMaxHeight(180);
        iv.setMaxWidth(120);
        iv.setPadding(15,15,0,0);
        hall.addView(iv);
    }

    private void addImageView2(int imageRes, LinearLayoutCompat hall) {
        ImageView iv2 = new ImageView(this);
        iv2.setImageResource(imageRes);
        iv2.setLayoutParams(new android.view.ViewGroup.LayoutParams(150, 150));
        iv2.setMaxHeight(30);
        iv2.setMaxWidth(30);

        iv2.setPadding(25,0,0,0);
        hall.addView(iv2);
    }

activity_second.java

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/hall_layout"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andiroot.restaurantbook.Second">

    <android.support.v7.widget.Toolbar
        android:id="@+id/second_toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="#ff1e8622"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.widget.Toolbar>

</android.support.v7.widget.LinearLayoutCompat>

Body:
You need to implement onTouchListener on those images.

  @Override
public boolean onTouch(View v, MotionEvent event) {
int width=cropperLayout.getLayoutParams().width;;
    int height=cropperLayout.getLayoutParams().height;
    switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:

            dX = v.getX() - event.getRawX();
            dY = v.getY() - event.getRawY();

            return true;

        case MotionEvent.ACTION_MOVE:

            if (width == windowWidth && height == windowHeight){}
            else {
                v.animate()
                        .x(event.getRawX() + dX)
                        .y(event.getRawY() + dY)
                        .setDuration(0)
                        .start();

                if (event.getRawX() + dX + width > windowWidth) {
                    v.animate()
                            .x(windowWidth - width)
                            .setDuration(0)
                            .start();
                }
                if (event.getRawX() + dX < 0) {
                    v.animate()
                            .x(0)
                            .setDuration(0)
                            .start();
                }
                if (event.getRawY() + dY + height > windowHeight) {
                    v.animate()
                            .y(windowHeight - height)
                            .setDuration(0)
                            .start();
                }
                if (event.getRawY() + dY < 0) {
                    v.animate()
                            .y(0)
                            .setDuration(0)
                            .start();
                }

                return true;
            }
  }
  }


来源: stackexchange

问:
MERGE statement DELETE alternative in SQL Server
I have a Query using T-SQL MERGE Statement. Due to performance issues I am re writing the Query using IF Exists Update and If Not Exists Insert. I am able to write Insert/Update without any issue. But I am unable to handle the DELETE. Can some one please help me on this?

Here is the sample

```<code>---SAMPLE MERGE STATEMENT
MERGE
   member_topic AS target
USING
   someOtherTable AS source
ON
   target.mt_member = source.mt_member

WHEN MATCHED THEN
   UPDATE SET target.mt_notes = source.mt_notes
WHEN NOT MATCHED THEN
   INSERT (mt_member, mt_topic, mt_notes) VALUES (source.mt_member, source.mt_notes)

WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;

--UPDATE

UPDATE T SET T.mt_notes = S.mt_notes
FROM member_topic T
JOIN someOtherTable S ON T.mt_member=S.mt_member

--INSERT

INSERT INTO member_topic(mt_member, mt_topic, mt_notes)
SELECT mt_member, mt_topic, mt_notes
FROM someOtherTable S
WHERE NOT EXISTS(SELECT 1
                 FROM member_topic T
                 WHERE T.mt_member=S.mt_member)
</code>```

How to handle

```<code>WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;
</code>```

in single DELETE Statement.

答:
```<code>DELETE t
FROM member_topic t
    LEFT JOIN someOtherTable s ON t.mt_member = s.mt_member
WHERE s.mt_member IS NULL
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Query using T-SQL MERGE Statement. Due to performance issues I am re writing the Query using IF Exists Update and If Not Exists Insert. I am able to write Insert/Update without any issue. But I am unable to handle the DELETE. Can some one please help me on this?

Here is the sample

---SAMPLE MERGE STATEMENT
MERGE
   member_topic AS target
USING
   someOtherTable AS source
ON
   target.mt_member = source.mt_member

WHEN MATCHED THEN
   UPDATE SET target.mt_notes = source.mt_notes
WHEN NOT MATCHED THEN
   INSERT (mt_member, mt_topic, mt_notes) VALUES (source.mt_member, source.mt_notes)

WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;

--UPDATE

UPDATE T SET T.mt_notes = S.mt_notes
FROM member_topic T
JOIN someOtherTable S ON T.mt_member=S.mt_member

--INSERT

INSERT INTO member_topic(mt_member, mt_topic, mt_notes)
SELECT mt_member, mt_topic, mt_notes
FROM someOtherTable S
WHERE NOT EXISTS(SELECT 1
                 FROM member_topic T
                 WHERE T.mt_member=S.mt_member)

How to handle

WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;

in single DELETE Statement.


问:
Queries about Teradata database connection

I am new to Teradata.

I need to connect Teradata database through ODBC connection in Tableau. For this requirement, I have installed below software.

1) Tableau Desktop

2) JDK 1.8

3) Teradata Studio Express 16.0

4) Teradata ODBC Driver

My Queries are,

1) Is it possible to create Teradata database using Teradata Studio Express? If yes means, Please provide steps?

2) How to ensure service is running for Teradata database server?

3) I think, need to run service for Teradata Studio Express to connect database throgh ODBC Driver. Is it correct?

Note: I am using windows platform.

答:
You don't need a 'service'. You connect to a already running server via its IP-address (this may be a VM on your loacal machine).

In your ODBC-Driver you create a connection to IP-Address, user, pasword. This ODBC-connection can be used from whatever Client you want to use, e.g. Tableau. Studio Express uses JDBC. Use similar parameters in configuration for a Connection.

The data space (which the server grants access to) is divided into databases, which you create via SQL-commands (create database ...) or from TD-Studio Administrative-View.


问:
Creating a Python window that dynamically updates with values read by RPi?
Novice when it comes to python and I need help creating a basic window that prints and updates the variables I have changing based on the readings the RPi collects. The window will display ON or OFF based on whether the voltages are >1.0 or <1.0. So far the variable 'values' just prints in the terminal.
My code so far:</p>

```<code>    import time
import spidev
import os
import sys
from windowex import *
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008

# Software SPI configuration:
CLK  = 12
MISO = 17
MOSI = 27
CS   = 22
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

x0 = "OFF"
x1 = "OFF"
x2 = "OFF"
x3 = "OFF"
x4 = "OFF"
x5 = "OFF"
x6 = "OFF"
x7 = "OFF"

y0 = "ON"
y1 = "ON"
y2 = "ON"
y3 = "ON"
y4 = "ON"
y5 = "ON"
y6 = "ON"
y7 = "ON"

# Main program loop.
while True:
    # Read all the ADC channel values in a list.
    values = [0]*8
    for i in range(8):
        # The read_adc function will get the value of the specified channel (0-7). rounds to nearest 2 decimals
        values[i] = round((mcp.read_adc(i)*(3.3/1023)),2)

#conditional statements for ON and OFF renaming
    if values[0] < 1.0:
         values[0] = x0
    else:
         values[0] = y0

    if values[1] < 1.0:
         values[1] = x1
    else:
         values[1] = y1

    if values[2] < 1.0:
         values[2] = x2
    else:
         values[2] = y2

    if values[3] < 1.0:
         values[3] = x3
    else:
         values[3] = y3

    if values[4] < 1.0:
         values[4] = x4
    else:
         values[4] = y4

    if values[5] < 1.0:
         values[5] = x5
    else:
         values[5] = y5

    if values[6] < 1.0:
         values[6] = x6
    else:
         values[6] = y6

    if values[7] < 1.0:
         values[7] = x7
    else:
         values[7] = y7

    print values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]

    time.sleep(0.5)
</code>```

答:
```<code>while True:
    # Read all the ADC channel values in a list.
    values = [0]*8
    output = ""
    for i in range(8):
        # The read_adc function will get the value of the specified channel (0-7). rounds to nearest 2 decimals
        values[i] = round((mcp.read_adc(i)*(3.3/1023)),2)
        output += "{}-{} ".format(i, "OFF" if values[i] < 1.0 else "ON" )
    print output
    time.sleep(0.5)

>> "0-ON 1-OFF 2-ON 3-OFF ..."
</code>```

<p>Why change the value to a string later just print if it is the range you want "ON/OFF". All the x0,x1,... are the same string, why do the need to be defined at all ? </p>

Body:
Novice when it comes to python and I need help creating a basic window that prints and updates the variables I have changing based on the readings the RPi collects. The window will display ON or OFF based on whether the voltages are >1.0 or <1.0. So far the variable 'values' just prints in the terminal.
My code so far:

    import time
import spidev
import os
import sys
from windowex import *
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008

# Software SPI configuration:
CLK  = 12
MISO = 17
MOSI = 27
CS   = 22
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

x0 = "OFF"
x1 = "OFF"
x2 = "OFF"
x3 = "OFF"
x4 = "OFF"
x5 = "OFF"
x6 = "OFF"
x7 = "OFF"

y0 = "ON"
y1 = "ON"
y2 = "ON"
y3 = "ON"
y4 = "ON"
y5 = "ON"
y6 = "ON"
y7 = "ON"

# Main program loop.
while True:
    # Read all the ADC channel values in a list.
    values = [0]*8
    for i in range(8):
        # The read_adc function will get the value of the specified channel (0-7). rounds to nearest 2 decimals
        values[i] = round((mcp.read_adc(i)*(3.3/1023)),2)

#conditional statements for ON and OFF renaming
    if values[0] < 1.0:
         values[0] = x0
    else:
         values[0] = y0

    if values[1] < 1.0:
         values[1] = x1
    else:
         values[1] = y1

    if values[2] < 1.0:
         values[2] = x2
    else:
         values[2] = y2

    if values[3] < 1.0:
         values[3] = x3
    else:
         values[3] = y3

    if values[4] < 1.0:
         values[4] = x4
    else:
         values[4] = y4

    if values[5] < 1.0:
         values[5] = x5
    else:
         values[5] = y5

    if values[6] < 1.0:
         values[6] = x6
    else:
         values[6] = y6

    if values[7] < 1.0:
         values[7] = x7
    else:
         values[7] = y7

    print values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]

    time.sleep(0.5)

Body:
while True:
    # Read all the ADC channel values in a list.
    values = [0]*8
    output = ""
    for i in range(8):
        # The read_adc function will get the value of the specified channel (0-7). rounds to nearest 2 decimals
        values[i] = round((mcp.read_adc(i)*(3.3/1023)),2)
        output += "{}-{} ".format(i, "OFF" if values[i] < 1.0 else "ON" )
    print output
    time.sleep(0.5)

>> "0-ON 1-OFF 2-ON 3-OFF ..."

Why change the value to a string later just print if it is the range you want "ON/OFF". All the x0,x1,... are the same string, why do the need to be defined at all ?


问:
How to list all timers of another form
I want to make a procedure that stops all timers of any given form. Though when building it says

"components' is not a member of 'System.Windows.Forms.Form".

Here is the code:

```<code>Public Sub _Timers_Stop(frm As Form)
        For Each itm As Object In frm.components.components
           If TypeOf (itm) Is Timer Then
               itm.stop()
           End If
        Next
End Sub
</code>```

答:
As I was corrected in the comments, the Controls collection does not contain components--it only contains controls.  The references to the non-visual components, such as timers, are held in a private Container field, typically called components.  That Container field is not a part of the base Form class at all.  It is declared and implemented separately, on each form that needs it, by the form designer.  Since it's not a member of the base class, there is no easy way to access it on any given form.  Even if it was a member of the base class, accessibility would still be an issue since it's typically declared as a private field.

The safe way to do this, which retains proper type-checking, would be to create an interface:

```<code>Public Interface IFormWithComponents
    ReadOnly Property Components As ComponentCollection
End Interface
</code>```

Which you could then implement on every form, as applicable:

```<code>Public Class MyForm
    Implements IFormWithComponents

    Public ReadOnly Property Components As ComponentCollection Implements IFormWithComponents.Components
        Get
            Return components.Components
        End Get
    End Property
End Class
</code>```

And then your timer-stopping method could take that interface as its parameter:

```<code>Public Sub _Timers_Stop(frm As IFormWithComponents)
    For Each t As Timer In frm.Components.Cast(Of Component).OfType(Of Timer)
       t.stop()
    Next
End Sub
</code>```

However, if you don't really care about the type-checking, and you don't mind the slight decrease in performance, you can alternatively use reflection to find the private field in the form object and extract its value:

```<code>Public Sub _Timers_Stop(frm As Form)
    Dim timers As IEnumerable(Of Timer) = frm.
        GetType().
        GetFields(BindingFlags.FlattenHierarchy Or BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.Public).
        Select(Function(fieldInfo) fieldInfo.GetValue(frm)).
        OfType(Of Container)().
        SelectMany(Function(container) container.Components.OfType(Of Timer)())
    For Each t As Timer In timers
        t.Stop()
    Next
End Sub
</code>```

Title: How to list all timers of another form

Body:
I want to make a procedure that stops all timers of any given form. Though when building it says

"components' is not a member of 'System.Windows.Forms.Form".

Here is the code:

Public Sub _Timers_Stop(frm As Form)
        For Each itm As Object In frm.components.components
           If TypeOf (itm) Is Timer Then
               itm.stop()
           End If
        Next
End Sub

Body:
As I was corrected in the comments, the Controls collection does not contain components--it only contains controls.  The references to the non-visual components, such as timers, are held in a private Container field, typically called components.  That Container field is not a part of the base Form class at all.  It is declared and implemented separately, on each form that needs it, by the form designer.  Since it's not a member of the base class, there is no easy way to access it on any given form.  Even if it was a member of the base class, accessibility would still be an issue since it's typically declared as a private field.

The safe way to do this, which retains proper type-checking, would be to create an interface:

Public Interface IFormWithComponents
    ReadOnly Property Components As ComponentCollection
End Interface

Which you could then implement on every form, as applicable:

Public Class MyForm
    Implements IFormWithComponents

    Public ReadOnly Property Components As ComponentCollection Implements IFormWithComponents.Components
        Get
            Return components.Components
        End Get
    End Property
End Class

And then your timer-stopping method could take that interface as its parameter:

Public Sub _Timers_Stop(frm As IFormWithComponents)
    For Each t As Timer In frm.Components.Cast(Of Component).OfType(Of Timer)
       t.stop()
    Next
End Sub

However, if you don't really care about the type-checking, and you don't mind the slight decrease in performance, you can alternatively use reflection to find the private field in the form object and extract its value:

Public Sub _Timers_Stop(frm As Form)
    Dim timers As IEnumerable(Of Timer) = frm.
        GetType().
        GetFields(BindingFlags.FlattenHierarchy Or BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.Public).
        Select(Function(fieldInfo) fieldInfo.GetValue(frm)).
        OfType(Of Container)().
        SelectMany(Function(container) container.Components.OfType(Of Timer)())
    For Each t As Timer In timers
        t.Stop()
    Next
End Sub


问:
How to test the spring check_token endpoint
The API is using the spring built in /oauth/check_token endpoint to validate the user with the basic auth. I can't seem to come up with any other scenario other than passing the invalid credentials.
Are there any other scenarios ?</p>

答:
to check this endpoint, you should have a valid unexpired token.
you need to pass client authentication in the Authorization header along with the access token.
curl example:
curl -X POST \ 'http://localhost:8080/oauth/check_token?token=' \
  -H 'accept: application/json' \
  -H 'authorization: Basic '

if the Client Auth and access token are valid you would get back the token details (in case of JWT, decoded token).


问:
How to manage hardcoded (VBA) EU date formats in Access when system locality is US
This is probably a shot in the dark and a little odd but here it goes.. We use an Access 2003 application built by a 3rd party.  It's REALLY horribly written but it calculates behavior measures with tons of scientific research and validation behind it.  This means that we CANNOT modify the application whatsoever.  To be clear we have requested even SMALL changes to be made or to allow us to make and we were denied (changing s to z in wording to be more US format)... based on the grounds that the application is validated and that any change in the application would make the outcome data void per that validation.

The above is important because we CANNOT make any direct changes to any asset inside the MDB file.  Any solutions MUST be a change in the behavior of Access and not a system wide change like changing locality.  Maybe a command line switch or something.

The problem exists that this application was written in a EU country and therefore conforms to EU locality standards hard coded into the VBA.  If there were a command line switch to force EU locality on Access during a single session this would be a great solution... I cannot find one however.

This issue only exposes itself with DATES in this application.

There is an access form that is used whenever date entry is required.  It pops up and requests month by NAME, day and year each it it's own field.  For example a birth date.  Since these fields are filled in separately the VBA code then concatenates them into a date... using EU format only..  Publisher did not take locality into consideration at all. So it places DAY FIRST instead of Month as the US format does.

This is a problem because the date conversions that Microsoft uses apparently doesn't consider EU formatted dates as invalid US dates and will happily convert them..  WRONG 30% of the time.

So what occurs is that a date of May 10, 2000 becomes October 10, 2000 because the date is converted to "DD/MM/YYYY' or 5/10/2000 becomes 10/5/2000.  10/5/2000 is a valid US formatted date but it's not the date entered by the user.  MS considers this a proper date for US, since technically it is,  but does not consider this an error in our date when a number above 12 is placed into the MONTH position.  13/5/2000 is not invalid when MS coverts it.. since there are only 12 months the MS algorithm apparently simply just identifies the date as EU format and converts it to US format... So, 13/5/2000 becomes May 13, 2000 even tho 13 is in a position that should be invalid for US locality but it is turned into the day of month and the 5 is turned into the Month number.  These types of dates come out correct because of this.. 5/13/2000 becomes 13/5/2000 but MS converts it back to 5/13/2000 however 5/10/2000 becomes 10/5/2000 and MS does NOT convert it back to 5/10/2000.

Hope you've followed that so far.

So, as I said, I need a solution that does not involve changing the application (forms, queries, vba or anything else because legally and scientifically we cannot) and does not involve changing system settings like locality.  Any solution needs to affect access only and also only affect it during the use of this single database ... ie: command line switch.

答:
You can try running Access using a locale emulator such as this one or this one (last one is no longer supported). Also, you can run it inside a VM, or on a different computer/server with correct locale settings and allow users to remotely connect to it.

As you can neither modify the database nor the locale settings, I don't see any other options.


问:
Round cap underline in CSS

Can you make round cap underlines (as in the above image) with CSS? How?

Is there a way to do this with border-bottom? border-radius produces this stylish effect instead:

答:
you can do that by using a div beneath the text and setting its border-radius to 2000px. i think that will be simpler

HTML:

```<code><div class="wrapper">
    <span>Hell World</span>
    <div class="underline"></div>
</div>
</code>```

CSS:

```<code>.underline{
    height:0px;border: 3px solid black;
    border-radius: 2000px;
}
.wrapper{
    display:inline-block;
}
</code>```

JQUERY SNIPPET:

```<code>var arbitrarynumber = 5
$('.underline').width($('.underline').parent().width()-arbitrarynumber)
</code>```

Title: Round cap underline in CSS

Body:
you can do that by using a div beneath the text and setting its border-radius to 2000px. i think that will be simpler

HTML:

<div class="wrapper">
    <span>Hell World</span>
    <div class="underline"></div>
</div>

CSS:

.underline{
    height:0px;border: 3px solid black;
    border-radius: 2000px;
}
.wrapper{
    display:inline-block;
}

JQUERY SNIPPET:

var arbitrarynumber = 5
$('.underline').width($('.underline').parent().width()-arbitrarynumber)


问:
jquery like lib in java
I am looking for a simple lightweight java library that parses HTML. I have looked a lot and there are many options out there. But I cannot find something simple. I really would like to have something like pyquery in python except in java. My requirements are: fast, easy to use and lightweight. </p>

<p>What do I need it for? Not sure if this matters, but I need to index parts of an html documents. So I am hoping to be able to select part of that document quickly and then parse it. </p>

答:
Look at Jerry which looks very promising
http://jodd.org/doc/jerry/</p>

Title: jquery like lib in java

Body:
I am looking for a simple lightweight java library that parses HTML. I have looked a lot and there are many options out there. But I cannot find something simple. I really would like to have something like pyquery in python except in java. My requirements are: fast, easy to use and lightweight.

What do I need it for? Not sure if this matters, but I need to index parts of an html documents. So I am hoping to be able to select part of that document quickly and then parse it.


问:
Swift Delegation: unexpectedly found nil while unwrapping an Optional value

Edit: Please note the question below discusses using delegation between
  2 viewcontrollers that are also implemented in a UITabBarController.

I've done a fair bit of searching here and on YouTube, but haven't seen my issue replicated elsewhere. I'll keep it to the point.

I have 2 view controllers that I coded myself -not generated by XCode-; TabOneController, and TabTwoController

below are the coding for both...

```<code>import UIKit

class TabOneController: UIViewController{

    private let instanceOfTabOneView = TabOneView()

    var vc1Delegate: fromOneToTwo!

    override func loadView() {

        super.loadView()

            view.addSubview(instanceOfTabOneView.buildTheVu())
                view.backgroundColor = UIColor.white

        runThisOnce()

        }

    func runThisOnce(){

        vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")

    }

}

protocol fromOneToTwo{

    func passTheValue(heroNameIs: String)

}
</code>```

as for tab 2...

```<code>import UIKit

class TabTwoController: UIViewController, fromOneToTwo{

    private let instanceOfTabTwoView = TabTwoView()

    override func loadView() {

        super.loadView()

            view.addSubview(instanceOfTabTwoView.buildTheVu())

        assignDelegateToSelf()

    }

    func assignDelegateToSelf(){

        let instanceTabOne = TabOneController()
            instanceTabOne.vc1Delegate = self

    }

    func passTheValue(heroNameIs:String){

        instanceOfTabTwoView.txtFld.text = heroNameIs

    }

}
</code>```

I'm getting the following error at runtime -the app builds successfully-...

fatal error: unexpectedly found nil while unwrapping an Optional value

on the following line...

```<code>vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")
</code>```

When I comment out the above line, the app builds and runs successfully, but of course the app doesn't execute the delegation.

I kinda understand what the compiler is trying to tell me, that the

```<code>vc1Delegate
</code>```

hasn't been instantiated -I guess-. But I searched under every rock, and can't seem to find how to get around this.

I'd appreciate any help or guidance. Sorry if my code seems immature, I'm new to Swift and programming in general. Thank you.

答:
First thing first, your error happens in line var vc1Delegate: fromOneToTwo! while you declared this delegate variable as not null but then calling passTheValue on it. A correct practice will be

```<code>var vc1Delegate: fromOneToTwo?

func runThisOnce(){
    if let delegate = vc1Delegate {
        vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")
    }
}
</code>```

Secondly, you are not using delegate correctly. In the assignDelegateToSelf() function, you are creating a new instance of TabOneController
 and then assign delegate. Instead, you need to find out the existing TabOneController instance and assign delegate.

Body:
Edit: Please note the question below discusses using delegation between
  2 viewcontrollers that are also implemented in a UITabBarController.

I've done a fair bit of searching here and on YouTube, but haven't seen my issue replicated elsewhere. I'll keep it to the point.

I have 2 view controllers that I coded myself -not generated by XCode-; TabOneController, and TabTwoController

below are the coding for both...

import UIKit

class TabOneController: UIViewController{

    private let instanceOfTabOneView = TabOneView()

    var vc1Delegate: fromOneToTwo!

    override func loadView() {

        super.loadView()

            view.addSubview(instanceOfTabOneView.buildTheVu())
                view.backgroundColor = UIColor.white

        runThisOnce()

        }

    func runThisOnce(){

        vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")

    }

}

protocol fromOneToTwo{

    func passTheValue(heroNameIs: String)

}

as for tab 2...

import UIKit

class TabTwoController: UIViewController, fromOneToTwo{

    private let instanceOfTabTwoView = TabTwoView()

    override func loadView() {

        super.loadView()

            view.addSubview(instanceOfTabTwoView.buildTheVu())

        assignDelegateToSelf()

    }

    func assignDelegateToSelf(){

        let instanceTabOne = TabOneController()
            instanceTabOne.vc1Delegate = self

    }

    func passTheValue(heroNameIs:String){

        instanceOfTabTwoView.txtFld.text = heroNameIs

    }

}

I'm getting the following error at runtime -the app builds successfully-...

fatal error: unexpectedly found nil while unwrapping an Optional value

on the following line...

vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")

When I comment out the above line, the app builds and runs successfully, but of course the app doesn't execute the delegation.

I kinda understand what the compiler is trying to tell me, that the

vc1Delegate

hasn't been instantiated -I guess-. But I searched under every rock, and can't seem to find how to get around this.

I'd appreciate any help or guidance. Sorry if my code seems immature, I'm new to Swift and programming in general. Thank you.

Body:
First thing first, your error happens in line var vc1Delegate: fromOneToTwo! while you declared this delegate variable as not null but then calling passTheValue on it. A correct practice will be

var vc1Delegate: fromOneToTwo?

func runThisOnce(){
    if let delegate = vc1Delegate {
        vc1Delegate.passTheValue(heroNameIs: "pass this to TabTwoController")
    }
}

Secondly, you are not using delegate correctly. In the assignDelegateToSelf() function, you are creating a new instance of TabOneController
 and then assign delegate. Instead, you need to find out the existing TabOneController instance and assign delegate.


问:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)
I'm using NLTK to perform kmeans clustering on my text file in which each line is considered as a document. So for example, my text file is something like this:

```<code>belong finger death punch <br>
hasty <br>
mike hasty walls jericho <br>
jägermeister rules <br>
rules bands follow performing jägermeister stage <br>
approach
</code>```

Now the demo code I'm trying to run is this:

import sys

import numpy
from nltk.cluster import KMeansClusterer, GAAClusterer, euclidean_distance
import nltk.corpus
from nltk import decorators
import nltk.stem

stemmer_func = nltk.stem.EnglishStemmer().stem
stopwords = set(nltk.corpus.stopwords.words('english'))

@decorators.memoize
def normalize_word(word):
    return stemmer_func(word.lower())

def get_words(titles):
    words = set()
    for title in job_titles:
        for word in title.split():
            words.add(normalize_word(word))
    return list(words)

@decorators.memoize
def vectorspaced(title):
    title_components = [normalize_word(word) for word in title.split()]
    return numpy.array([
        word in title_components and not word in stopwords
        for word in words], numpy.short)

if __name__ == '__main__':

    filename = 'example.txt'
    if len(sys.argv) == 2:
        filename = sys.argv[1]

    with open(filename) as title_file:

        job_titles = [line.strip() for line in title_file.readlines()]

        words = get_words(job_titles)

        # cluster = KMeansClusterer(5, euclidean_distance)
        cluster = GAAClusterer(5)
        cluster.cluster([vectorspaced(title) for title in job_titles if title])

        # NOTE: This is inefficient, cluster.classify should really just be
        # called when you are classifying previously unseen examples!
        classified_examples = [
                cluster.classify(vectorspaced(title)) for title in job_titles
            ]

        for cluster_id, title in sorted(zip(classified_examples, job_titles)):
            print cluster_id, title
```

<p>(which can also be found here)</p>

<p>The error I receive is this:</p>

```Traceback (most recent call last):
File "cluster_example.py", line 40, in
words = get_words(job_titles)
File "cluster_example.py", line 20, in get_words
words.add(normalize_word(word))
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/nltk/decorators.py", line 183, in memoize
result = func(*args)
File "cluster_example.py", line 14, in normalize_word
return stemmer_func(word.lower())
File "/usr/local/lib/python2.7/dist-packages/nltk/stem/snowball.py", line 694, in stem
word = (word.replace(u"\u2019", u"\x27")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)
```

What is happening here?

答:
You can try this also:</p>

```<code>import sys
reload(sys)
sys.setdefaultencoding('utf8')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using NLTK to perform kmeans clustering on my text file in which each line is considered as a document. So for example, my text file is something like this:

belong finger death punch

hasty

mike hasty walls jericho

jägermeister rules

rules bands follow performing jägermeister stage

approach

Now the demo code I'm trying to run is this:

import sys

import numpy
from nltk.cluster import KMeansClusterer, GAAClusterer, euclidean_distance
import nltk.corpus
from nltk import decorators
import nltk.stem

stemmer_func = nltk.stem.EnglishStemmer().stem
stopwords = set(nltk.corpus.stopwords.words('english'))

@decorators.memoize
def normalize_word(word):
    return stemmer_func(word.lower())

def get_words(titles):
    words = set()
    for title in job_titles:
        for word in title.split():
            words.add(normalize_word(word))
    return list(words)

@decorators.memoize
def vectorspaced(title):
    title_components = [normalize_word(word) for word in title.split()]
    return numpy.array([
        word in title_components and not word in stopwords
        for word in words], numpy.short)

if __name__ == '__main__':

    filename = 'example.txt'
    if len(sys.argv) == 2:
        filename = sys.argv[1]

    with open(filename) as title_file:

        job_titles = [line.strip() for line in title_file.readlines()]

        words = get_words(job_titles)

        # cluster = KMeansClusterer(5, euclidean_distance)
        cluster = GAAClusterer(5)
        cluster.cluster([vectorspaced(title) for title in job_titles if title])

        # NOTE: This is inefficient, cluster.classify should really just be
        # called when you are classifying previously unseen examples!
        classified_examples = [
                cluster.classify(vectorspaced(title)) for title in job_titles
            ]

        for cluster_id, title in sorted(zip(classified_examples, job_titles)):
            print cluster_id, title

(which can also be found here)

The error I receive is this:

Traceback (most recent call last):
File "cluster_example.py", line 40, in
words = get_words(job_titles)
File "cluster_example.py", line 20, in get_words
words.add(normalize_word(word))
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/nltk/decorators.py", line 183, in memoize
result = func(*args)
File "cluster_example.py", line 14, in normalize_word
return stemmer_func(word.lower())
File "/usr/local/lib/python2.7/dist-packages/nltk/stem/snowball.py", line 694, in stem
word = (word.replace(u"\u2019", u"\x27")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

What is happening here?

Body:
You can try this also:

import sys
reload(sys)
sys.setdefaultencoding('utf8')


问:
How to write a custom converter for

How can I write a custom converter when working with PrimeFaces components that use a list of POJO? My particular problem is with

```<code><p:pickList converter="????" value="#{bean.projects}" var="project"
                             itemLabel="#{project.name}" itemValue="#{project}">
</code>```

Without a converter I get java.lang.ClassCastException because JSF sets the submitted values with unconverted java.lang.String submitted values.

答:
is there any way to implement that without 2 database hits?

I mean, when you have

```<code>#{bean.projects}
</code>```

this is a database hit.

and when the converter puts

```<code>sBean.getProjectById(value);
</code>```

is a unnecessary database hit, since bean.projects already have id and value of the objects

Title: How to write a custom converter for <p:pickList>

Body:
How can I write a custom converter when working with PrimeFaces components that use a list of POJO? My particular problem is with

Without a converter I get java.lang.ClassCastException because JSF sets the submitted values with unconverted java.lang.String submitted values.

Body:
is there any way to implement that without 2 database hits?

I mean, when you have

#{bean.projects}

this is a database hit.

and when the converter puts

sBean.getProjectById(value);

is a unnecessary database hit, since bean.projects already have id and value of the objects

ContentLicense: CC BY-SA 2.5


问:
Can I change the shell used by extended git functionality?
On my systems, putting a shell script git-foo in directory /home/me/mygits (nothing special about the name) on your path causes the command

```<code>git foo
</code>```

to evaluate to

```<code>/bin/sh /home/me/mygits/git-goo
</code>```

I use a lot of bash shell functions in my programming and even though I export -f the functions, they don't make it to the shell started up by the git functionality.

I was wondering if there was any way to control what shell gets started when the command that is being executed is a shell script? That may not help in the end, but I'd like to try a few experiments before giving up.

Thank you.

答:
Yes, you can use whatever you want (including Perl, Python, etc). Just add

```<code>#!/bin/bash
</code>```

as the first line of the script.

Or you can use something like this to find a command in $PATH without specifying it at a static path.

```<code>#!/usr/bin/env bash
</code>```

Body:
On my systems, putting a shell script git-foo in directory /home/me/mygits (nothing special about the name) on your path causes the command

git foo

to evaluate to

/bin/sh /home/me/mygits/git-goo

I use a lot of bash shell functions in my programming and even though I export -f the functions, they don't make it to the shell started up by the git functionality.

I was wondering if there was any way to control what shell gets started when the command that is being executed is a shell script? That may not help in the end, but I'd like to try a few experiments before giving up.

Thank you.

Body:
Yes, you can use whatever you want (including Perl, Python, etc). Just add

#!/bin/bash

as the first line of the script.

Or you can use something like this to find a command in $PATH without specifying it at a static path.

#!/usr/bin/env bash


问:
HTML Select option with PHP Dynamic
I'm getting a weird result when i try to implement the PHP inside a HTML

The config is literally my DB connection, other scripts work well but only for this matter i couldn't figure out.

Maybe I missed out some elements.

```<code><select name="country">
    <option value="" disabled selected style="display: none;">All Japan Cities</option>
    <?php
    include 'scripts/config.php';
        $query = "SELECT state FROM product";
        $result = mysql_query($query);
        $count = count($result);
        if (!empty($count)) {
            while($row = mysql_fetch_array($result))
            {
                $state = $row['state'];
                echo "<option value='$state'> $state </option>";
            }
        } else {
            echo '<option>No data</option>';
        }
    ?>
    </select>
</code>```

I keep on getting no data for my select statement where I have 3 results in my db.

答:
I don't think you can do a count() on a mysql result set like that.

Try using mysql_num_rows instead, like this:

```<code>....
$count = mysql_num_rows($result);
    if (!empty($count)) {
....
</code>```

Also, as others have said, these old mysql_ functions are deprecated, so you should probably switch to mysqli or PDO if that is practical as well.

Title: HTML Select option with PHP Dynamic

Body:
I'm getting a weird result when i try to implement the PHP inside a HTML

The config is literally my DB connection, other scripts work well but only for this matter i couldn't figure out.

Maybe I missed out some elements.

<select name="country">
    <option value="" disabled selected style="display: none;">All Japan Cities</option>
    <?php
    include 'scripts/config.php';
        $query = "SELECT state FROM product";
        $result = mysql_query($query);
        $count = count($result);
        if (!empty($count)) {
            while($row = mysql_fetch_array($result))
            {
                $state = $row['state'];
                echo "<option value='$state'> $state </option>";
            }
        } else {
            echo '<option>No data</option>';
        }
    ?>
    </select>

I keep on getting no data for my select statement where I have 3 results in my db.

Body:
I don't think you can do a count() on a mysql result set like that.

Try using mysql_num_rows instead, like this:

....
$count = mysql_num_rows($result);
    if (!empty($count)) {
....

Also, as others have said, these old mysql_ functions are deprecated, so you should probably switch to mysqli or PDO if that is practical as well.


问:
Replace Retrolambda with Android Studio 3.0 Java 8 built-in features
In my project I'm using popular library retrolambda.
I've just downloaded new Android Studio 3.0 Canary 1.

I've updated my project to use new version of Gradle etc. And everything is OK.

What's new in Android Studio 3 is built in support for some Java8 features.
New AS3 is suggesting to remove retrolambda and use these features.

I have removed retrolambda, Gradle build was successful but app is crashing with this error (in a place where there is lambda)

```<code>E/UncaughtException: java.lang.NoSuchMethodError: No static method lambda$replace$2
</code>```

I'm using RxJava2 in my project. I'm not sure this is related with it, but it looks like in my case built-in features for Java8 are not working. Maybe I need to set something "somewhere"?

My project settings

My Gradle files

Root project

```<code>   dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
        classpath 'com.google.gms:google-services:3.0.0'
        //classpath 'me.tatarka:gradle-retrolambda:3.6.1'
    }
</code>```

App module

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
    }
}

repositories {
    mavenCentral()
    maven { url "https://jitpack.io" }
}

apply plugin: 'com.android.application'
apply plugin: 'com.jakewharton.hugo'

...

    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.firebase:firebase-analytics:9.8.+'
    compile 'com.google.firebase:firebase-crash:9.8.+'
    compile 'com.google.android.gms:play-services-maps:9.8.+'
    compile 'com.google.android.gms:play-services-analytics:9.8.+'
    compile 'com.google.android.gms:play-services-auth:9.8.+'
    compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'
    //Support Library

(...)

    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'
    compile 'com.google.maps.android:android-maps-utils:0.4'

    /* RXJAVA2 */
    compile 'io.reactivex.rxjava2:rxjava:2.0.6'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
    compile 'com.github.VictorAlbertos:ReactiveCache:1.1.0-2.x'
    compile 'com.github.VictorAlbertos.Jolyglot:gson:0.0.3'

android {

    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    defaultConfig {
        applicationId "my_app_id"
        minSdkVersion 15
        targetSdkVersion 25
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

(...)

    dexOptions {
        javaMaxHeapSize "4g"
    }
    lintOptions {
        abortOnError false
    }

    }

    buildTypes {
        debug {
            minifyEnabled false
            shrinkResources false
        }

        debugpro {
            minifyEnabled true
            shrinkResources false
            proguardFile file('proguard-project.txt')
            proguardFile file('proguard-google-api-client.txt')
            //noinspection GroovyAssignabilityCheck
            signingConfig signingConfigs.debug
        }

        release {
            minifyEnabled true
            shrinkResources false
            proguardFile file('proguard-project.txt')
            proguardFile file('proguard-google-api-client.txt')

        }
        releaseci {
            minifyEnabled true
            shrinkResources false
            proguardFile file('proguard-project.txt')
            proguardFile file('proguard-google-api-client.txt')
            //noinspection GroovyAssignabilityCheck
            signingConfig signingConfigs.releaseci
        }

(...)

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.jakewharton.butterknife'
</code>```

答:
This is probably caused by a bug in the Gradle Java 8 language feature desugaring that is tracked in https://issuetracker.google.com/issues/62456849

desugar seems to blindly rename the synthetic methods in a class file if their name starts with lambda$ (appending the owner class name) regardless of whether a reference to that method already exists in the bytecode (and that reference doesn't get renamed too).

When the code path hits such a reference at runtime the obvious result is a NoSuchMethodError because a method with that name doesn't exist anymore.

Body:
In my project I'm using popular library retrolambda.
I've just downloaded new Android Studio 3.0 Canary 1.

I've updated my project to use new version of Gradle etc. And everything is OK.

What's new in Android Studio 3 is built in support for some Java8 features.
New AS3 is suggesting to remove retrolambda and use these features.

I have removed retrolambda, Gradle build was successful but app is crashing with this error (in a place where there is lambda)

E/UncaughtException: java.lang.NoSuchMethodError: No static method lambda$replace$2

I'm using RxJava2 in my project. I'm not sure this is related with it, but it looks like in my case built-in features for Java8 are not working. Maybe I need to set something "somewhere"?

My project settings

My Gradle files

Root project

   dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
        classpath 'com.google.gms:google-services:3.0.0'
        //classpath 'me.tatarka:gradle-retrolambda:3.6.1'
    }

App module

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
    }
}

repositories {
    mavenCentral()
    maven { url "https://jitpack.io" }
}

apply plugin: 'com.android.application'
apply plugin: 'com.jakewharton.hugo'

...

    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.firebase:firebase-analytics:9.8.+'
    compile 'com.google.firebase:firebase-crash:9.8.+'
    compile 'com.google.android.gms:play-services-maps:9.8.+'
    compile 'com.google.android.gms:play-services-analytics:9.8.+'
    compile 'com.google.android.gms:play-services-auth:9.8.+'
    compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'
    //Support Library

(...)

    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'
    compile 'com.google.maps.android:android-maps-utils:0.4'

    /* RXJAVA2 */
    compile 'io.reactivex.rxjava2:rxjava:2.0.6'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
    compile 'com.github.VictorAlbertos:ReactiveCache:1.1.0-2.x'
    compile 'com.github.VictorAlbertos.Jolyglot:gson:0.0.3'

android {

    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    defaultConfig {
        applicationId "my_app_id"
        minSdkVersion 15
        targetSdkVersion 25
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

(...)

    dexOptions {
        javaMaxHeapSize "4g"
    }
    lintOptions {
        abortOnError false
    }

    }

    buildTypes {
        debug {
            minifyEnabled false
            shrinkResources false
        }

        debugpro {
            minifyEnabled true
            shrinkResources false
            proguardFile file('proguard-project.txt')
            proguardFile file('proguard-google-api-client.txt')
            //noinspection GroovyAssignabilityCheck
            signingConfig signingConfigs.debug
        }

        release {
            minifyEnabled true
            shrinkResources false
            proguardFile file('proguard-project.txt')
            proguardFile file('proguard-google-api-client.txt')

        }
        releaseci {
            minifyEnabled true
            shrinkResources false
            proguardFile file('proguard-project.txt')
            proguardFile file('proguard-google-api-client.txt')
            //noinspection GroovyAssignabilityCheck
            signingConfig signingConfigs.releaseci
        }

(...)

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.jakewharton.butterknife'


问:
Can we use third party payment gateway in ios In-App Purchase?
One of our clients have approached us to develop an app like Yelp where Restaurants with Happy Hours can list their business, which is showed to end consumer of the app when they are trying to find nearest Restaurants.

Business Owner have to purchase subscription in order to do that, we wanted to clarify whether we can use third party payment processor like Pay Pal as the same service is also going to be available in Android platform as well.

答:
In essence, this is not possible. Third party payment walls are against the strict rules of the payment control and income sharing of App Store guidelines.

Take a look at Apple's App Store Review Guidelines for more information.


问:
Get space between floating divs using JavaScript?
I got an layout using bootstrap with multiple floating divs.

I want to retrieve the space between the divs using JavaScript. Ive only no idea how i can do this. See below picture.

A picture says  a 1000 words ;)

Ive created a fiddle with above layout, i will paste it here so you can play with it if you want.

.page-container {
    background: #ededed;
    padding: 40px 0;
}

.column {
    padding: 15px;
    background-color: white;
    box-shadow: 1px 1px 3px #ccc;
}

[class^="col-"] {
    margin-bottom: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="page-container">
<div class="container">
    <div class="col-md-6 col-sm-6 col-xs-6">
        <div class="column">
            <h2>
        Floating element #1
        </h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
        </p>
        <p>
        Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.
        </p>
        </div>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6">
        <div class="column">
            <h2>
        Floating element #2
        </h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
        </p>
        </div>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6">
       <div class="column">
        <h2>
        Floating element #3
        </h2>
        <p>
            Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.
        </p>
        <p>
        Fusce a velit et justo porttitor sollicitudin a a velit. Praesent ultrices arcu a sodales ultricies. Etiam cursus mattis dapibus. Fusce vulputate commodo pretium. Suspendisse a orci vitae ipsum interdum dapibus a quis velit. Proin euismod, lectus id euismod semper, tellus nunc luctus dui, consectetur venenatis erat mi eu dolor. Nunc eleifend semper lacus, at hendrerit massa. Praesent ac magna at lacus commodo faucibus eu sit amet magna. Donec pellentesque felis et leo interdum dignissim. Sed sit amet sapien ac quam auctor semper quis ut nibh. Vivamus consectetur, ipsum luctus semper viverra, sem arcu sagittis mauris, a interdum odio sapien in augue.
        </p>
        <p>
        Nam ut bibendum urna, sed congue neque. Nunc a nunc venenatis, porttitor odio vitae, finibus est. Suspendisse quis purus a diam aliquam ullamcorper eu sed dolor. Etiam ac eros eget nisl pretium lobortis. Nulla convallis id nunc eget efficitur. Morbi vel elementum justo. Phasellus et egestas quam. Cras eu tristique urna. Cras ac justo efficitur, consectetur eros et, tincidunt nulla. Quisque et cursus ipsum. Ut tincidunt, purus et tempor fermentum, nulla diam suscipit ex, non sodales eros nunc vel ante. Duis quis justo quam. Sed imperdiet lorem et blandit pretium. Etiam elit dui, tristique et vehicula vitae, venenatis et augue.
        </p>
       </div>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6">
        <div class="column">
        <h2>
        Floating element #4
        </h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
        </p>
        <p>
        Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.
        </p>
        </div>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6">
        <div class="column">
        <h2>
        Floating element #4
        </h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
        </p>
        </div>
    </div>
</div>
</div></code>```

Im trying to get those pixel, and move the underlying div up using JavaScript. I know i can use something like masonry. But i can't get those working in my application.

Does anyone have an idea how i can do this? (oh, using jQuery is no problem)

答:
Get first element's x,y cordinates (e.g Retrieve the position (X,Y) of an HTML element)

Get first elements height and width (e.g. marco gomes answer)

Get fourth element's x,y cordinates

Calculate:
Fourth's x pos minus (First's x pos + height) = empty space's height
As it is same width as other's width, you have a width.

If you need dynamically find gaps, you can loop all divs and put them in column groups (with help of x pos). Then you do above for each group's current and next in order element (they should be in right order). If the vertical difference is above set rule, you can assume you have a gap.

Body:
I got an layout using bootstrap with multiple floating divs.

I want to retrieve the space between the divs using JavaScript. Ive only no idea how i can do this. See below picture.

A picture says  a 1000 words ;)

Ive created a fiddle with above layout, i will paste it here so you can play with it if you want.

.page-container {
    background: #ededed;
    padding: 40px 0;
}

.column {
    padding: 15px;
    background-color: white;
    box-shadow: 1px 1px 3px #ccc;
}

[class^="col-"] {
    margin-bottom: 30px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        Floating element #1

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.

        Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.

        Floating element #2

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.

        Floating element #3

            Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.

        Fusce a velit et justo porttitor sollicitudin a a velit. Praesent ultrices arcu a sodales ultricies. Etiam cursus mattis dapibus. Fusce vulputate commodo pretium. Suspendisse a orci vitae ipsum interdum dapibus a quis velit. Proin euismod, lectus id euismod semper, tellus nunc luctus dui, consectetur venenatis erat mi eu dolor. Nunc eleifend semper lacus, at hendrerit massa. Praesent ac magna at lacus commodo faucibus eu sit amet magna. Donec pellentesque felis et leo interdum dignissim. Sed sit amet sapien ac quam auctor semper quis ut nibh. Vivamus consectetur, ipsum luctus semper viverra, sem arcu sagittis mauris, a interdum odio sapien in augue.

        Nam ut bibendum urna, sed congue neque. Nunc a nunc venenatis, porttitor odio vitae, finibus est. Suspendisse quis purus a diam aliquam ullamcorper eu sed dolor. Etiam ac eros eget nisl pretium lobortis. Nulla convallis id nunc eget efficitur. Morbi vel elementum justo. Phasellus et egestas quam. Cras eu tristique urna. Cras ac justo efficitur, consectetur eros et, tincidunt nulla. Quisque et cursus ipsum. Ut tincidunt, purus et tempor fermentum, nulla diam suscipit ex, non sodales eros nunc vel ante. Duis quis justo quam. Sed imperdiet lorem et blandit pretium. Etiam elit dui, tristique et vehicula vitae, venenatis et augue.

        Floating element #4

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.

        Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.

        Floating element #4

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.

Im trying to get those pixel, and move the underlying div up using JavaScript. I know i can use something like masonry. But i can't get those working in my application.

Does anyone have an idea how i can do this? (oh, using jQuery is no problem)


问:
Has Tez support been removed from Flink?
Attempting to build 1.3.1 with (out of date) https://ci.apache.org/projects/flink/flink-docs-release-0.9/setup/flink_on_tez.html instructions yielded:

mvn  -DskipTests clean package -Pinclude-tez -Dhadoop.version=2.7.1 -Dtez.version=0.7.0

[WARNING] The requested profile "include-tez" could not be activated because it does not exist.

答: Yes, it was removed quite some time ago.</p>


问:
Call function for each route in $routeProvider
I have got a little challenge and didn't find the solution yet. As I tried serveral things I'm asking your help so probably someone can lead me to the right direction.

I've got a routes.js in AngularJS. There am I using a $routeProvider. In each .when() I need to call a function (as I need to do something with the name).

```<code>$routeProvider
.when('/url', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url1', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url2', { templateUrl: '', /* callMyFunction('/url'); */ }) ....
</code>```

This is just an example, I know this won't work. But to give you an idea what I'm trying to do. As you can see this will mess up my code (you need much more to get this working, so you'll get a lot of extra code for each .when() and this code is in every statement exactly the same (except for the argument).

So I'm looking for some function that can be called before or after (doesn't make sense as long as it's getting called) .when().

I've read plenty of questions here on Stack Overflow but didn't find the right answer. Most questions answered to put this in the controller. How ever, this function I've to call is for each route exactly the same. Because of this I don't want to put it in all my controllers but just in the routes.js and called for/after every when().

答:
You are looking for something like $routeChangeSuccess or $routeChangeStart (See $route).

Before route change

```<code>function runConfig($rootScope) {
    $rootScope.$on('$routeChangeStart', function (event, next, current) {
        if (next && next['$$route']) {
            var route = next['$$route']['originalPath'];
            //route is 'url', 'url1' or 'urlX'
            //do with it as you please
        }
    });
}

angular
        .module('app')
        .run(runConfig);
</code>```

After route changed

```<code>function runConfig($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, prev) {
        if (current && current['$$route']) {
            var route = current['$$route']['originalPath'];
            //route is 'url', 'url1' or 'urlX'
            //do with it as you please
        }
    });
}

angular
        .module('app')
        .run(runConfig);
</code>```

Body:
I have got a little challenge and didn't find the solution yet. As I tried serveral things I'm asking your help so probably someone can lead me to the right direction.

I've got a routes.js in AngularJS. There am I using a $routeProvider. In each .when() I need to call a function (as I need to do something with the name).

$routeProvider
.when('/url', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url1', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url2', { templateUrl: '', /* callMyFunction('/url'); */ }) ....

This is just an example, I know this won't work. But to give you an idea what I'm trying to do. As you can see this will mess up my code (you need much more to get this working, so you'll get a lot of extra code for each .when() and this code is in every statement exactly the same (except for the argument).

So I'm looking for some function that can be called before or after (doesn't make sense as long as it's getting called) .when().

I've read plenty of questions here on Stack Overflow but didn't find the right answer. Most questions answered to put this in the controller. How ever, this function I've to call is for each route exactly the same. Because of this I don't want to put it in all my controllers but just in the routes.js and called for/after every when().

Body:
You are looking for something like $routeChangeSuccess or $routeChangeStart (See $route).

Before route change

function runConfig($rootScope) {
    $rootScope.$on('$routeChangeStart', function (event, next, current) {
        if (next && next['$$route']) {
            var route = next['$$route']['originalPath'];
            //route is 'url', 'url1' or 'urlX'
            //do with it as you please
        }
    });
}

angular
        .module('app')
        .run(runConfig);

After route changed

function runConfig($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, prev) {
        if (current && current['$$route']) {
            var route = current['$$route']['originalPath'];
            //route is 'url', 'url1' or 'urlX'
            //do with it as you please
        }
    });
}

angular
        .module('app')
        .run(runConfig);


问:
FitnessActivities.getName(int i) method is deprecated, what method to use instead?
In the following library:
 com.google.android.gms:play-services-fitness:9.8.0

In the following class: com.google.android.gms.fitness.FitnessActivities

There is this method: public static java.lang.String getName(int i)

However, in the library com.google.android.gms:play-services-fitness:10.2.0 the above mentioned method is removed.

What method to use instead of the above mentioned method?

答:
Can you give us some code? I assume that you have a variable with value X and you want to perform some actions according to this value. If that is the case, I will do that with a switch statement:</p>

```<code>switch(myFitnessValue) {
case FitnessActivities.AEROBICS:
    doAerobics();
break;

case FitnessActivities.BIKING:
    doBiking();
break;

case FitnessActivities.WALKING:
    doWalking();
break;

default:
    doNothing();
}
</code>```

Body:
Can you give us some code? I assume that you have a variable with value X and you want to perform some actions according to this value. If that is the case, I will do that with a switch statement:

switch(myFitnessValue) {
case FitnessActivities.AEROBICS:
    doAerobics();
break;

case FitnessActivities.BIKING:
    doBiking();
break;

case FitnessActivities.WALKING:
    doWalking();
break;

default:
    doNothing();
}


问:
Nodejs HTTP request, cant alter response headers
Hello I'm doing a request and then upon response i'm trying to add come headers but I get the following error:

```<code>Server listening on port 80 [Request]: test.domain.com//web/guest/retail-betting (GET) D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19
        resp.setHeader("Access-Control-Allow-Origin", "*");
             ^

TypeError: resp.setHeader is not a function
    at ClientRequest.<anonymous> (D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19:14)
    at ClientRequest.g (events.js:291:16)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
    at Socket.socketOnData (_http_client.js:362:20)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
</code>```

An here is the code sample:

```<code>const http = require("http");
const clear = require("clear");
const server = http.createServer();

server.on('request', function(req, res) {

    var options = {
        host: HOST,
        path: req.url,
        method: req.method
    };

    console.log("[Request]:", HOST + "/" + options.path, "(" + options.method.toUpperCase() + ")");

    var connector = http.request(options, function(resp) {

        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");

        console.log("===============[Response Headers]===============");
        console.log(JSON.stringify(resp.headers, null, 4), "\n");

        resp.pipe(res);

    });

    req.pipe(connector);

});

server.listen(PORT);

clear();

console.log("Server listening on port", PORT);
</code>```

答:
You cannot use resp to change request headers because that request has already ended - you have to use res for that (using your variable names).

That's because resp is a response that you got from some external service, while res is the response that you are sending as a response to the request that your service got from someone else.

In other words, when you are acting as a client then you are making the request and you get the response. The response headers are set and you cannot change them. But when you are acting as the server then you get a request and you send a response - that comprises of headers and body that you can define yourself.

See:

https://nodejs.org/api/http.html#http_response_setheader_name_value

Body:
Hello I'm doing a request and then upon response i'm trying to add come headers but I get the following error:

Server listening on port 80 [Request]: test.domain.com//web/guest/retail-betting (GET) D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19
        resp.setHeader("Access-Control-Allow-Origin", "*");
             ^

TypeError: resp.setHeader is not a function
    at ClientRequest.<anonymous> (D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19:14)
    at ClientRequest.g (events.js:291:16)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
    at Socket.socketOnData (_http_client.js:362:20)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)

An here is the code sample:

const http = require("http");
const clear = require("clear");
const server = http.createServer();

server.on('request', function(req, res) {

    var options = {
        host: HOST,
        path: req.url,
        method: req.method
    };

    console.log("[Request]:", HOST + "/" + options.path, "(" + options.method.toUpperCase() + ")");

    var connector = http.request(options, function(resp) {

        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");

        console.log("===============[Response Headers]===============");
        console.log(JSON.stringify(resp.headers, null, 4), "\n");

        resp.pipe(res);

    });

    req.pipe(connector);

});

server.listen(PORT);

clear();

console.log("Server listening on port", PORT);


问:
Two divs for the same section
In the following HTML code, why do they use two divs, one with a class, and the other with an ID, instead of just using one of them for giving the properties?

.header {
  background-image: url("https://s3.amazonaws.com/codecademy-content/courses/web-101/unit-5/htmlcss1-img_canyon.jpeg");
  background-position: center center;
  background-size: cover;
  height: 700px;
  width: 100%;
}

#header-text {
  margin: 0 auto;
  position: relative;
  text-align: center;
  top: 25%;
  width: 60%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="header">
    <div  id="header-text">
      <h1>Travel Like Never Before</h1>
      <h2>Whether you're looking for adventure or luxury, let us help you plan your perfect getaway.</h2>
    </div>
 </div></code>```

答: The reason is because the .header class defines the area for the background image, and the #header-text id defines the text that's on top of the image. Since the text is centered and positioned within the larger header area, it needs a separate container so it can be moved around and styled appropriately.

Title: Two divs for the same section

Body:
In the following HTML code, why do they use two divs, one with a class, and the other with an ID, instead of just using one of them for giving the properties?

.header {
  background-image: url("https://s3.amazonaws.com/codecademy-content/courses/web-101/unit-5/htmlcss1-img_canyon.jpeg");
  background-position: center center;
  background-size: cover;
  height: 700px;
  width: 100%;
}

#header-text {
  margin: 0 auto;
  position: relative;
  text-align: center;
  top: 25%;
  width: 60%;
}

Travel Like Never Before

Whether you're looking for adventure or luxury, let us help you plan your perfect getaway.


问:
Is this the right way to get string resources from within a Fragment?
Which method is generally better / safer for reading string resources while in a Fragment?

Here I read getResources().getString() directly:

```<code>public class SomeFragment extends Fragment {

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = getResources().getString(R.string.my_string_id);
    }

}
</code>```

Or is it better to do it this way, by setting a Context field first and then reading the resources from that:

```<code>public class SomeFragment extends Fragment {
    private Context context;

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = context.getResources().getString(R.string.my_string_id);
    }

}
</code>```

Any tradeoffs/drawbacks to either of these methods?

The reason I ask is because sometimes I've run into nullpointer issues with the first approach that were resolved by using the second approach; so I wasn't sure if it was problematic to use the first one.

答:
Both the approaches are better. No issues in this. You faced the null pointer exception because.

When a fragment transaction happens the lifecycle of the fragment starts and only when it gets attached to the activity and when reaches the onstart it will be ready.

Some times if we try to access the public methods of the fragment immediately after the fragmentManager's commit. Then you will run into null pointer exception while accessing the context object. As it is not still completed the process.

So its developers logic to write the code understanding the life cycle to avoid those.

Body:
Which method is generally better / safer for reading string resources while in a Fragment?

Here I read getResources().getString() directly:

public class SomeFragment extends Fragment {

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = getResources().getString(R.string.my_string_id);
    }

}

Or is it better to do it this way, by setting a Context field first and then reading the resources from that:

public class SomeFragment extends Fragment {
    private Context context;

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = context.getResources().getString(R.string.my_string_id);
    }

}

Any tradeoffs/drawbacks to either of these methods?

The reason I ask is because sometimes I've run into nullpointer issues with the first approach that were resolved by using the second approach; so I wasn't sure if it was problematic to use the first one.


问:
Inserting a formula within a file reference in Excel
I can't really give out the file names which is why I've used the fillers. So my current workbook is called 'thisfile.xls' (again, filler) with 6 columns. B has the dates, and C,D,E,F,G has the values that need to be filled in from values in different files located in 'Z\Folder1\Folder2\Folder3'. A new file is created every day in the format: 'filename_des_Part II_04-03-2017.xls'. The 'filename', 'des', and 'Part II' part remain the same for each new file created but the date part changes everyday (based on whatever day it is). I need 5 separate values from each of these files (they're always located in the same place in each file) and the values are spread out in different worksheets.

Now, in my original file 'thisfile.xls', if B2: 04/03/2017, then I want C2:='Z:Folder1\Folder2\Folder3[filename_des_04-03-2017.xls]Sheet3'!$K$10.

And if B3: 04/04/2017, then I want C3:= 'Z:Folder1\Folder2\Folder3[filename_des_04-04-2017.xls]Sheet3'!$K$10.

So only the date component of the file name would be changing so that I can use autofill and drag the formula down to all the dates.

答:
INDIRECT will do this for you. The function is built to do precisely this -- when you need to refer to a cell, but the cell (or workbook) you want to refer to varies based on some other thing. If

Try, in C2,:

```<code>=INDIRECT("'Z:Folder1\Folder2\Folder3[filename_des_"&TEXT(B2,"DD-MM-YYYY")&".xls]Sheet3'!$K$10")
</code>```

Not sure whether you're using DD-MM-YYYY or MM-DD-YYYY, if the latter instead of the former, just change the DD-MM around in the formula.

Body:
INDIRECT will do this for you. The function is built to do precisely this -- when you need to refer to a cell, but the cell (or workbook) you want to refer to varies based on some other thing. If

Try, in C2,:

=INDIRECT("'Z:Folder1\Folder2\Folder3[filename_des_"&TEXT(B2,"DD-MM-YYYY")&".xls]Sheet3'!$K$10")

Not sure whether you're using DD-MM-YYYY or MM-DD-YYYY, if the latter instead of the former, just change the DD-MM around in the formula.