问:
Apache Spark 2.1.1 how to set hive.serialization.extend.nesting.levels property to true
I am trying to perform some queries on nested data from my JSON data, but spark complains that my data (8) exceeds the level of nesting supported for LazySimpleSerde (7). I cannot figure out how to set the hive.serialization.extend.nesting.levels property to true.

Spark Log:

org.apache.hadoop.hive.serde2.SerDeException Number of levels of nesting supported for LazySimpleSerde is 7 Unable to work with level 8. Use hive.serialization.extend.nesting.levels serde property for tables using LazySimpleSerde.

答:
I see 3 possibilities which you could try in spark:

for a new SparkSession:

```<code>val sparkSession =
  SparkSession.builder
    .master("local[*]")
    .appName("MyApp")
    .config("set hive.serialization.extend.nesting.levels","true")
    .getOrCreate()
</code>```

For existing SparkSession:

```<code>sparkSession.sql("set hive.serialization.extend.nesting.levels = true")
</code>```

or

```<code>sparkSession.conf.set("set hive.serialization.extend.nesting.levels","true")
</code>```

But I'm not sure whether this works for this specific property, but I often set e.g. hive.exec.dynamic.partition.mode at runtime using above methods

Body:
I see 3 possibilities which you could try in spark:

for a new SparkSession:

val sparkSession =
  SparkSession.builder
    .master("local[*]")
    .appName("MyApp")
    .config("set hive.serialization.extend.nesting.levels","true")
    .getOrCreate()

For existing SparkSession:

sparkSession.sql("set hive.serialization.extend.nesting.levels = true")

or

sparkSession.conf.set("set hive.serialization.extend.nesting.levels","true")

But I'm not sure whether this works for this specific property, but I often set e.g. hive.exec.dynamic.partition.mode at runtime using above methods


来源: stackexchange

问:
Reduce wifi range to 2-3 metre
I want to keep two wifi routers in a room in such a way that a WiFi station does not see both the Access Points at the same time. My idea is to reduce the transmit power of the AP  so that the WiFi range becomes around 2-3 metres. Is this possible?

I was experimenting this by configuring raspberry pi as the Access Point. I tried iwconfig command to reduce the txpower like this

```<code>iwconfig wlan0 txpower 1mW
iwconfig wlan0 txpower 1
iwconfig wlan0 txpower 0
</code>```

I tried many other combinations as well, but the range doesn't seem to reduce. How to accomplish this? I would prefer to use raspberry pi as the router as it is less cumbersome to be used in demo scenarios.

答:
Well for the request, I suggest you to directly access the router advance settings depending on the router which you are using, search for the transmission power and reduce the latency according to your will.

In another case you can also hide your wireless network, which can become visible when you search for the requested SSID.

Hope this helps.

Enjoy.

ContentLicense: CC BY-SA 3.0

Title: Reduce wifi range to 2-3 metre

Body:
I want to keep two wifi routers in a room in such a way that a WiFi station does not see both the Access Points at the same time. My idea is to reduce the transmit power of the AP  so that the WiFi range becomes around 2-3 metres. Is this possible?

I was experimenting this by configuring raspberry pi as the Access Point. I tried iwconfig command to reduce the txpower like this

iwconfig wlan0 txpower 1mW
iwconfig wlan0 txpower 1
iwconfig wlan0 txpower 0

I tried many other combinations as well, but the range doesn't seem to reduce. How to accomplish this? I would prefer to use raspberry pi as the router as it is less cumbersome to be used in demo scenarios.


问:
How to read External Sqllite Database in xamirin android in Visual Studio C#
My Code :

```<code>var dbpath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "ot.db3");
Context myContext = null;
try
{
      var dbcon = new SQLiteConnection(dbpath);
         var db=   dbcon.Query<records>("SELECT * FROM records WHERE sno = ? ", "1");
            int count = db.Count;
}
catch (IOException ex)
{
    var reason = string.Format("The database failed to create - reason {0}", ex.Message);
    Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}
</code>```

I Create a Sqlite Database from my SQL Server Database.

Now I save it to my Phone on this path (Android/Data/Application/File)

Now using Sqlite-net-pcl nugget package for Sqlite Connection the connection works fine showing have no error.

When I try to read a table from database this Give any error that "No Such Table exist in database". And the table exists in the database and is populated with data.

What can I do?

Thanks in advance

答:
Why are you writing the SQL query? You could make it more simple, something like, conn.Get(id);

You will only need to add [PrimaryKey] to your PK in the model.

Also, I suggest you to not use SQLite.SQLiteConnection and use SQLiteAsyncConnection instead, so you will be able to get data using "await conn.GetAsync(id)" and this way it won't block the main thread.

Body:
My Code :

var dbpath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "ot.db3");
Context myContext = null;
try
{
      var dbcon = new SQLiteConnection(dbpath);
         var db=   dbcon.Query<records>("SELECT * FROM records WHERE sno = ? ", "1");
            int count = db.Count;
}
catch (IOException ex)
{
    var reason = string.Format("The database failed to create - reason {0}", ex.Message);
    Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}

I Create a Sqlite Database from my SQL Server Database.

Now I save it to my Phone on this path (Android/Data/Application/File)

Now using Sqlite-net-pcl nugget package for Sqlite Connection the connection works fine showing have no error.

When I try to read a table from database this Give any error that "No Such Table exist in database". And the table exists in the database and is populated with data.

What can I do?

Thanks in advance


问:
Cassandra SELECT DISTINCT and timeout issue
When running the following CQL query:

```<code>SELECT DISTINCT partition_key FROM table_name;
</code>```

This is supposedly meant to return the list of partition keys that are in use for the given table. However, with the default timeout settings of 10s, it always times out:

```<code>ReadTimeout: Error from server: code=1200 [Coordinator node timed out waiting for replica nodes' responses] message="Operation timed out - received only 0 responses." info={'received_responses': 0, 'required_responses': 1, 'consistency': 'ONE'}
</code>```

Changing the timeout settings to:

```<code>read_request_timeout_in_ms: 60000
range_request_timeout_in_ms: 60000
request_timeout_in_ms: 60000
</code>```

And then running said query results in several Cassandra nodes crashing, including the coordinator node. The table has approximately >100M rows with about 5000 unique partition keys.

Is there a workaround to find the unique list of partition keys?

答:
This query should work fine on modern versions of cassandra (2.1 and newer) assuming you're using a client that supports paging/fetch-size, and use a sufficiently low fetch-size (the actual limit depends on your server load).

Using a third party driver, look for an option to drop the page/fetch size. Set it to 100 and see if it behaves better.

Using cqlsh, if you have cassandra 3.0 or newer, try PAGING 100;

Body:
When running the following CQL query:

SELECT DISTINCT partition_key FROM table_name;

This is supposedly meant to return the list of partition keys that are in use for the given table. However, with the default timeout settings of 10s, it always times out:

ReadTimeout: Error from server: code=1200 [Coordinator node timed out waiting for replica nodes' responses] message="Operation timed out - received only 0 responses." info={'received_responses': 0, 'required_responses': 1, 'consistency': 'ONE'}

Changing the timeout settings to:

read_request_timeout_in_ms: 60000
range_request_timeout_in_ms: 60000
request_timeout_in_ms: 60000

And then running said query results in several Cassandra nodes crashing, including the coordinator node. The table has approximately >100M rows with about 5000 unique partition keys.

Is there a workaround to find the unique list of partition keys?


答:
If you are trying to allocate space for an array of pointers, such as

```<code>char** my_array_of_strings;  // or some array of pointers such as int** or even void**
</code>```

then you will need to consider word size (8 bytes in a 64-bit system, 4 bytes in a 32-bit system) when allocating space for n pointers.  The size of a pointer is the same of your word size.

So while you may wish to allocate space for n pointers, you are actually going to need n times 8 or 4 (for 64-bit or 32-bit systems, respectively)

To avoid overflowing your allocated memory for n elements of 8 bytes:

```<code>my_array_of_strings = (char**) malloc( n * 8 );  // for 64-bit systems
my_array_of_strings = (char**) malloc( n * 4 );  // for 32-bit systems
</code>```

This will return a block of n pointers, each consisting of 8 bytes (or 4 bytes if you're using a 32-bit system)

I have noticed that Linux will allow you to use all n pointers when you haven't compensated for word size, but when you try to free that memory it realizes its mistake and it gives out that rather nasty error.  And it is a bad one, when you overflow allocated memory, many security issues lie in wait.

Title: Error: free(): invalid next size (fast):

Body:
What is this strange error I'm getting? I'm compiling C++ using g++ on Ubuntu 10.10. It pops up randomly when I run the executable (maybe 2 times in 8 hours, with 10 compiles an hour). However, if I make clean and recompile it goes away most of the time.

*** glibc detected *** ./emailQueue.app: free(): invalid next size (fast): 0x0000000001c40270 ***
======= Backtrace: =========
/lib/libc.so.6(+0x774b6)[0x7f490d95e4b6]
/lib/libc.so.6(cfree+0x73)[0x7f490d964c83]
./emailQueue.app[0x401f47]
/lib/libc.so.6(__libc_start_main+0xfe)[0x7f490d905d8e]
./emailQueue.app[0x401cc9]
======= Memory map: ========
00400000-0040d000 r-xp 00000000 08:01 1311132                            /home/server/Projects/email/emailQueue.app
0060d000-0060e000 r--p 0000d000 08:01 1311132                            /home/server/Projects/email/emailQueue.app
0060e000-0060f000 rw-p 0000e000 08:01 1311132                            /home/server/Projects/email/emailQueue.app
01c40000-01c82000 rw-p 00000000 00:00 0                                  [heap]
7f4908000000-7f4908021000 rw-p 00000000 00:00 0
7f4908021000-7f490c000000 ---p 00000000 00:00 0
7f490ce52000-7f490ce5e000 r-xp 00000000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490ce5e000-7f490d05d000 ---p 0000c000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490d05d000-7f490d05e000 r--p 0000b000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490d05e000-7f490d05f000 rw-p 0000c000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490d05f000-7f490d075000 r-xp 00000000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d075000-7f490d275000 ---p 00016000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d275000-7f490d276000 r--p 00016000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d276000-7f490d277000 rw-p 00017000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d277000-7f490d28e000 r-xp 00000000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d28e000-7f490d48d000 ---p 00017000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d48d000-7f490d48e000 r--p 00016000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d48e000-7f490d48f000 rw-p 00017000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d48f000-7f490d491000 rw-p 00000000 00:00 0
7f490d491000-7f490d49a000 r-xp 00000000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d49a000-7f490d69a000 ---p 00009000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d69a000-7f490d69b000 r--p 00009000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d69b000-7f490d69c000 rw-p 0000a000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d69c000-7f490d6ca000 rw-p 00000000 00:00 0
7f490d6ca000-7f490d6e2000 r-xp 00000000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d6e2000-7f490d8e1000 ---p 00018000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d8e1000-7f490d8e2000 r--p 00017000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d8e2000-7f490d8e3000 rw-p 00018000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d8e3000-7f490d8e7000 rw-p 00000000 00:00 0
7f490d8e7000-7f490da61000 r-xp 00000000 08:01 1048743                    /lib/libc-2.12.1.so
7f490da61000-7f490dc60000 ---p 0017a000 08:01 1048743                    /lib/libc-2.12.1.so
7f490dc60000-7f490dc64000 r--p 00179000 08:01 1048743                    /lib/libc-2.12.1.so
7f490dc64000-7f490dc65000 rw-p 0017d000 08:01 1048743                    /lib/libc-2.12.1.so
7f490dc65000-7f490dc6a000 rw-p 00000000 00:00 0
7f490dc6a000-7f490dc7f000 r-xp 00000000 08:01 1048655                    /lib/libgcc_s.so.1
7f490dc7f000-7f490de7e000 ---p 00015000 08:01 1048655                    /lib/libgcc_s.so.1
7f490de7e000-7f490de7f000 r--p 00014000 08:01 1048655                    /lib/libgcc_s.so.1
7f490de7f000-7f490de80000 rw-p 00015000 08:01 1048655                    /lib/libgcc_s.so.1
7f490de80000-7f490df02000 r-xp 00000000 08:01 1051246                    /lib/libm-2.12.1.so
7f490df02000-7f490e101000 ---p 00082000 08:01 1051246                    /lib/libm-2.12.1.so
7f490e101000-7f490e102000 r--p 00081000 08:01 1051246                    /lib/libm-2.12.1.so
7f490e102000-7f490e103000 rw-p 00082000 08:01 1051246                    /lib/libm-2.12.1.so
7f490e103000-7f490e1eb000 r-xp 00000000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e1eb000-7f490e3ea000 ---p 000e8000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e3ea000-7f490e3f2000 r--p 000e7000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e3f2000-7f490e3f4000 rw-p 000ef000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e3f4000-7f490e409000 rw-p 00000000 00:00 0
7f490e409000-7f490e5c7000 r-xp 00000000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e5c7000-7f490e7c7000 ---p 001be000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e7c7000-7f490e7cc000 r--p 001be000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e7cc000-7f490e816000 rw-p 001c3000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e816000-7f490e817000 rw-p 00000000 00:00 0
7f490e817000-7f490e837000 r-xp 00000000 08:01 1048597                    /lib/ld-2.12.1.so
7f490ea15000-7f490ea1c000 rw-p 00000000 00:00 0
7f490ea33000-7f490ea37000 rw-p 00000000 00:00 0
7f490ea37000-7f490ea38000 r--p 00020000 08:01 1048597                    /lib/ld-2.12.1.so
7f490ea38000-7f490ea39000 rw-p 00021000 08:01 1048597                    /lib/ld-2.12.1.so
7f490ea39000-7f490ea3a000 rw-p 00000000 00:00 0
7fffb85b9000-7fffb85da000 rw-p 00000000 00:00 0                          [stack]
7fffb85ff000-7fffb8600000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted

Body:
If you are trying to allocate space for an array of pointers, such as

char** my_array_of_strings;  // or some array of pointers such as int** or even void**

then you will need to consider word size (8 bytes in a 64-bit system, 4 bytes in a 32-bit system) when allocating space for n pointers.  The size of a pointer is the same of your word size.

So while you may wish to allocate space for n pointers, you are actually going to need n times 8 or 4 (for 64-bit or 32-bit systems, respectively)

To avoid overflowing your allocated memory for n elements of 8 bytes:

my_array_of_strings = (char**) malloc( n * 8 );  // for 64-bit systems
my_array_of_strings = (char**) malloc( n * 4 );  // for 32-bit systems

This will return a block of n pointers, each consisting of 8 bytes (or 4 bytes if you're using a 32-bit system)

I have noticed that Linux will allow you to use all n pointers when you haven't compensated for word size, but when you try to free that memory it realizes its mistake and it gives out that rather nasty error.  And it is a bad one, when you overflow allocated memory, many security issues lie in wait.


问:
Click handler for Android ListView
I am trying to find out how to implement a click handler for items in a ListView in Android.

I have a layout file that looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView03lr"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical">
    <LinearLayout
         android:id="@+id/Linear03lr"
         android:layout_width="fill_parent"
         android:orientation="vertical"
         android:gravity="center"
         android:layout_height="fill_parent">

 <!--Put form controls here-->
        <ListView android:id="@+id/ListView01"

 android:layout_width="wrap_content"
 android:layout_height="400dp" />

         <Button
            android:id="@+id/previousbutton"
            android:gravity="center_horizontal"
            android:layout_width = "fill_parent"
            android:layout_height = "fill_parent"

            android:text="Previous Menu"/>
    </LinearLayout>
</ScrollView>
</code>```

..and an activity/class that has the following code in the OnCreate() method:

```<code> ListView lv1;
    lv1=(ListView)findViewById(R.id.ListView01);
    lv1.setTextFilterEnabled(true);
         lv1.setOnItemClickListener(new OnItemClickListener() {
        // @Override
         public void onItemClick(AdapterView<?> a, View v, int position, long id) {
             Toast.makeText(ListRecords.this,"Clicked!", Toast.LENGTH_LONG).show();
         }
         });
</code>```

When I run this code, when I click an item in the ListView, nothing happens.
Can someone help me with this?

答: Get rid of the ScrollView, or move the ListView outside of the ScrollView. Generally, you cannot have scrollable things inside of other scrollable things.

ContentLicense: CC BY-SA 2.5

Title: Click handler for Android ListView

Body:
I am trying to find out how to implement a click handler for items in a ListView in Android.

I have a layout file that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView03lr"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical">
    <LinearLayout
         android:id="@+id/Linear03lr"
         android:layout_width="fill_parent"
         android:orientation="vertical"
         android:gravity="center"
         android:layout_height="fill_parent">

        <ListView android:id="@+id/ListView01"

 android:layout_width="wrap_content"
 android:layout_height="400dp" />

         <Button
            android:id="@+id/previousbutton"
            android:gravity="center_horizontal"
            android:layout_width = "fill_parent"
            android:layout_height = "fill_parent"

            android:text="Previous Menu"/>
    </LinearLayout>
</ScrollView>

..and an activity/class that has the following code in the OnCreate() method:

 ListView lv1;
    lv1=(ListView)findViewById(R.id.ListView01);
    lv1.setTextFilterEnabled(true);
         lv1.setOnItemClickListener(new OnItemClickListener() {
        // @Override
         public void onItemClick(AdapterView<?> a, View v, int position, long id) {
             Toast.makeText(ListRecords.this,"Clicked!", Toast.LENGTH_LONG).show();
         }
         });

When I run this code, when I click an item in the ListView, nothing happens.
Can someone help me with this?


问:
Simon Game how to proceed?
So I am trying to build a Simon Game.
First of all I created a random array with 20 values that varies between 1 and 4 (That would identify each color of the game).
So 1 would be red, 2 would be blue, 3 would be green and 4 would be yellow.
So I got the array which is something like this:

```<code>var arrayRandomColors = [1, 3, 1, 2, 4, 3, 2, 1, 3, 2, 1, 2, 4, 1, 2, 3, 4, 1, 3, 2]
</code>```

Now this is de order of sounds and colors of my Simon Game. However, I now need to go over there array like this:

```<code>Level 1 - [1] -> Level 2 - [1, 3] -> Level 3 - [1, 3, 1] ->  Level 4 - [1, 3, 1, 2]... etc. And then each time it loops over these arrays it plays a sequence o sounds that corresponds to the current level.
</code>```

So that's what I did:

```<code>var j=2;
    var arrayPlay = [];
    for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        console.log(arrayPlay); //[1] -> [1,3] -> [1,3,1]...etc
        arrayPlay = [];
    }
</code>```

So far, I managed to get all the arrays I want. However, I got stuck about how to proceed, because I need to go over this numbers slowly, showing the colors being selected and playing a sound while it loops, and the for loop is just too fast. I thought about doing something like this:

```<code>for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        //console.log(arrayPlay);
        for (var k=0; k<arrayPlay.length; k++){
            var id = setInterval(function(){
                console.log("entrou");
            if (arrayPlay[k] == 1){
                $red.css("background-color", "#ffc1c1");
                $red.delay(500);
                $red.css("background-color", "red");
            }
            else if (arrayPlay[k] == 2){
                $blue.css("background-color", "#a5b0f7");
                $blue.delay(500);
                $blue.css("background-color", "blue");
            }
            else if (arrayPlay[k] == 3){
                $green.css("background-color", "#aff7a5");
                $green.delay(500)
                $green.css("background-color", "green");
            }
            else if (arrayPlay[k] == 4){
                $yellow.css("background-color", "#fffb91");
                $yellow.delay(500);
                $yellow.css("background-color", "yellow");
            }

            }, 500);
        }
        arrayPlay = [];
        console.log("\n");
    }
</code>```

But it doesn't work. Can anyone help me out?

答:
The loop like you said runs too fast. Your idea to use interval is a good step, but there is a gotcha. You used a fixed interval of 500. Now try to imagine it, the loop runs fast and creates a bunch of intervals all 500, so they all will run almost at the same time after 500. We didn't solve the issue, we just delayed the execution by 500.

The solution is to use an incrementing interval. Multiply it by the index (remember to add one because it is zero based). Something like:

```<code>setInterval(..., 500 * (k+1));
</code>```

You probably need to use the index j or a combination of k and j. I will leave that to you to explore, but this answer will get you started.

Title: Simon Game how to proceed?

Body:
So I am trying to build a Simon Game.
First of all I created a random array with 20 values that varies between 1 and 4 (That would identify each color of the game).
So 1 would be red, 2 would be blue, 3 would be green and 4 would be yellow.
So I got the array which is something like this:

var arrayRandomColors = [1, 3, 1, 2, 4, 3, 2, 1, 3, 2, 1, 2, 4, 1, 2, 3, 4, 1, 3, 2]

Now this is de order of sounds and colors of my Simon Game. However, I now need to go over there array like this:

Level 1 - [1] -> Level 2 - [1, 3] -> Level 3 - [1, 3, 1] ->  Level 4 - [1, 3, 1, 2]... etc. And then each time it loops over these arrays it plays a sequence o sounds that corresponds to the current level.

So that's what I did:

var j=2;
    var arrayPlay = [];
    for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        console.log(arrayPlay); //[1] -> [1,3] -> [1,3,1]...etc
        arrayPlay = [];
    }

So far, I managed to get all the arrays I want. However, I got stuck about how to proceed, because I need to go over this numbers slowly, showing the colors being selected and playing a sound while it loops, and the for loop is just too fast. I thought about doing something like this:

for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        //console.log(arrayPlay);
        for (var k=0; k<arrayPlay.length; k++){
            var id = setInterval(function(){
                console.log("entrou");
            if (arrayPlay[k] == 1){
                $red.css("background-color", "#ffc1c1");
                $red.delay(500);
                $red.css("background-color", "red");
            }
            else if (arrayPlay[k] == 2){
                $blue.css("background-color", "#a5b0f7");
                $blue.delay(500);
                $blue.css("background-color", "blue");
            }
            else if (arrayPlay[k] == 3){
                $green.css("background-color", "#aff7a5");
                $green.delay(500)
                $green.css("background-color", "green");
            }
            else if (arrayPlay[k] == 4){
                $yellow.css("background-color", "#fffb91");
                $yellow.delay(500);
                $yellow.css("background-color", "yellow");
            }

            }, 500);
        }
        arrayPlay = [];
        console.log("\n");
    }

But it doesn't work. Can anyone help me out?

Body:
The loop like you said runs too fast. Your idea to use interval is a good step, but there is a gotcha. You used a fixed interval of 500. Now try to imagine it, the loop runs fast and creates a bunch of intervals all 500, so they all will run almost at the same time after 500. We didn't solve the issue, we just delayed the execution by 500.

The solution is to use an incrementing interval. Multiply it by the index (remember to add one because it is zero based). Something like:

setInterval(..., 500 * (k+1));

You probably need to use the index j or a combination of k and j. I will leave that to you to explore, but this answer will get you started.


问:
Group of Tasks condition inno setup
I´m having difficult to combine conditions in Tasks with GroupDescription. If I don´t to use GroupDescription, it works. I need auto select tasks[0] if tasks[2] is selected. I tried:</p>

```<code>[Tasks]
Name: InstallDS; Description: Install DServer?; GroupDescription: InsDS
Name: InstallTG; Description: Install TServer?; GroupDescription: InsDS
Name: InstallOP; Description: Install Optionals?; GroupDescription: InsDS

[Code]
procedure TasksListClickCheck(Sender: TObject);
begin
    WizardForm.TasksList.Checked[0] := WizardForm.TasksList.Checked[2];
end;

procedure InitializeWizard;
begin
    WizardForm.TasksList.OnClickCheck := @TasksListClickCheck
end;

procedure CurPageChanged(CurPageID: Integer);
begin
    if CurPageID = wpSelectTasks then
    begin
        TasksListClickCheck(WizardForm.TasksList);
    end;
end;
</code>```

答:
Once you add GroupDescription, the Consecutive Tasks below the group will be arranged as elements 1,2,3. Inno Tasks section description </p>

```<code>procedure TasksListClickCheck(Sender: TObject);
begin
    if (WizardForm.TasksList.Checked[3] = True) then
    begin
      WizardForm.TasksList.Checked[1] := True;
    end;
end;
</code>```

Title: Group of Tasks condition inno setup

Body:
I´m having difficult to combine conditions in Tasks with GroupDescription. If I don´t to use GroupDescription, it works. I need auto select tasks[0] if tasks[2] is selected. I tried:

[Tasks]
Name: InstallDS; Description: Install DServer?; GroupDescription: InsDS
Name: InstallTG; Description: Install TServer?; GroupDescription: InsDS
Name: InstallOP; Description: Install Optionals?; GroupDescription: InsDS

[Code]
procedure TasksListClickCheck(Sender: TObject);
begin
    WizardForm.TasksList.Checked[0] := WizardForm.TasksList.Checked[2];
end;

procedure InitializeWizard;
begin
    WizardForm.TasksList.OnClickCheck := @TasksListClickCheck
end;

procedure CurPageChanged(CurPageID: Integer);
begin
    if CurPageID = wpSelectTasks then
    begin
        TasksListClickCheck(WizardForm.TasksList);
    end;
end;

Body:
Once you add GroupDescription, the Consecutive Tasks below the group will be arranged as elements 1,2,3. Inno Tasks section description

procedure TasksListClickCheck(Sender: TObject);
begin
    if (WizardForm.TasksList.Checked[3] = True) then
    begin
      WizardForm.TasksList.Checked[1] := True;
    end;
end;


问:
style a textbox into the following format?
I have a field called WATER METER READING(Right now its a textbox to take 6 numbers) on my HTml page, but I need to change its format to display as  [][][][][][] (6 separate small (single digit forms)).... all 6 fields required and all need to be a number.

finally it should look like this.

Water Meter Reading:* [][][][][][]

Any suggestions how to display the values like this.

答: Are you asking for regex validation? Try [\d][\d][\d][\d][\d][\d]</p>


问:
how to show a spinner till the time data recieved from the server in angular2
The project have a service.ts to make ajax call(http.post) and several components(abc.component.ts, bcd.component.ts etc) gets the data from the server through service.ts

I am using

  for the spinner view. But, need a better approach to show loader either gif etc.

I want to show a spinner till the time each component fetch data from the server. How to do that?

service.ts

```<code> getdata(){
      let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        let url = "http://883.82./Ser/soSe";
        return this.http.post(url, clientJson).map((res: Response) => res.json());
    }
</code>```

abc.component.ts

```<code>let clientJson = {
        "aoId": "M_AO_918",
        "viewBys": ["usstate"],
        /* ... */
    };
  this.DataService.getdata(clientJson).subscribe(
        success => this.abcChart(success),
        error => this.errorMessage = error
    );
abcChart(jsonData) {
    /* ... */
}
</code>```

bcd-chart.component.ts

```<code> initData() {
        let clientJson = {
            "aoId": "M_AO_918",
            "viewBys": ["brands"],
            /* ... */
        };
        this.DataService.getdata(clientJson).subscribe(
            success => this.bcdChart(success),
            error => this.errorMessage = error
        );
    }
    bcdChart(jsonData) {
        /* ... */
    }
</code>```

styles.css

```<code>.spinner {
  width: 40px;
  height: 40px;
  background-color: #333;

  margin: 100px auto;
  -webkit-animation: sk-rotateplane 1.2s infinite ease-in-out;
  animation: sk-rotateplane 1.2s infinite ease-in-out;
}

@-webkit-keyframes sk-rotateplane {
  0% { -webkit-transform: perspective(120px) }
  50% { -webkit-transform: perspective(120px) rotateY(180deg) }
  100% { -webkit-transform: perspective(120px) rotateY(180deg)  rotateX(180deg) }
}

@keyframes sk-rotateplane {
  0% {
    transform: perspective(120px) rotateX(0deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg)
  } 50% {
    transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg)
  } 100% {
    transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
    -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
  }
}
.loading{
  background-color: #d35400;
}
</code>```

答:
Create a function called show spinner

get(url: string, options?: RequestOptionsArgs): Observable {
        this.showLoader();

```<code>    //return super.get ....
</code>```

}

2.after success hide loader

```<code>private showLoader(): void {

            this.loaderService.show();
}
 private hideLoader(): void {
            this.loaderService.hide();
}
</code>```

3.Add Loader component

```<code>    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs/Subscription';
    import { LoaderService } from './loader.service';
    import { LoaderState } from './loader';
    @Component({
        selector: 'angular-loader',
        templateUrl: 'loader.component.html',
        styleUrls: ['loader.component.css']
    })
    export class LoaderComponent implements OnInit {
    show = false;
    private subscription: Subscription;
    constructor(private loaderService: LoaderService) { }
    ngOnInit() {

            this.subscription = this.loaderService.loaderState
                .subscribe((state: LoaderState) => {
                    this.show = state.show;
                });
    }
    ngOnDestroy() {
         this.subscription.unsubscribe();
    }

    }
</code>```

Loader component view

Loader Service

```<code>import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { LoaderState } from './loader';
@Injectable()
export class LoaderService {
private loaderSubject = new Subject<LoaderState>();
loaderState = this.loaderSubject.asObservable();
constructor() { }
show() {
        this.loaderSubject.next(<LoaderState>{show: true});
    }
hide() {
        this.loaderSubject.next(<LoaderState>{show: false});
    }
}
</code>```

Body:
The project have a service.ts to make ajax call(http.post) and several components(abc.component.ts, bcd.component.ts etc) gets the data from the server through service.ts

I am using

  for the spinner view. But, need a better approach to show loader either gif etc.

I want to show a spinner till the time each component fetch data from the server. How to do that?

service.ts

 getdata(){
      let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        let url = "http://883.82./Ser/soSe";
        return this.http.post(url, clientJson).map((res: Response) => res.json());
    }

abc.component.ts

let clientJson = {
        "aoId": "M_AO_918",
        "viewBys": ["usstate"],
        /* ... */
    };
  this.DataService.getdata(clientJson).subscribe(
        success => this.abcChart(success),
        error => this.errorMessage = error
    );
abcChart(jsonData) {
    /* ... */
}

bcd-chart.component.ts

 initData() {
        let clientJson = {
            "aoId": "M_AO_918",
            "viewBys": ["brands"],
            /* ... */
        };
        this.DataService.getdata(clientJson).subscribe(
            success => this.bcdChart(success),
            error => this.errorMessage = error
        );
    }
    bcdChart(jsonData) {
        /* ... */
    }

styles.css

.spinner {
  width: 40px;
  height: 40px;
  background-color: #333;

  margin: 100px auto;
  -webkit-animation: sk-rotateplane 1.2s infinite ease-in-out;
  animation: sk-rotateplane 1.2s infinite ease-in-out;
}

@-webkit-keyframes sk-rotateplane {
  0% { -webkit-transform: perspective(120px) }
  50% { -webkit-transform: perspective(120px) rotateY(180deg) }
  100% { -webkit-transform: perspective(120px) rotateY(180deg)  rotateX(180deg) }
}

@keyframes sk-rotateplane {
  0% {
    transform: perspective(120px) rotateX(0deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg)
  } 50% {
    transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg)
  } 100% {
    transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
    -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
  }
}
.loading{
  background-color: #d35400;
}

Body:
Create a function called show spinner

get(url: string, options?: RequestOptionsArgs): Observable {
        this.showLoader();

    //return super.get ....

}

2.after success hide loader

private showLoader(): void {

            this.loaderService.show();
}
 private hideLoader(): void {
            this.loaderService.hide();
}

3.Add Loader component

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs/Subscription';
    import { LoaderService } from './loader.service';
    import { LoaderState } from './loader';
    @Component({
        selector: 'angular-loader',
        templateUrl: 'loader.component.html',
        styleUrls: ['loader.component.css']
    })
    export class LoaderComponent implements OnInit {
    show = false;
    private subscription: Subscription;
    constructor(private loaderService: LoaderService) { }
    ngOnInit() {

            this.subscription = this.loaderService.loaderState
                .subscribe((state: LoaderState) => {
                    this.show = state.show;
                });
    }
    ngOnDestroy() {
         this.subscription.unsubscribe();
    }

    }

Loader component view

Loader Service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { LoaderState } from './loader';
@Injectable()
export class LoaderService {
private loaderSubject = new Subject<LoaderState>();
loaderState = this.loaderSubject.asObservable();
constructor() { }
show() {
        this.loaderSubject.next(<LoaderState>{show: true});
    }
hide() {
        this.loaderSubject.next(<LoaderState>{show: false});
    }
}


问:
#pragma mark in Swift?
In Objective C, I can use #pragma mark to mark sections of my code in the symbol navigator. Since this is a C preprocessor command, it's not available in Swift. Is there a stand-in for this in Swift, or do I have to use ugly comments?

答:
Professional programer must be use this tag for good code.
It is also good for team work.

```<code>// MARK: example Web Service start here
// TODO: example 1
// FIXME: Please change BASE url before live
</code>```

It is easy to find method like this

Title: #pragma mark in Swift?

Body:
Professional programer must be use this tag for good code.
It is also good for team work.

// MARK: example Web Service start here
// TODO: example 1
// FIXME: Please change BASE url before live

It is easy to find method like this

ContentLicense: CC BY-SA 4.0


问:
is it possible/good to have two helper class for one controller and view in rails?
i have too many functions that needs to be used in my view, and my helper class is looking too long. so is it possible/good to have two helper class for a single controller and view?

if so how to define the second helper class?

答:
To create a new helper:

choose a name for the helper file, for instance my_helper.rb

create the file in the /app/helpers directory

create a module according to the file name. In this case

```<code>module MyHelper
end
</code>```

define your helper as method

```<code>module MyHelper
  def hello_world(name)
    "hello #{name}"
  end
end
</code>```

Body:
To create a new helper:

choose a name for the helper file, for instance my_helper.rb

create the file in the /app/helpers directory

create a module according to the file name. In this case

module MyHelper
end

define your helper as method

module MyHelper
  def hello_world(name)
    "hello #{name}"
  end
end


问:
Input from file in C, data types
thanks in advance for taking the time to read through my question...

```<code>/* Binary search for use with Gen_window.comp */
#include <stdio.h>

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        printf("Error opening file!");
  }
  else {
        printf("Processing file...");
  }

  while( (fgets(line, 25, fp) != NULL) ){
        fscanf(fp, "%lf\t%lf", &E, &sig);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n",E, sig);
  }

}
</code>```

Numbers in the file are of the format X.XXXXXX+X or X.XXXXXX-X accordingly.  Does C have a way to specify this as input?  Is it a bother that there is no 'e'.  I cannot find any documentation that tells about inputing exponential, only returning exponential...

I do not need it to print that exact format, any other exponential format would be fine.

I realize there should be some specifiers and precision in my %lf, or maybe it should be %e, but I have tried everything that makes sense to me, so I am basically leaving it blank.

Thanks for your help.

答:
Unfortunately C does require the "e". So you will have to parse the input for yourself. Such as:

```<code>#include <stdio.h>
#include <math.h>

double parse(const char** cursor)
{
    int len;
    double mantissa, exponent;
    char sign;
    sscanf(*cursor, " %lf%[+-]%lf%n", &mantissa, &sign, &exponent, &len);
    *cursor += len;
    return mantissa * pow(10, (sign == '-' ? -exponent : exponent));
}

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        puts("Error opening file!");
        return 1;
  }
  puts("Processing file...");

  while( (fgets(line, 25, fp) != NULL) ){
        const char* cursor = line;
        E = parse(&cursor);
        sig = parse(&cursor);
        printf("The energy is: %e eV\nThe corresponding cross section is: %e barns\n",E, sig);
  }
  return 0;
}
</code>```

(Add error handling as needed)

Title: Input from file in C, data types

Body:
thanks in advance for taking the time to read through my question...

/* Binary search for use with Gen_window.comp */
#include <stdio.h>

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        printf("Error opening file!");
  }
  else {
        printf("Processing file...");
  }

  while( (fgets(line, 25, fp) != NULL) ){
        fscanf(fp, "%lf\t%lf", &E, &sig);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n",E, sig);
  }

}

Numbers in the file are of the format X.XXXXXX+X or X.XXXXXX-X accordingly.  Does C have a way to specify this as input?  Is it a bother that there is no 'e'.  I cannot find any documentation that tells about inputing exponential, only returning exponential...

I do not need it to print that exact format, any other exponential format would be fine.

I realize there should be some specifiers and precision in my %lf, or maybe it should be %e, but I have tried everything that makes sense to me, so I am basically leaving it blank.

Thanks for your help.

Body:
Unfortunately C does require the "e". So you will have to parse the input for yourself. Such as:

#include <stdio.h>
#include <math.h>

double parse(const char** cursor)
{
    int len;
    double mantissa, exponent;
    char sign;
    sscanf(*cursor, " %lf%[+-]%lf%n", &mantissa, &sign, &exponent, &len);
    *cursor += len;
    return mantissa * pow(10, (sign == '-' ? -exponent : exponent));
}

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        puts("Error opening file!");
        return 1;
  }
  puts("Processing file...");

  while( (fgets(line, 25, fp) != NULL) ){
        const char* cursor = line;
        E = parse(&cursor);
        sig = parse(&cursor);
        printf("The energy is: %e eV\nThe corresponding cross section is: %e barns\n",E, sig);
  }
  return 0;
}

(Add error handling as needed)


问:
JavaMail Exchange server MimeContent
I am using JavaMail api and I have to send email through Exchange server and then embed image on the email body. For this I am using ExchangeService for getting connected with Exchange server. Note: If it is SMTP, I would gone through Session and Authenticator.

The challenge I face here is I have to use EmailMessage for sending the mail finally. I dont have option to set the embed message(MIMEContent) in the EmailMessage and send it.

```<code>try{

                    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                    ExchangeCredentials credentials = new WebCredentials(userName, password, domain);
                    service.setCredentials(credentials);
                    service.setUrl(new URI(host));
                    EmailMessage msg = new EmailMessage(service);
                    msg.setSubject(subject); //email subject
                    msg.getFrom().setAddress(from);
                    msg.getToRecipients().add(to); //email receiver
                    MimeBodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setContent(bodyStart, "text/html");

                    // creates multi-part
                    MimeMultipart multipart = new MimeMultipart();
                    multipart.addBodyPart(messageBodyPart);
                    MimeBodyPart imagePart = new MimeBodyPart();
                    imagePart.setHeader("Content-ID", "<123234325>");
                    imagePart.setDisposition(MimeBodyPart.INLINE);
                    imagePart.attachFile("C:/selenium/ma000xsspf01.png");
                    multipart.addBodyPart(imagePart);
                    msg.send(); //send email
}catch(Exception e){
}
</code>```

Someone please let know how shall i use object "msg" to set the image in it as a embedded one.

答: By making use of Datahandler.I think this is the one you are looking for mail with attachment.

Title: JavaMail Exchange server MimeContent

Body:
I am using JavaMail api and I have to send email through Exchange server and then embed image on the email body. For this I am using ExchangeService for getting connected with Exchange server. Note: If it is SMTP, I would gone through Session and Authenticator.

The challenge I face here is I have to use EmailMessage for sending the mail finally. I dont have option to set the embed message(MIMEContent) in the EmailMessage and send it.

try{

                    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                    ExchangeCredentials credentials = new WebCredentials(userName, password, domain);
                    service.setCredentials(credentials);
                    service.setUrl(new URI(host));
                    EmailMessage msg = new EmailMessage(service);
                    msg.setSubject(subject); //email subject
                    msg.getFrom().setAddress(from);
                    msg.getToRecipients().add(to); //email receiver
                    MimeBodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setContent(bodyStart, "text/html");

                    // creates multi-part
                    MimeMultipart multipart = new MimeMultipart();
                    multipart.addBodyPart(messageBodyPart);
                    MimeBodyPart imagePart = new MimeBodyPart();
                    imagePart.setHeader("Content-ID", "<123234325>");
                    imagePart.setDisposition(MimeBodyPart.INLINE);
                    imagePart.attachFile("C:/selenium/ma000xsspf01.png");
                    multipart.addBodyPart(imagePart);
                    msg.send(); //send email
}catch(Exception e){
}

Someone please let know how shall i use object "msg" to set the image in it as a embedded one.


问:
Remove child image from RelativeLayout
I have a set of images in a RelativeLayout, and I'd like to programmatically remove some of them. Is there some kind of metadata property (ie ID, tag etc) that I can assign these images (when adding them to the layout), so that I can easily find and them remove them?

Scenario: As a learning tool I am making a tower defence game. As a unit is killed, I want to remove its image. There are ~20 other units/images in the layout at the time.

thanks

答:
// remove all imageview from layout

```<code>               for (int pos = 0; pos < relativeLayout.getChildCount(); pos++)                            {
                if (relativeLayout.getChildAt(pos) instanceof ImageView) {
                    relativeLayout.removeView(relativeLayout.getChildAt(pos));
                }
</code>```

// remove imageview by tag from layout

//set Tag to imageview

```<code>          imageview.setTag("yourimagetag");
</code>```

//get imageview tag  and remove

```<code>for (int pos = 0; pos < relativeLayout.getChildCount(); pos++)
  {
    Object tag = relativeLayout.getChildAt(pos).getTag();
    if (tag != null && tag.toString().equals("yourimagetag")) {
    relativeLayout.removeView(relativeLayout.getChildAt(pos));
  }
</code>```

Title: Remove child image from RelativeLayout

Body:
// remove all imageview from layout

               for (int pos = 0; pos < relativeLayout.getChildCount(); pos++)                            {
                if (relativeLayout.getChildAt(pos) instanceof ImageView) {
                    relativeLayout.removeView(relativeLayout.getChildAt(pos));
                }

// remove imageview by tag from layout

//set Tag to imageview

          imageview.setTag("yourimagetag");

//get imageview tag  and remove

for (int pos = 0; pos < relativeLayout.getChildCount(); pos++)
  {
    Object tag = relativeLayout.getChildAt(pos).getTag();
    if (tag != null && tag.toString().equals("yourimagetag")) {
    relativeLayout.removeView(relativeLayout.getChildAt(pos));
  }


问:
sql query update table with missing fields from another table
I have an issue with a SQL query/SP where I'm trying to update a table that has missing data in specific fields from another table where the data in those same fields exists and is valid.  The trick here is I would like to anchor on a value in the first table.  I can make it work with a INSERT INTO / SELECT FROM combo, but it creates a duplicate record.

Im using mysql 5.x.  Here are the details. The table with missing data is thisweek and the table with valid data is lastweek. Field 1 is MACAddress (which exists and is the anchor) and exists in both tables (for ex. BE:EF:BA:BE:CA:FE), Fields 2-10 in thisweek are blank (''), but there is data in those same fields(Fields2-10) in table lastweek.

```<code>UPDATE thisweek
SET thisweek.field2 = lastweek.field2
where thisweek.MACAddress = lastweek.MACAddress and thisweek.filed2 = '';
</code>```

I know that query isn't anywhere close, so looking for help.  Again, the same MACAddress exists in both tables, with the only difference between tables being that field2 in thisweek is blank (and it shouldn't be) and needs to be equal to lastweek.field2 for that MACAddress.

Thanks all.

答:
```<code>update table1
inner join table2 on table1.id = table2.id and (table1.name = '' or table1.name is null)
set table1.name = table2.name;
</code>```

Body:
I have an issue with a SQL query/SP where I'm trying to update a table that has missing data in specific fields from another table where the data in those same fields exists and is valid.  The trick here is I would like to anchor on a value in the first table.  I can make it work with a INSERT INTO / SELECT FROM combo, but it creates a duplicate record.

Im using mysql 5.x.  Here are the details. The table with missing data is thisweek and the table with valid data is lastweek. Field 1 is MACAddress (which exists and is the anchor) and exists in both tables (for ex. BE:EF:BA:BE:CA:FE), Fields 2-10 in thisweek are blank (''), but there is data in those same fields(Fields2-10) in table lastweek.

UPDATE thisweek
SET thisweek.field2 = lastweek.field2
where thisweek.MACAddress = lastweek.MACAddress and thisweek.filed2 = '';

I know that query isn't anywhere close, so looking for help.  Again, the same MACAddress exists in both tables, with the only difference between tables being that field2 in thisweek is blank (and it shouldn't be) and needs to be equal to lastweek.field2 for that MACAddress.

Thanks all.


问:
Bootstrap 3 fixed footer is breaking my mobile site
I'm using a fixed footer on my webpage.

On mobile, it is fixing to the bottom of the page and covering other content.

How can I change it so that the footer is fixed only on large/desktop screens?

答:
Use media query css for the solution.

```<code>@media (min-width:320px)  { .navbar-fixed-bottom{position:relative !important;} }
@media (min-width:480px)  { .navbar-fixed-bottom{position:relative !important;} }
@media (min-width:600px)  { .navbar-fixed-bottom{position:relative !important;} }
</code>```

Hope this answer helpful to you.

Body:
Use media query css for the solution.

@media (min-width:320px)  { .navbar-fixed-bottom{position:relative !important;} }
@media (min-width:480px)  { .navbar-fixed-bottom{position:relative !important;} }
@media (min-width:600px)  { .navbar-fixed-bottom{position:relative !important;} }

Hope this answer helpful to you.


问:
Filter function in jquery with relevant value
I have used the following filter funtion,

```<code>$.each(contacts,function(i,contact){

            var keyword = (contact.dept+';'+contact.name+';'+contact.location+';'+contact.extn).toLowerCase();

            if( keyword.indexOf(newSearchValue) != -1){
                newdata.push(contact);
            }
        });
</code>```

Its works fine. It filters by ascending order by default. But i need exactly  what i am trying to search should come on top and the rest below. How can i get this result?

答:
It is a question of how you set up your newdata array:

```<code>var newdata=['newSearchValue'];
// then put your code snippet here
</code>```

This way your results array starts off with the search expression itself on top with the actual search results following that.

Body:
I have used the following filter funtion,

$.each(contacts,function(i,contact){

            var keyword = (contact.dept+';'+contact.name+';'+contact.location+';'+contact.extn).toLowerCase();

            if( keyword.indexOf(newSearchValue) != -1){
                newdata.push(contact);
            }
        });

Its works fine. It filters by ascending order by default. But i need exactly  what i am trying to search should come on top and the rest below. How can i get this result?

Body:
It is a question of how you set up your newdata array:

var newdata=['newSearchValue'];
// then put your code snippet here

This way your results array starts off with the search expression itself on top with the actual search results following that.


问:
How to open command prompt from powershell
I am new to powershell.

Can any body please explain me how to open command prompt from powershell.

I want to open command prompt and run Dir command

Is it possible to use new-object -comobject for this???

答:
Just run start cmd.

That will open Command Prompt in a new window.


答:
After created the array of newdata. you need to sort array like this

```<code>$.each(contacts, function(i, contact) {
  var keyword = (contact.dept + ';' + contact.name + ';' + contact.location + ';' + contact.extn).toLowerCase();

  if (keyword.indexOf(newSearchValue) != -1) {
    newdata.push(contact);
  }
});

newdata =newdata.sort(function(a, b){
return b.indexOf(newSearchValue) - a.indexOf(newSearchValue);
})
</code>```

Example

Updated

var newdata = [{  "id": "86",  "name": "fgdf",  "password": "",  "dept": "test",  "extn": "534534",  "mobile_no": "97767867677",  "location": "xxxx",  "email": "xxxx@gmail.commn",  "type": "0",  "dept_id": "1",
  "created_on": "2017-06-30 11:19:03",  "loc_id": "3"}, {  "id": "85",
  "name": "new",  "password": "",  "dept": "test1",  "extn": "565",
  "mobile_no": "4357347853945",  "location": "yyyyy",  "email": "test@gmail.com",  "type": "0",  "dept_id": "3",  "created_on": "2017-06-30 11:19:03",  "loc_id": "3"}]

var newSearchValue = 'h';//change the as your wish

newdata = newdata.sort(function(a, b) {
   var a1 = (a.dept + ';' + a.name + ';' + a.location + ';' + a.extn).toLowerCase()
      var b1 = (b.dept + ';' + b.name + ';' + b.location + ';' + a.extn).toLowerCase()
  return b1.indexOf(newSearchValue) - a1.indexOf(newSearchValue);
})

console.log(newdata)```

Title: Filter function in jquery with relevant value

Body:
After created the array of newdata. you need to sort array like this

$.each(contacts, function(i, contact) {
  var keyword = (contact.dept + ';' + contact.name + ';' + contact.location + ';' + contact.extn).toLowerCase();

  if (keyword.indexOf(newSearchValue) != -1) {
    newdata.push(contact);
  }
});

newdata =newdata.sort(function(a, b){
return b.indexOf(newSearchValue) - a.indexOf(newSearchValue);
})

Example

Updated

var newdata = [{  "id": "86",  "name": "fgdf",  "password": "",  "dept": "test",  "extn": "534534",  "mobile_no": "97767867677",  "location": "xxxx",  "email": "xxxx@gmail.commn",  "type": "0",  "dept_id": "1",
  "created_on": "2017-06-30 11:19:03",  "loc_id": "3"}, {  "id": "85",
  "name": "new",  "password": "",  "dept": "test1",  "extn": "565",
  "mobile_no": "4357347853945",  "location": "yyyyy",  "email": "test@gmail.com",  "type": "0",  "dept_id": "3",  "created_on": "2017-06-30 11:19:03",  "loc_id": "3"}]

var newSearchValue = 'h';//change the as your wish

newdata = newdata.sort(function(a, b) {
   var a1 = (a.dept + ';' + a.name + ';' + a.location + ';' + a.extn).toLowerCase()
      var b1 = (b.dept + ';' + b.name + ';' + b.location + ';' + a.extn).toLowerCase()
  return b1.indexOf(newSearchValue) - a1.indexOf(newSearchValue);
})

console.log(newdata)


问:
Database Controller: Login
I am very new to C# and it is not as easy as PHP. lol.

I'm doing a DB_Controller class where I put in the code for the Database connection. I also have a Login_Model class where I put the functions for Login.
I'm trying to build a some sort of MVC type concept, so that I can easily code in the future.

However, the code I constructed is not even working. lol. I am having an error which is InvalidOperationException was Unhandled - An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll

Below is my code:

LoginForm.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MacoApp
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            String user = txtbox_id.Text;
            String pass = txtbox_pin.Text;

            Boolean log = Login_Model.validate_login(user, pass);

            //Login Procedure
            if (log)
            {
                MessageBox.Show("Thank you for logging in!");
            }
            else
            {
                MessageBox.Show("Oops! Incorrect Login");
            }
        }
    }
}
</code>```

Login_Model.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MacoApp
{
    class Login_Model
    {
        public static MySqlConnection connect;

        public static bool validate_login(string user, string pass)
        {
            DB_Controller.db_connection();
            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandText = "Select * from users where username=@user and password=@pass";
            cmd.Parameters.AddWithValue("@user", user);
            cmd.Parameters.AddWithValue("@pass", pass);
            cmd.Connection = connect;
            MySqlDataReader login = cmd.ExecuteReader();
            if (login.Read())
            {
                connect.Close();
                return true;
            }
            else
            {
                connect.Close();
                return false;
            }
        }
    }
}
</code>```

DB_Controller.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MacoApp
{
    class DB_Controller
    {

        public static void db_connection()
        {
            try
            {
                MySqlConnection connect;
                String conn = "Server=localhost;Database=macoapp;Uid=root;Pwd=;";
                connect = new MySqlConnection(conn);
                connect.Open();
            }
            catch (MySqlException e)
            {
                throw;
            }
        }
    }
}
</code>```

Your help is much appreciated.

答:
The static connection variables in your model and db_controller classes are not related. You never initialize the former, which is most likely what causes the MySQL API to crash.
But please start by figuring out how to get the Message and StackTrace of your exceptions, that will make finding the errors much easier both for yourself and the community.</p>

Title: Database Controller: Login

Body:
I am very new to C# and it is not as easy as PHP. lol.

I'm doing a DB_Controller class where I put in the code for the Database connection. I also have a Login_Model class where I put the functions for Login.
I'm trying to build a some sort of MVC type concept, so that I can easily code in the future.

However, the code I constructed is not even working. lol. I am having an error which is InvalidOperationException was Unhandled - An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll

Below is my code:

LoginForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MacoApp
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            String user = txtbox_id.Text;
            String pass = txtbox_pin.Text;

            Boolean log = Login_Model.validate_login(user, pass);

            //Login Procedure
            if (log)
            {
                MessageBox.Show("Thank you for logging in!");
            }
            else
            {
                MessageBox.Show("Oops! Incorrect Login");
            }
        }
    }
}

Login_Model.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MacoApp
{
    class Login_Model
    {
        public static MySqlConnection connect;

        public static bool validate_login(string user, string pass)
        {
            DB_Controller.db_connection();
            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandText = "Select * from users where username=@user and password=@pass";
            cmd.Parameters.AddWithValue("@user", user);
            cmd.Parameters.AddWithValue("@pass", pass);
            cmd.Connection = connect;
            MySqlDataReader login = cmd.ExecuteReader();
            if (login.Read())
            {
                connect.Close();
                return true;
            }
            else
            {
                connect.Close();
                return false;
            }
        }
    }
}

DB_Controller.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MacoApp
{
    class DB_Controller
    {

        public static void db_connection()
        {
            try
            {
                MySqlConnection connect;
                String conn = "Server=localhost;Database=macoapp;Uid=root;Pwd=;";
                connect = new MySqlConnection(conn);
                connect.Open();
            }
            catch (MySqlException e)
            {
                throw;
            }
        }
    }
}

Your help is much appreciated.


问:
Mockito/Powermock not working as expected with Kotlin
I'm using mockito/powermock version 1.7.0, Spring Boot 2.0.0 M2, Kotlin 1.3.0.

I'm testing a Spring @Service class, that inject a Repository.
I want to mock that repository on my tests, so I can just test the class itself.

I'm new to Kotlin, but I come from Java, so I tried doing this "the java way", but probably I'm missing something...

Here is my Service interface:

```<code>interface MyService {
    fun create(myObject: MyObject): MyObject
}
</code>```

... and its implementation:

```<code>@Service
class DefaultMyService : MyService {
    @Autowired
    lateinit var myRepository: MyRepository
    override fun create(myObject: MyObject): MyObject = this.myRepository.insert(myObject)
}
</code>```

Here is my repository (I'm using Spring Data with Mongo):

```<code>interface MyRepository: MongoRepository<MyObject, String>
</code>```

Here is my test class:

```<code>@RunWith(PowerMockRunner::class)
@PrepareForTest(MyService::class)
class MyServiceTest {
    @Mock
    lateinit var myRepository: MyRepository
    @InjectMocks
    lateinit var myService: MyService

    @Test
    fun shouldDoSomething() {
        val myObject = MyObject(name = "Marco")
        `when`(myRepository.insert(myObject)).thenReturn(myObject)
        assertEquals(myObject.name, this.myService.create(myObject).name)
    }
}
</code>```

When I run this test, an exception occurs:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/mockito/exceptions/Reporter
    at sun.reflect.GeneratedSerializationConstructorAccessor5.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48)
    at org.powermock.reflect.internal.WhiteboxImpl.newInstance(WhiteboxImpl.java:260)
    at org.powermock.reflect.Whitebox.newInstance(Whitebox.java:139)
    at org.powermock.api.extension.reporter.AbstractMockingFrameworkReporterFactory.getInstanceForClassLoader(AbstractMockingFrameworkReporterFactory.java:41)
    at org.powermock.api.extension.reporter.AbstractMockingFrameworkReporterFactory.create(AbstractMockingFrameworkReporterFactory.java:35)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.getMockingFrameworkReporter(JUnit4TestSuiteChunkerImpl.java:140)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:119)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ClassNotFoundException: org.mockito.exceptions.Reporter
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 16 more
</code>```

What am I doing wrong? I think it's an issue with some configuration, but I can't understand exactly where the mistake is.

答:
It seems like that your mockito and powermock versions are not working very well together. You have to use versions which are compatible. See the compatibility matrix of powermock https://github.com/powermock/powermock/wiki/Mockito#supported-versions

Latest compatible is Mockito: 2.8.x   with PowerMock: 1.7.0

Body:
I'm using mockito/powermock version 1.7.0, Spring Boot 2.0.0 M2, Kotlin 1.3.0.

I'm testing a Spring @Service class, that inject a Repository.
I want to mock that repository on my tests, so I can just test the class itself.

I'm new to Kotlin, but I come from Java, so I tried doing this "the java way", but probably I'm missing something...

Here is my Service interface:

interface MyService {
    fun create(myObject: MyObject): MyObject
}

... and its implementation:

@Service
class DefaultMyService : MyService {
    @Autowired
    lateinit var myRepository: MyRepository
    override fun create(myObject: MyObject): MyObject = this.myRepository.insert(myObject)
}

Here is my repository (I'm using Spring Data with Mongo):

interface MyRepository: MongoRepository<MyObject, String>

Here is my test class:

@RunWith(PowerMockRunner::class)
@PrepareForTest(MyService::class)
class MyServiceTest {
    @Mock
    lateinit var myRepository: MyRepository
    @InjectMocks
    lateinit var myService: MyService

    @Test
    fun shouldDoSomething() {
        val myObject = MyObject(name = "Marco")
        `when`(myRepository.insert(myObject)).thenReturn(myObject)
        assertEquals(myObject.name, this.myService.create(myObject).name)
    }
}

When I run this test, an exception occurs:

Exception in thread "main" java.lang.NoClassDefFoundError: org/mockito/exceptions/Reporter
    at sun.reflect.GeneratedSerializationConstructorAccessor5.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48)
    at org.powermock.reflect.internal.WhiteboxImpl.newInstance(WhiteboxImpl.java:260)
    at org.powermock.reflect.Whitebox.newInstance(Whitebox.java:139)
    at org.powermock.api.extension.reporter.AbstractMockingFrameworkReporterFactory.getInstanceForClassLoader(AbstractMockingFrameworkReporterFactory.java:41)
    at org.powermock.api.extension.reporter.AbstractMockingFrameworkReporterFactory.create(AbstractMockingFrameworkReporterFactory.java:35)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.getMockingFrameworkReporter(JUnit4TestSuiteChunkerImpl.java:140)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:119)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ClassNotFoundException: org.mockito.exceptions.Reporter
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 16 more

What am I doing wrong? I think it's an issue with some configuration, but I can't understand exactly where the mistake is.


答:
Could you make 6 very narrow textboxes.

Add validation controls to make them required fields.

In code-behind, read the values from the textboxes, and concatenate them into a single string.

Title: style a textbox into the following format?

Body:
I have a field called WATER METER READING(Right now its a textbox to take 6 numbers) on my HTml page, but I need to change its format to display as  [][][][][][] (6 separate small (single digit forms)).... all 6 fields required and all need to be a number.

finally it should look like this.

Water Meter Reading:* [][][][][][]

Any suggestions how to display the values like this.


问:
AWS Autoscaling Thinks Dead Instance is Alive
My autoscaling group in AWS is all messed up... I tried scaling down, but for some reason it wasn't terminating the instances... they just stayed stuck at "Terminating:Wait" for hours. So I gave up and just terminated them manually, but now they're still there in the Auto Scaling group's Instance list, saying "Terminating:Wait" even though they no longer exist in any way.

How do I fix this?

答:
It appears that you have Lifecycle Hooks activated on your Auto Scaling group.

When an instance is terminated with a Lifecycle Hook active, the instance is not immediately terminated. Rather, it is placed into the Terminating:Wait state and a message is sent via SNS or SQS to signal the pending termination. You are meant to have a process that receives this message, does whatever it needs to do (eg copy off log files) and then signals that the instance may be terminated.

If the termination signal is not received after 90 minutes, the instance will be terminated. So, you'll probably find they are gone now.

It's very strange to have Lifecycle Hooks activated unintentionally because they can only be added via an API call.


问:
recyclerview for chat not display first message from bottom
I had implemented recyclerview for chat module but i had 1 problem that first message must be from bottom of screen but right now it is not possible it shows at top of screen and then it scrolls down so how can i set it to bottom. I had tried various things which are already listed at below but it not set

1) linearlayoutManager.setStackFromEnd(true);`

2) In xml also

```<code><android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stackFromBottom="true"/>
</code>```

3)

```<code>layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
layoutManager.setSmoothScrollbarEnabled(true);
</code>```

4) I also tried with below link also but not possible
RecyclerView for chat app

kindly help me.

答:
Try doing this</p>

```<code>layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
layoutManager.setSmoothScrollbarEnabled(true);
layoutManager.setReverseLayout(true);
</code>```

Body:
I had implemented recyclerview for chat module but i had 1 problem that first message must be from bottom of screen but right now it is not possible it shows at top of screen and then it scrolls down so how can i set it to bottom. I had tried various things which are already listed at below but it not set

1) linearlayoutManager.setStackFromEnd(true);`

2) In xml also

<android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stackFromBottom="true"/>

3)

layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
layoutManager.setSmoothScrollbarEnabled(true);

4) I also tried with below link also but not possible
RecyclerView for chat app

kindly help me.

Body:
Try doing this

layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
layoutManager.setSmoothScrollbarEnabled(true);
layoutManager.setReverseLayout(true);


问:
validation form using php code
Hi i am trying to build a form and insert the data to my db it's working perfect now i want to make it validation using php to prevent span inputs i am beginner at php so p;ease i need help with this

and the php code

```<code>      <?php
     $nameErr = $emailErr = $genderErr = $websiteErr = "";
      $con = mysqli_connect('localhost','root','');

        if(!$con)
         {echo'not connect';}

       if(!mysqli_select_db($con,'form'))
        {echo'not selected';}
         $name=$_POST['name'];
         $phone=$_POST['phone'];
         $nationality=$_POST['nationality'];
         $country=$_POST['country'];
         $sql = "INSERT INTO newform(Name,Number,Nationality,Country)                   VALUES('$name','$phone','$nationality','$country')";
          if(!mysqli_query($con,$sql))
         {echo'not insert';}
        else
        {
            echo'insertes';
         }
        header("refresh:2;url=form.php");
          ?>
</code>```

答:
```<code><!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$error = false;
$nameErr = $phoneErr = $nationalErr = $countErr = "";
$con = mysqli_connect('localhost','root','');
if(!$con)
{
    echo 'not connect';
}
if(!mysqli_select_db($con,'form'))
{
    echo' DB not selected';
}
if(isset($_POST['submit'])){
    $name=$_POST['name'];
    $phone=$_POST['phone'];
    $nationality=$_POST['nationality'];
    $country=$_POST['country'];
    if($name ==""){
        $error = true;
        $nameErr = "Name field is empty";
    }
    if($phone ==""){
        $error = true;
        $phoneErr = "phone field is empty";
    }
    if($nationality ==""){
        $error = true;
        $nationalErr = "nationality field is empty";
    }
    if($country ==""){
        $error = true;
        $countErr = "country field is empty";
    }
    if($error == false){
        $sql = "INSERT INTO newform(Name,Number,Nationality,Country) VALUES($name,$phone,$nationality,$country')";
        if(!mysqli_query($con,$sql))
        {
            echo 'Values not insert';
        }else
        {
            header("refresh:2;url=form.php");
        }
    }
}
?>
<form method="post">
First name:<br>
<input type="text" name="name">
<p  style="color:red"><?php echo $nameErr ?></p>
<br>
phone:<br>
<input type="text" name="phone">
<p  style="color:red"><?php echo $phoneErr ?></p>
<br><br>
Nationality:<br>
<input type="text" name="nationality">
<p  style="color:red"><?php echo $nationalErr ?></p>
<br><br>
Country:<br>
<input type="text" name="country">
<p style="color:red"><?php echo $countErr ?></p>
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</code>```

Title: validation form using php code

Body:
Hi i am trying to build a form and insert the data to my db it's working perfect now i want to make it validation using php to prevent span inputs i am beginner at php so p;ease i need help with this

and the php code

      <?php
     $nameErr = $emailErr = $genderErr = $websiteErr = "";
      $con = mysqli_connect('localhost','root','');

        if(!$con)
         {echo'not connect';}

       if(!mysqli_select_db($con,'form'))
        {echo'not selected';}
         $name=$_POST['name'];
         $phone=$_POST['phone'];
         $nationality=$_POST['nationality'];
         $country=$_POST['country'];
         $sql = "INSERT INTO newform(Name,Number,Nationality,Country)                   VALUES('$name','$phone','$nationality','$country')";
          if(!mysqli_query($con,$sql))
         {echo'not insert';}
        else
        {
            echo'insertes';
         }
        header("refresh:2;url=form.php");
          ?>


问:
Azure SQL in SQL Server Management Studio 17 - Can't edit data manually
I have a table, which I have clicked Edit top 200 rows, as I wish to flip a cell in one of my columns which is  smallint from a 0 to a 1. Every time I change the cell's data from a 0 to a 1 it is automatically changed back to a 0.

It seems that all of my columns are immutable in this way, what am I missing so that I can edit data in my sql database table manually for testing? I am using SQL Server Management Studio 17.

答:
When using Microsoft SQL Server Migration Assistant which converts a MySQL database to an MSSQL or Azure Sql database, triggers are generated for you during the migration and added to your SQL tables.

In my case, these were stopping me from updating and inserting to my table, so I deleted them.


问:
Complete Comments REGEX for LEX
I am working on building a calculator compiler using Lex and Yacc. The idea is based upon the following resource: http://epaperpress.com/lexandyacc/index.html.

For the given input file I need to identify all of the comments:

```<code>//.TEST -- JWJ
//.Step final  -- testing all requirements
//.source: test-1m.cal
//.expected output: test-1m_expected.out

/**
 *  This program will use Newton's method to estimate the roots of

 This should be a comment as well, but does not get picked up

 *  f(x) = x^3 - 3*x
 */
 float xn;
 float xo;
// int num_iterations;
 xo = 3.0;
 xn = 3.0;
 num_iterations = 1;

 /* A do-while loop */
 do {
  print xo;
  xo = xn;
  xn = xo - ( xo * xo * xo - 3.0 * xo  ) / ( 3.0 * xo * xo - 3.0);
  num_iterations = num_iterations + 1;
} while ( num_iterations <= 6 )

print xn; // The root found using Newton's method.
print (xo * xo * xo - 3.0 * xo ); // Print f(xn), which should be 0.
</code>```

I am using the following regular expressions in my lex file:

```<code>"//"[^\n]*|"\/\*".*"\*\/"
"\/\*"([^\n])*
(.)*"\*\/"
</code>```

I do not understand why multiple line comments are not being matched? Could someone please offer some insight?

答:
The regular expression for comments in C or C++ program is like:

"//".*|"/*"(.*[\n].*)*"*/"

Title: Complete Comments REGEX for LEX

Body:
I am working on building a calculator compiler using Lex and Yacc. The idea is based upon the following resource: http://epaperpress.com/lexandyacc/index.html.

For the given input file I need to identify all of the comments:

//.TEST -- JWJ
//.Step final  -- testing all requirements
//.source: test-1m.cal
//.expected output: test-1m_expected.out

/**
 *  This program will use Newton's method to estimate the roots of

 This should be a comment as well, but does not get picked up

 *  f(x) = x^3 - 3*x
 */
 float xn;
 float xo;
// int num_iterations;
 xo = 3.0;
 xn = 3.0;
 num_iterations = 1;

 /* A do-while loop */
 do {
  print xo;
  xo = xn;
  xn = xo - ( xo * xo * xo - 3.0 * xo  ) / ( 3.0 * xo * xo - 3.0);
  num_iterations = num_iterations + 1;
} while ( num_iterations <= 6 )

print xn; // The root found using Newton's method.
print (xo * xo * xo - 3.0 * xo ); // Print f(xn), which should be 0.

I am using the following regular expressions in my lex file:

"//"[^\n]*|"\/\*".*"\*\/"
"\/\*"([^\n])*
(.)*"\*\/"

I do not understand why multiple line comments are not being matched? Could someone please offer some insight?


答:
I can't see where you're using the connection object.

Try these steps

Create the connection and return it from  db_connection()

public static void db_connection()
{
    ...
    return connect;
}
```

<ol start="2">
<li>Use this connection in MySqlCommand</li>
</ol>

<pre class="lang-cs prettyprint-override"><code>public static bool validate_login(string user, string pass)
{
    Login_Model.connect = DB_Controller.db_connection();
    MySqlCommand cmd = new MySqlCommand(Login_Model.connect);
}
</code>```

Title: Database Controller: Login

Body:
I can't see where you're using the connection object.

Try these steps

Create the connection and return it from  db_connection()

public static void db_connection()
{
    ...
    return connect;
}

Use this connection in MySqlCommand

public static bool validate_login(string user, string pass)
{
    Login_Model.connect = DB_Controller.db_connection();
    MySqlCommand cmd = new MySqlCommand(Login_Model.connect);
}


问:
Java name clash error, a method has the same erasure as another method
I have two classes as follows

class QueryResult:

```<code>public class QueryResult
{
...
public static List sortResults(boolean ascending, List<QueryResult> toSort)
    {   ...
    }
}
</code>```

and class CaseResult:

```<code>public class CaseResult extends QueryResult
{
...
public static List sortResults(boolean ascending, List<CaseResult> toSort)
    {   ...
    }
}
</code>```

I am getting the following error:

Name clash: The method sortResults(boolean, List) of type
  CaseResult has the same erasure as sortResults(boolean,
  List) of type QueryResult but does not hide
  it    CaseResult.java

I tried answers under the similar question Java generics name clash , has the same erasure but got more errors. I think I may misunderstand something or those answers do not fit my case.

Could someone please provide any solutions or explain more to help me understand? Thank you all.

答:
As per Java Documentation,

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method has important implications:

The version of the overridden instance method that gets invoked is the one in the subclass.

The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass

Body:
I have two classes as follows

class QueryResult:

public class QueryResult
{
...
public static List sortResults(boolean ascending, List<QueryResult> toSort)
    {   ...
    }
}

and class CaseResult:

public class CaseResult extends QueryResult
{
...
public static List sortResults(boolean ascending, List<CaseResult> toSort)
    {   ...
    }
}

I am getting the following error:

Name clash: The method sortResults(boolean, List) of type
  CaseResult has the same erasure as sortResults(boolean,
  List) of type QueryResult but does not hide
  it    CaseResult.java

I tried answers under the similar question Java generics name clash , has the same erasure but got more errors. I think I may misunderstand something or those answers do not fit my case.

Could someone please provide any solutions or explain more to help me understand? Thank you all.


问:
Split or extract a Value from a vector SCALA
I am working with the following list in a text file:

```<code>10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48
</code>```

I am creating some indexes to analysis the table, then if each column is (s,p,o) and I create a map that is P -> SO I create it of the form

```<code>val dicP_SO: scala.collection.mutable.Map[Int, Vector[Vector[Int]]] = collection.mutable.Map[Int, Vector[Vector[Int]]]()
</code>```

I read the file, and create the mapping with

```<code>if (dicP_SO.contains(p)) {
   P_SO = dicP_SO.apply(p) :+ Vector(s, o) //To add to the same key the diff
   dicP_SO += (p -> P_SO)                  //(s,o)
}else dicP_SO += (p -> Vector(Vector(s,o)))
</code>```

in this way if I put as key the 38, and I run the following code:

```<code>dicP_SO.getOrElse(38,Vector(0))
</code>```

I get the following:

```<code>Vector(Vector(15, 3), Vector(22, 21), Vector(40, 39), Vector(45, 27))
</code>```

My quetion is the following: I need each vector[Int] that are inside, I try to declare a variable

```<code>val a:Vector[Int] = dicP_SO.getOrElse(yi,Vector(0))
</code>```

I am getting the error that a Vector[Any] does not conform to Vector[Int] and I don't know why is this error and how fix it

答:
Since dicP_SO.getOrElse(38,Vector(0)) return type is: Vector[Any], when you assign it to Vector[Int], the compiler throw this error.

You can do it by:

```<code>dicP_SO.get(38).map(_.flatten).getOrElse(Vector(0)) //flatten nest Vector[Vector[Int]] to Vector[Int], and `getOrElse`
</code>```

use flatten to flat a nest collection:

```<code>Vector(Vector(1)).flatten
> Vector(1)
</code>```

Body:
I am working with the following list in a text file:

10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48

I am creating some indexes to analysis the table, then if each column is (s,p,o) and I create a map that is P -> SO I create it of the form

val dicP_SO: scala.collection.mutable.Map[Int, Vector[Vector[Int]]] = collection.mutable.Map[Int, Vector[Vector[Int]]]()

I read the file, and create the mapping with

if (dicP_SO.contains(p)) {
   P_SO = dicP_SO.apply(p) :+ Vector(s, o) //To add to the same key the diff
   dicP_SO += (p -> P_SO)                  //(s,o)
}else dicP_SO += (p -> Vector(Vector(s,o)))

in this way if I put as key the 38, and I run the following code:

dicP_SO.getOrElse(38,Vector(0))

I get the following:

Vector(Vector(15, 3), Vector(22, 21), Vector(40, 39), Vector(45, 27))

My quetion is the following: I need each vector[Int] that are inside, I try to declare a variable

val a:Vector[Int] = dicP_SO.getOrElse(yi,Vector(0))

I am getting the error that a Vector[Any] does not conform to Vector[Int] and I don't know why is this error and how fix it

Body:
Since dicP_SO.getOrElse(38,Vector(0)) return type is: Vector[Any], when you assign it to Vector[Int], the compiler throw this error.

You can do it by:

dicP_SO.get(38).map(_.flatten).getOrElse(Vector(0)) //flatten nest Vector[Vector[Int]] to Vector[Int], and `getOrElse`

use flatten to flat a nest collection:

Vector(Vector(1)).flatten
> Vector(1)


问:
ANTLR4 Building in Visual Studio 2017 (C++)
I'm trying to build ANTLR4 in Visual Studio (C++).

These are the errors:
Error trying to build

The unresolved externals are virtual destructors.

Why it is implemented like that? Pure virtual destructors must have a function body. How can I fix it and build ANTLR4?

Thanks in advance

答: Seems you used the latest code from Github. There is a pull request with fixes for the recent changes in the C++ target. Just download and apply this patch to make the code compiling. Currently there is no VS 2017 solution in the repo, so if you like you can create a pull request for that.</p>


问:
Eval within if statement
How can I dynamically pass eq or ne inside perl if statement? I tried below but is not working:</p>

```<code>my $this="this";
my $that="that";
my $cond='ne';
if($this eval($cond) $that)
{
  print "$cond\n";
}
</code>```

答:
Whenever you are using eval for runtime code generation, it is best to keep in mind a few details.  First, eval is dangerous, so you should eval the smallest, most generic code you can, and check for errors.  Second, eval is slow, so you should store the result for later.

```<code>{my %cache;
sub compare {
    my ($x, $op, $y) = @_;
    $cache{$op} ||= eval "sub {\$_[0] $op \$_[1]}" || die "bad op: $op\n";
    $cache{$op}->($x, $y)
}}

my $this="this";
my $that="that";
my $cond='ne';

if (compare $this, $cond, $that) {
    print "$cond\n";
}
</code>```

Here the compare function will build a new coderef (with eval) when it sees an operator that it has not had yet.  The return value of the eval is checked, and an error is raised if anything when wrong.

This coderef (which expects its values as arguments) is stored in %cache.  Then the cached coderef is run with the two values as arguments.  This same coderef will be used over and over whenever the same operator is used.

Title: Eval within if statement

Body:
How can I dynamically pass eq or ne inside perl if statement? I tried below but is not working:

my $this="this";
my $that="that";
my $cond='ne';
if($this eval($cond) $that)
{
  print "$cond\n";
}

Body:
Whenever you are using eval for runtime code generation, it is best to keep in mind a few details.  First, eval is dangerous, so you should eval the smallest, most generic code you can, and check for errors.  Second, eval is slow, so you should store the result for later.

{my %cache;
sub compare {
    my ($x, $op, $y) = @_;
    $cache{$op} ||= eval "sub {\$_[0] $op \$_[1]}" || die "bad op: $op\n";
    $cache{$op}->($x, $y)
}}

my $this="this";
my $that="that";
my $cond='ne';

if (compare $this, $cond, $that) {
    print "$cond\n";
}

Here the compare function will build a new coderef (with eval) when it sees an operator that it has not had yet.  The return value of the eval is checked, and an error is raised if anything when wrong.

This coderef (which expects its values as arguments) is stored in %cache.  Then the cached coderef is run with the two values as arguments.  This same coderef will be used over and over whenever the same operator is used.