问:
get by id in mongoose
If I want to get by id a only subdocument that is an array into a document, how I need to call it? I have these models

```<code>/* Build */
var buildSchema = new Schema({
  buildName: String,
  package: [packageSchema],
  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
  }
})
var Build = mongoose.model('build', buildSchema)

/* Project */
var projectSchema = new Schema({
  projectName: String,
  build: [buildSchema],
  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
  }
})
var Project = mongoose.model('project', projectSchema)
</code>```

my get function and route is this:

```<code>router.get('/build/:id', function (req, res, next) {
  var token = helperJwt.decodeToken(req)
  jwt.verify(token, helperJwt.secret, function (error, decoded) {
    if (error) {
      res.status(401)
    } else {
      Project.findOne({ _id: req.params.id}, 'build', function (err, build) {
        if (err) {
          res.status(401)
        } else {
          build.findOne({build: build._id}, 'postedBy', 'email', function (err, getBuild) {
            if (err) {
              res.status(401)
            } else {
              return status(200).json(build)
            }
          })
        }
      })
    }
  })
})
</code>```

that is good or how can I do for get only one build?

I'm using vue as front end but it doesn't recognise only one build data.

I don't know how to findById a subdocument.

I want to bring something like:

```<code>{
    "_id" : ObjectId("5a26fbfd1866893baf14b175"),
    "postedBy" : "5a2021539f1d222bfc915fa2",
    "projectName" : "El pipiripau",
    "build" : [
        {
            "buildName" : "bdfbdgf",
            "postedBy" : ObjectId("5a2021539f1d222bfc915fa2"),
            "_id" : ObjectId("5a26fc0dbe4de0039cdae0c7"),
            "package" : []
        },
}
</code>```

答:
If you use buildSchema inside of projectSchema, the build array will contain subdocuments so they won’t have ids.

You could set a custom id field in your build schema and then reference that in your query, but you would have to take care of setting those ids when you save your project docs.

Alternatively, if your build docs are being stored in a separate collection (as you have a build model) then they will have an _id field and you could store an array of references to the build model in your projectSchema:

```<code>var projectSchema = new Schema({
  projectName: String,
  build: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'build'
  }],
  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
  }
})
</code>```

And then, assuming req.params.id is the id of a build doc, you could find projects where the build array has the id and then use populate to replace the array of build ids with the corresponding subdocuments:

```<code>Project
  .find({ build: req.params.id })
  .populate('build')
  .exec(function (err, projects) {
    if (err) {
      // Handle error
    } else {
      // For each project, filter builds for just the one matching the id param
      projects.forEach(project => {
        project.build = project.build.filter(item => item._id == req.params.id )
      })
      // Handle result
    }
  })
</code>```

Here are the docs on population:
http://mongoosejs.com/docs/populate.html

I hope this helps.

Title: get by id in mongoose

Body:
If I want to get by id a only subdocument that is an array into a document, how I need to call it? I have these models

/* Build */
var buildSchema = new Schema({
  buildName: String,
  package: [packageSchema],
  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
  }
})
var Build = mongoose.model('build', buildSchema)

/* Project */
var projectSchema = new Schema({
  projectName: String,
  build: [buildSchema],
  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
  }
})
var Project = mongoose.model('project', projectSchema)

my get function and route is this:

router.get('/build/:id', function (req, res, next) {
  var token = helperJwt.decodeToken(req)
  jwt.verify(token, helperJwt.secret, function (error, decoded) {
    if (error) {
      res.status(401)
    } else {
      Project.findOne({ _id: req.params.id}, 'build', function (err, build) {
        if (err) {
          res.status(401)
        } else {
          build.findOne({build: build._id}, 'postedBy', 'email', function (err, getBuild) {
            if (err) {
              res.status(401)
            } else {
              return status(200).json(build)
            }
          })
        }
      })
    }
  })
})

that is good or how can I do for get only one build?

I'm using vue as front end but it doesn't recognise only one build data.

I don't know how to findById a subdocument.

I want to bring something like:

{
    "_id" : ObjectId("5a26fbfd1866893baf14b175"),
    "postedBy" : "5a2021539f1d222bfc915fa2",
    "projectName" : "El pipiripau",
    "build" : [
        {
            "buildName" : "bdfbdgf",
            "postedBy" : ObjectId("5a2021539f1d222bfc915fa2"),
            "_id" : ObjectId("5a26fc0dbe4de0039cdae0c7"),
            "package" : []
        },
}

Body:
If you use buildSchema inside of projectSchema, the build array will contain subdocuments so they won’t have ids.

You could set a custom id field in your build schema and then reference that in your query, but you would have to take care of setting those ids when you save your project docs.

Alternatively, if your build docs are being stored in a separate collection (as you have a build model) then they will have an _id field and you could store an array of references to the build model in your projectSchema:

var projectSchema = new Schema({
  projectName: String,
  build: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'build'
  }],
  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
  }
})

And then, assuming req.params.id is the id of a build doc, you could find projects where the build array has the id and then use populate to replace the array of build ids with the corresponding subdocuments:

Project
  .find({ build: req.params.id })
  .populate('build')
  .exec(function (err, projects) {
    if (err) {
      // Handle error
    } else {
      // For each project, filter builds for just the one matching the id param
      projects.forEach(project => {
        project.build = project.build.filter(item => item._id == req.params.id )
      })
      // Handle result
    }
  })

Here are the docs on population:
http://mongoosejs.com/docs/populate.html

I hope this helps.


来源: stackexchange

问:
Configure CMakeLists.txt for locally installed Protocol Buffers
I downloaded the Protocol Buffers source from GitHub. I don't want to install it globally and just want to use it in my ROS package. I found cmake files here but not sure how to use them in my project.

Below is the content of my CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 2.8.3)
project(local_protobuf_ros_example)

find_package(catkin REQUIRED COMPONENTS roscpp)
find_package(Protobuf REQUIRED)

catkin_package()
include_directories(include ${catkin_INCLUDE_DIRS} ${PROTOBUF_INCLUDE_DIRS})

add_library(addressbook_protobuf include/addressbook.pb.cc)

add_executable(main src/main.cpp)
target_link_libraries(main ${catkin_LIBRARIES} addressbook_protobuf ${PROTOBUF_LIBRARIES})
</code>```

Below is the file structure of ROS Package:

```<code>├── CMakeLists.txt
├── include
│   ├── addressbook.pb.cc
│   ├── addressbook.pb.h
│   └── addressbook.proto
├── lib
│   ├── protobuf-3.5.0
│   │   ├── cmake
│   │   │   ├── CMakeLists.txt
│   │   │   ├── examples.cmake
│   │   │   ├── extract_includes.bat.in
│   │   │   ├── install.cmake
│   │   │   ├── libprotobuf.cmake
│   │   │   ├── libprotobuf-lite.cmake
│   │   │   ├── libprotoc.cmake
│   │   │   ├── protobuf-config.cmake.in
│   │   │   ├── protobuf-config-version.cmake.in
│   │   │   ├── protobuf-lite.pc.cmake
│   │   │   ├── protobuf-module.cmake.in
│   │   │   ├── protobuf-options.cmake
│   │   │   ├── protobuf.pc.cmake
│   │   │   ├── protoc.cmake
│   │   │   ├── README.md
│   │   │   └── tests.cmake
│   │   ├──SOME_FILES_ARE_NOT_BEING_SHOWN_HERE
│   └── protobuf-cpp-3.5.0.zip
├── package.xml
└── src
    └── main.cpp
</code>```

I want to know that how to configure above CMakeLists.txt so that it uses locally installed Protocol Buffers?

答:
You can set CMAKE_MODULE_PATH when you configure your build directory to specify a custom location to search for packages. You are not required to modify your CMakeLists.txt, configure your build for example like this:

```<code>cmake -DCMAKE_MODULE_PATH=/path/to/protobuf/cmake/config /path/to/source
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I downloaded the Protocol Buffers source from GitHub. I don't want to install it globally and just want to use it in my ROS package. I found cmake files here but not sure how to use them in my project.

Below is the content of my CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.3)
project(local_protobuf_ros_example)

find_package(catkin REQUIRED COMPONENTS roscpp)
find_package(Protobuf REQUIRED)

catkin_package()
include_directories(include ${catkin_INCLUDE_DIRS} ${PROTOBUF_INCLUDE_DIRS})

add_library(addressbook_protobuf include/addressbook.pb.cc)

add_executable(main src/main.cpp)
target_link_libraries(main ${catkin_LIBRARIES} addressbook_protobuf ${PROTOBUF_LIBRARIES})

Below is the file structure of ROS Package:

├── CMakeLists.txt
├── include
│   ├── addressbook.pb.cc
│   ├── addressbook.pb.h
│   └── addressbook.proto
├── lib
│   ├── protobuf-3.5.0
│   │   ├── cmake
│   │   │   ├── CMakeLists.txt
│   │   │   ├── examples.cmake
│   │   │   ├── extract_includes.bat.in
│   │   │   ├── install.cmake
│   │   │   ├── libprotobuf.cmake
│   │   │   ├── libprotobuf-lite.cmake
│   │   │   ├── libprotoc.cmake
│   │   │   ├── protobuf-config.cmake.in
│   │   │   ├── protobuf-config-version.cmake.in
│   │   │   ├── protobuf-lite.pc.cmake
│   │   │   ├── protobuf-module.cmake.in
│   │   │   ├── protobuf-options.cmake
│   │   │   ├── protobuf.pc.cmake
│   │   │   ├── protoc.cmake
│   │   │   ├── README.md
│   │   │   └── tests.cmake
│   │   ├──SOME_FILES_ARE_NOT_BEING_SHOWN_HERE
│   └── protobuf-cpp-3.5.0.zip
├── package.xml
└── src
    └── main.cpp

I want to know that how to configure above CMakeLists.txt so that it uses locally installed Protocol Buffers?

Body:
You can set CMAKE_MODULE_PATH when you configure your build directory to specify a custom location to search for packages. You are not required to modify your CMakeLists.txt, configure your build for example like this:

cmake -DCMAKE_MODULE_PATH=/path/to/protobuf/cmake/config /path/to/source


问:
R.java disappears after project clean
After I added some .png files into my Project Workspace drawable folder I refreshed my drawable folders in Eclipse and the newly added files showed up. But when I tried to access those resources using R.drawable.xyzimage, xyzimage although in the folder could not be resolved.

So I did a Project Clean and guess what after this clean R.java is totally gone and all my classes accessing resources using R.java is showing all sorts of error and Eclipse won't let me run the code anymore.

I have backup of my source code but I want to explore if R.java can be regenerated and how?

Thanks for all the help.

答: I had an invalid jpg in my res/drawable folder. I removed the jpg and it worked.</p>

ContentLicense: CC BY-SA 2.5

Title: R.java disappears after project clean


问:
PHP Query won't work with DELETE
I have connection, and I wan't delete one record by choosing ID (option have value of row ID in db)

```<code><form class="form">
      <?php
      require "connect.php";
      $select = $_POST['del_zaint'];
      if(isset($_POST['Del'])){
        $$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
        mysqli_query($db, $que);
      }
      mysqli_close($db);
      ?>

      <span class="main-page__info">Usuń rekord zainteresowań.</span>
      <select name="del_zaint">
        <option disabled selected>Wybierz rekord do usunięcia</option>
        <?php
        require "connect.php";
        $que = "SELECT * from zainteresowania";
        $wynik = mysqli_query($db, $que);
        while($row = mysqli_fetch_array($wynik)){
          echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
        }
        mysqli_close($db);
        ?>
      </select>
      <input name="Del" type="submit" value="Usuń">
    </form>
</code>```

Nothing is done by this :/ I choose option and after clicking submit with name = Del, it won't work, just reset to normal position. (Adding informations to db and showing from it works well)

答:
Try This

You miss the method in the form tag.
Also, I Change the SQL query

```<code>$que = "DELETE FROM `zainteresowania` WHERE id = '".$select."'";
</code>```

Below code is working on my system. You have to use the SQL injection for secure

```<code>$db->real_escape_string($_POST['del_zaint'])
</code>```

instated of delete the record, Make a column like status in the database and change the status 0 or 1.

You can refer the site for deleting the record

https://www.w3schools.com/php/php_mysql_delete.asp

```<code> <?php
include('db/connection.php');
      if(isset($_POST['Del'])){

        echo $select = $db->real_escape_string($_POST['del_zaint']);
        $que = "DELETE FROM `zainteresowania` WHERE id = '".$select."'";
            if (mysqli_query($db, $que)) {
                  echo "Record deleted successfully";
            } else {
                echo "Error deleting record: " . mysqli_error($db);
            }
      mysqli_close($db);
  }
      ?>

<form class="form" method="POST" action="#">
      <span class="main-page__info">Usuń rekord zainteresowań.</span>

      <select name="del_zaint">
        <option disabled selected>Wybierz rekord do usunięcia</option>
        <?php
        $que = "SELECT * from zainteresowania";
        $wynik = mysqli_query($db, $que);

        while($row = mysqli_fetch_array($wynik)){
          echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
        }
        mysqli_close($db);
        ?>
      </select>
      <input name="Del" type="submit" value="Usuń">
    </form>
</code>```

Title: PHP Query won't work with DELETE

Body:
I have connection, and I wan't delete one record by choosing ID (option have value of row ID in db)

<form class="form">
      <?php
      require "connect.php";
      $select = $_POST['del_zaint'];
      if(isset($_POST['Del'])){
        $$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
        mysqli_query($db, $que);
      }
      mysqli_close($db);
      ?>

      Usuń rekord zainteresowań.
      <select name="del_zaint">
        <option disabled selected>Wybierz rekord do usunięcia</option>
        <?php
        require "connect.php";
        $que = "SELECT * from zainteresowania";
        $wynik = mysqli_query($db, $que);
        while($row = mysqli_fetch_array($wynik)){
          echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
        }
        mysqli_close($db);
        ?>
      </select>
      <input name="Del" type="submit" value="Usuń">
    </form>

Nothing is done by this :/ I choose option and after clicking submit with name = Del, it won't work, just reset to normal position. (Adding informations to db and showing from it works well)

Body:
Try This

You miss the method in the form tag.
Also, I Change the SQL query

$que = "DELETE FROM `zainteresowania` WHERE id = '".$select."'";

Below code is working on my system. You have to use the SQL injection for secure

$db->real_escape_string($_POST['del_zaint'])

instated of delete the record, Make a column like status in the database and change the status 0 or 1.

You can refer the site for deleting the record

https://www.w3schools.com/php/php_mysql_delete.asp

 <?php
include('db/connection.php');
      if(isset($_POST['Del'])){

        echo $select = $db->real_escape_string($_POST['del_zaint']);
        $que = "DELETE FROM `zainteresowania` WHERE id = '".$select."'";
            if (mysqli_query($db, $que)) {
                  echo "Record deleted successfully";
            } else {
                echo "Error deleting record: " . mysqli_error($db);
            }
      mysqli_close($db);
  }
      ?>

<form class="form" method="POST" action="#">
      <span class="main-page__info">Usuń rekord zainteresowań.</span>

      <select name="del_zaint">
        <option disabled selected>Wybierz rekord do usunięcia</option>
        <?php
        $que = "SELECT * from zainteresowania";
        $wynik = mysqli_query($db, $que);

        while($row = mysqli_fetch_array($wynik)){
          echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
        }
        mysqli_close($db);
        ?>
      </select>
      <input name="Del" type="submit" value="Usuń">
    </form>


问:
Clear table before reloding the data in a table
I am trying to bind data from the database. what is happening is that it binds every 5 seconds. Now its binding properly but it does not clear the earlier data. it keeps pilling up. So if there is 3 rows .. it needs to show only 3 rows. now what is happening is it is adding 3 rows every 5 seconds and keeps pilling 6-9-12 every 5 seconds.
I need to clear the data and then load every 5 seconds.</p>

```<code><script type="text/javascript">
        $(document).ready(function () {
            Get();
            setInterval(function () {
                Get() // this will run after every 5 seconds
            }, 5000);
        });

    function Get() {
        $.ajax({
            type: "POST",
            url: "../adminpage/noti.ashx",
            data: {},
            dataType: "json",
            success: function (response) {
                $.each(response, function (index, itemData) {
                    var tr = "<tr>" +
                                  "<td>" + itemData.msg + "</td>" +
                                  "<td>" + itemData.dt + "</td>" +
                                  "</tr>";

                    $("#testTable").find("tbody").append(tr);
                });

                BindTable();
            }
        });
    }
    function BindTable() {

        try {
            $('#testTable thead th').each(function (i) {
                var title = $('#testTable thead th').eq($(this).index()).text();

                if (title != "") {
                    $(this).html('<div style="width:40%;text-align:center;white-space:nowrap">' + title + '</div>');
                }
            });

        }
        catch (e) { }
    }
</script>

<table id="testTable" class="display" cellspacing="0" width="100%">
                                        <thead>
                                            <tr>
                                                <th class="m-list-timeline__text" style="width:70%">msg</th>
                                                <th class="m-list-timeline__time" style="width:30%">dt</th>
                                            </tr>
                                        </thead>
                                          <tbody></tbody>
                                    </table>
</code>```

答:
```<code><script type="text/javascript">
      $(document).ready(function () {
          Get();
           setInterval(function () {
            Get() // this will run after every 5 seconds
            }, 5000);
       });

function Get() {
    $.ajax({
        type: "POST",
        url: "../adminpage/noti.ashx",
        data: {},
        dataType: "json",
        success: function (response) {

              // Check if response data is not empty
            if (response) {
              // Empty previous data

                 $("#testTable").empty();
              // Iterate data for each row

                 $.each(response, function (index, itemData) {
                 var tr = "<tr>" +
                              "<td>" + itemData.msg + "</td>" +
                              "<td>" + itemData.dt + "</td>" +
                              "</tr>";

                $("#testTable").find("tbody").append(tr);
            });

            BindTable();
        }
       }
    });
}
</code>```

Body:
I am trying to bind data from the database. what is happening is that it binds every 5 seconds. Now its binding properly but it does not clear the earlier data. it keeps pilling up. So if there is 3 rows .. it needs to show only 3 rows. now what is happening is it is adding 3 rows every 5 seconds and keeps pilling 6-9-12 every 5 seconds.
I need to clear the data and then load every 5 seconds.

                                                msg
                                                dt


问:
PUT inventory custom fragment
This is my device inventory with the custom tasks array:

```<code>{
    ...
    "c8y_IsDevice": {},
    "tasks": [
        {
            "task_status" : "NEW",
            "task_id" : "1",
            "task_data" : {
                ...
            }
        },
        {
            "task_status" : "DONE",
            "task_id" : "2",
            "task_data" : {
                ...
            }
        },
            ...
    ]
    ...
}
</code>```

I want to create a MQTT/SMARTREST PUT template to update a task by id and status.

For example: 800,[task_id],[task_status]

I am not able to find a way for this, especially it's an json array and all my attempts end up in overwriting the complete json array.
Maybe there's sth. like a condition, if task_id = x -> set task_status = y

Thank you.

答: You can only replace the whole fragment. There is no way to partially modify fragments.</p>

Title: PUT inventory custom fragment

Body:
This is my device inventory with the custom tasks array:

{
    ...
    "c8y_IsDevice": {},
    "tasks": [
        {
            "task_status" : "NEW",
            "task_id" : "1",
            "task_data" : {
                ...
            }
        },
        {
            "task_status" : "DONE",
            "task_id" : "2",
            "task_data" : {
                ...
            }
        },
            ...
    ]
    ...
}

I want to create a MQTT/SMARTREST PUT template to update a task by id and status.

For example: 800,[task_id],[task_status]

I am not able to find a way for this, especially it's an json array and all my attempts end up in overwriting the complete json array.
Maybe there's sth. like a condition, if task_id = x -> set task_status = y

Thank you.


问:
Widget clickable only for the first time
I'm developing an application with widget. And when I click on the widget for the first time it works (start an activity), but It does not start the activity after turning the screen off and on. Below is the code for my widget:

WidgetProvider

```<code>@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    EmailApp.getAppComponent().inject(this);
    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
        //updateAppWidgetCompose(context, appWidgetManager, appWidgetId);
    }

    final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    final Intent i = new Intent(context, WidgetIntentService.class);

    if (service == null) {
        service = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    }
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 120000, service);
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

private void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                             int appWidgetId) {
    Intent intent = null;
    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.sample_widget);
    // Construct an Intent object includes web adresss.
    if(mPrefs.getUsername() != "")
        intent = new Intent(context, HomeActivity.class);
    else
        intent = new Intent(context, MainActivity.class);
    // In widget we are not allowing to use intents as usually. We have to use PendingIntent instead of 'startActivity'
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Here the basic operations the remote view can do.
    views.setOnClickPendingIntent(R.id.mainWidgetLayout, pendingIntent);
    //views.setTextViewText(R.id.widget_folder, context.getText(R.string.boite_reception_label));
    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}
</code>```

sample_widget

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/mainWidgetLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:layout_marginTop="@dimen/widget_margin_top"
android:layout_marginLeft="@dimen/widget_margin_left"
android:layout_marginRight="@dimen/widget_margin_right"
android:layout_marginBottom="@dimen/widget_margin_bottom">

<LinearLayout
    android:id="@+id/widget_header"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="@color/colorPrimary"
    style="@style/WidgetHeaderStartMargin">
    <TextView
        android:id="@+id/widget_folder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:freezesText="true"
        android:text="@string/widget_title"
        android:includeFontPadding="false"
        style="@style/WidgetTitle"/>

</LinearLayout>

<LinearLayout
    android:id="@+id/widget_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="15dp"
    android:visibility="gone"
    android:background="@drawable/gradient_bg_widget_holo"
    android:gravity="center_vertical">

    <ImageView
        android:id="@+id/numberImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        app:srcCompat="@drawable/apk"/>

    <TextView
        android:id="@+id/textMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:text="@string/no_new_message" />

</LinearLayout>
<LinearLayout
    android:id="@+id/widget_not_connected"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:orientation="vertical"
    android:padding="15dp"
    android:visibility="gone"
    android:background="@drawable/gradient_bg_widget_holo"
    android:gravity="center_vertical|center_horizontal">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/icon_deconnected"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:text="@string/device_not_connected" />

</LinearLayout>

<TextView
    android:id="@+id/no_msg"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textStyle="bold"
    android:gravity="center"
    android:textColor="@android:color/black"
    android:background="@drawable/gradient_bg_widget_holo"
    android:text="@string/no_new_message"/>
</code>```

AndroidManifest

```<code><receiver android:name=".widget.MailWidgetProvider">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />

        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/widget_provider" />
    </receiver>
</code>```

I want to understand where I'm wrong in the code or what I need to add in my code. Every bit of help is welcomed.

EDIT

I call IntentService in AlarmManager to get data to update the widget. this is the content of my IntentService

```<code>public class WidgetIntentService extends IntentService {
private String user, pass;

@Inject
PreferenceManager mPrefs;

public WidgetIntentService() {
    super(WidgetIntentService.class.getName());

}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    int count = 0;
    user = mPrefs.getUsername();
    pass = mPrefs.getPassword();

    if(InternetStateMonitor.isConnected()) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.sample_widget);
        remoteViews.setViewVisibility(R.id.widget_not_connected, View.GONE);

        if(user!="" && pass!="") {
            try {
                count = server.getCount(user, pass);
                Log.w("COUNT WIDGET",""+count);
            } catch (Exception e) {
                e.printStackTrace();
            }
            TextDrawable mDrawable = TextDrawable.builder()
                    .buildRound(""+count, Color.RED);

            if(count == 0) {
                remoteViews.setViewVisibility(R.id.widget_layout, View.GONE);
                remoteViews.setViewVisibility(R.id.no_msg, View.VISIBLE);
                //remoteViews.setTextViewText(R.id.no_msg, this.getText(R.string.no_new_message));
            } else if(count == 1) {
                remoteViews.setViewVisibility(R.id.no_msg, View.GONE);
                remoteViews.setViewVisibility(R.id.widget_layout, View.VISIBLE);
                remoteViews.setImageViewBitmap(R.id.numberImg, DrawableUtils.drawableToBitmap(mDrawable));
                remoteViews.setTextViewText(R.id.textMsg, this.getText(R.string.new_message_single));
            } else {
                remoteViews.setViewVisibility(R.id.no_msg, View.GONE);
                remoteViews.setViewVisibility(R.id.widget_layout, View.VISIBLE);

                remoteViews.setImageViewBitmap(R.id.numberImg, DrawableUtils.drawableToBitmap(mDrawable));
                remoteViews.setTextViewText(R.id.textMsg, this.getText(R.string.new_message_more));
            }
            ComponentName theWidget = new ComponentName(this, MailWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(theWidget, remoteViews);
        } else {
            remoteViews.setViewVisibility(R.id.no_msg, View.VISIBLE);
            remoteViews.setTextViewText(R.id.no_msg, this.getText(R.string.tap_here));

            ComponentName theWidget = new ComponentName(this, MailWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(theWidget, remoteViews);
        }

    } else {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.sample_widget);
        remoteViews.setViewVisibility(R.id.widget_layout, View.GONE);
        remoteViews.setViewVisibility(R.id.no_msg, View.GONE);
        remoteViews.setViewVisibility(R.id.widget_not_connected, View.VISIBLE);

        ComponentName theWidget = new ComponentName(this, MailWidgetProvider.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(this);
        manager.updateAppWidget(theWidget, remoteViews);
    }

}
</code>```

}

Is this code change something in widget or no?

答:
You can use AppWidgetProvider's receiver method for starting your activity. On every click action, you have to simple broadcast an action message and receiver will handle rest of it.
Below, I am sharing the snippet I used to solve a similar issue,

Declare a constant String for broadcast action, In my case, I was using add broadcast to start an activity.

```<code>public static final String ACTION_ADD = "com.myapplication.action.ADD";
</code>```

In your 'updateAppWidget' method use this to get a pending intent:

```<code>views.setOnClickPendingIntent(R.id.mainWidgetLayout, getPendingSelfIntent(context, ACTION_ADD, appWidgetId));
</code>```

Here is the helper method:

```<code>private static PendingIntent getPendingSelfIntent(Context context, String action, int widgetId) {
    Intent intent = new Intent(context, MailWidgetProvider.class);
    intent.setAction(action);
    intent.putExtra("widget_id", widgetId);
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
</code>```

And this is how your AppWidgetProvider's receiver looks like:

```<code>@Override
public void onReceive(Context context, Intent intent) {
    if (ACTION_ADD.equals(intent.getAction())) {
        int appWidgetId = intent.getIntExtra("widget_id", 0);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String content = preferences.getString(String.valueOf(appWidgetId),"0");
        Intent expenseIntent;
        if(preferences.getUsername() != "") {
            expenseIntent = new Intent(context, HomeActivity.class);
        }
        else {
            expenseIntent = new Intent(context, MainActivity.class);
        }
        expenseIntent.putExtra("widget_data", content);
        expenseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(expenseIntent);
    } else {
        super.onReceive(context, intent);
    }
}
</code>```

Body:
I'm developing an application with widget. And when I click on the widget for the first time it works (start an activity), but It does not start the activity after turning the screen off and on. Below is the code for my widget:

WidgetProvider

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    EmailApp.getAppComponent().inject(this);
    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
        //updateAppWidgetCompose(context, appWidgetManager, appWidgetId);
    }

    final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    final Intent i = new Intent(context, WidgetIntentService.class);

    if (service == null) {
        service = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    }
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 120000, service);
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

private void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                             int appWidgetId) {
    Intent intent = null;
    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.sample_widget);
    // Construct an Intent object includes web adresss.
    if(mPrefs.getUsername() != "")
        intent = new Intent(context, HomeActivity.class);
    else
        intent = new Intent(context, MainActivity.class);
    // In widget we are not allowing to use intents as usually. We have to use PendingIntent instead of 'startActivity'
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Here the basic operations the remote view can do.
    views.setOnClickPendingIntent(R.id.mainWidgetLayout, pendingIntent);
    //views.setTextViewText(R.id.widget_folder, context.getText(R.string.boite_reception_label));
    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

sample_widget

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/mainWidgetLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:layout_marginTop="@dimen/widget_margin_top"
android:layout_marginLeft="@dimen/widget_margin_left"
android:layout_marginRight="@dimen/widget_margin_right"
android:layout_marginBottom="@dimen/widget_margin_bottom">

<LinearLayout
    android:id="@+id/widget_header"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="@color/colorPrimary"
    style="@style/WidgetHeaderStartMargin">
    <TextView
        android:id="@+id/widget_folder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:freezesText="true"
        android:text="@string/widget_title"
        android:includeFontPadding="false"
        style="@style/WidgetTitle"/>

</LinearLayout>

<LinearLayout
    android:id="@+id/widget_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="15dp"
    android:visibility="gone"
    android:background="@drawable/gradient_bg_widget_holo"
    android:gravity="center_vertical">

    <ImageView
        android:id="@+id/numberImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        app:srcCompat="@drawable/apk"/>

    <TextView
        android:id="@+id/textMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:text="@string/no_new_message" />

</LinearLayout>
<LinearLayout
    android:id="@+id/widget_not_connected"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:orientation="vertical"
    android:padding="15dp"
    android:visibility="gone"
    android:background="@drawable/gradient_bg_widget_holo"
    android:gravity="center_vertical|center_horizontal">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/icon_deconnected"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:text="@string/device_not_connected" />

</LinearLayout>

<TextView
    android:id="@+id/no_msg"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textStyle="bold"
    android:gravity="center"
    android:textColor="@android:color/black"
    android:background="@drawable/gradient_bg_widget_holo"
    android:text="@string/no_new_message"/>

AndroidManifest

<receiver android:name=".widget.MailWidgetProvider">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />

        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/widget_provider" />
    </receiver>

I want to understand where I'm wrong in the code or what I need to add in my code. Every bit of help is welcomed.

EDIT

I call IntentService in AlarmManager to get data to update the widget. this is the content of my IntentService

public class WidgetIntentService extends IntentService {
private String user, pass;

@Inject
PreferenceManager mPrefs;

public WidgetIntentService() {
    super(WidgetIntentService.class.getName());

}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    int count = 0;
    user = mPrefs.getUsername();
    pass = mPrefs.getPassword();

    if(InternetStateMonitor.isConnected()) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.sample_widget);
        remoteViews.setViewVisibility(R.id.widget_not_connected, View.GONE);

        if(user!="" && pass!="") {
            try {
                count = server.getCount(user, pass);
                Log.w("COUNT WIDGET",""+count);
            } catch (Exception e) {
                e.printStackTrace();
            }
            TextDrawable mDrawable = TextDrawable.builder()
                    .buildRound(""+count, Color.RED);

            if(count == 0) {
                remoteViews.setViewVisibility(R.id.widget_layout, View.GONE);
                remoteViews.setViewVisibility(R.id.no_msg, View.VISIBLE);
                //remoteViews.setTextViewText(R.id.no_msg, this.getText(R.string.no_new_message));
            } else if(count == 1) {
                remoteViews.setViewVisibility(R.id.no_msg, View.GONE);
                remoteViews.setViewVisibility(R.id.widget_layout, View.VISIBLE);
                remoteViews.setImageViewBitmap(R.id.numberImg, DrawableUtils.drawableToBitmap(mDrawable));
                remoteViews.setTextViewText(R.id.textMsg, this.getText(R.string.new_message_single));
            } else {
                remoteViews.setViewVisibility(R.id.no_msg, View.GONE);
                remoteViews.setViewVisibility(R.id.widget_layout, View.VISIBLE);

                remoteViews.setImageViewBitmap(R.id.numberImg, DrawableUtils.drawableToBitmap(mDrawable));
                remoteViews.setTextViewText(R.id.textMsg, this.getText(R.string.new_message_more));
            }
            ComponentName theWidget = new ComponentName(this, MailWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(theWidget, remoteViews);
        } else {
            remoteViews.setViewVisibility(R.id.no_msg, View.VISIBLE);
            remoteViews.setTextViewText(R.id.no_msg, this.getText(R.string.tap_here));

            ComponentName theWidget = new ComponentName(this, MailWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(theWidget, remoteViews);
        }

    } else {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.sample_widget);
        remoteViews.setViewVisibility(R.id.widget_layout, View.GONE);
        remoteViews.setViewVisibility(R.id.no_msg, View.GONE);
        remoteViews.setViewVisibility(R.id.widget_not_connected, View.VISIBLE);

        ComponentName theWidget = new ComponentName(this, MailWidgetProvider.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(this);
        manager.updateAppWidget(theWidget, remoteViews);
    }

}

}

Is this code change something in widget or no?

Body:
You can use AppWidgetProvider's receiver method for starting your activity. On every click action, you have to simple broadcast an action message and receiver will handle rest of it.
Below, I am sharing the snippet I used to solve a similar issue,

Declare a constant String for broadcast action, In my case, I was using add broadcast to start an activity.

public static final String ACTION_ADD = "com.myapplication.action.ADD";

In your 'updateAppWidget' method use this to get a pending intent:

views.setOnClickPendingIntent(R.id.mainWidgetLayout, getPendingSelfIntent(context, ACTION_ADD, appWidgetId));

Here is the helper method:

private static PendingIntent getPendingSelfIntent(Context context, String action, int widgetId) {
    Intent intent = new Intent(context, MailWidgetProvider.class);
    intent.setAction(action);
    intent.putExtra("widget_id", widgetId);
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

And this is how your AppWidgetProvider's receiver looks like:

@Override
public void onReceive(Context context, Intent intent) {
    if (ACTION_ADD.equals(intent.getAction())) {
        int appWidgetId = intent.getIntExtra("widget_id", 0);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String content = preferences.getString(String.valueOf(appWidgetId),"0");
        Intent expenseIntent;
        if(preferences.getUsername() != "") {
            expenseIntent = new Intent(context, HomeActivity.class);
        }
        else {
            expenseIntent = new Intent(context, MainActivity.class);
        }
        expenseIntent.putExtra("widget_data", content);
        expenseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(expenseIntent);
    } else {
        super.onReceive(context, intent);
    }
}


问:
CMake install destination bin equivalent for Windows
On Linux I configured CMake to install output in the bin folder.

Then I can call the executable in a terminal whatever the current directory is.

I did:

```<code>Install(TARGETS ... DESTINATION bin)
</code>```

On Windows, it doesn't work. It's telling me:

'whatever' is not recognized as an internal or external command,
  operable program or batch file.

What would be the equivalent destination for Windows?

答:
Unlike Linux, Windows has no common directory for installing runnable files into it.

If your project contains runnable files, you may place them anywhere under the project's installation prefix (which in turn looks like C:/Program Files/<Package name>): you may place runnable files directly under installation prefix or into bin/ subdirectory or whatever else.

For making a file runnable just by name, you need to add a directory with the file to PATH environment variable.

I am unsure whether CMake has support for automatically modifying the PATH variable on plain installing of a CMake project.

However, when packaging your project with CPack, some generators allows you to create a project's installer with automatic PATH updating. E.g. for the NSIS generator, see the CPACK_NSIS_MODIFY_PATH and CPACK_NSIS_EXECUTABLES_DIRECTORY variables.

ContentLicense: CC BY-SA 4.0

Body:
On Linux I configured CMake to install output in the bin folder.

Then I can call the executable in a terminal whatever the current directory is.

I did:

Install(TARGETS ... DESTINATION bin)

On Windows, it doesn't work. It's telling me:

'whatever' is not recognized as an internal or external command,
  operable program or batch file.

What would be the equivalent destination for Windows?


问:
Can any one explain me how does the string and number comparison work in javascript?
I have compared some strings and numbers to see the result as true and false

```<code>"dfdf" > 1
false
"dfdf" > 99
false
"dfdf" > 9999
false
"dfdf" > 99999
false
1> ''
true
1> '545'
false
1> '545d'
false
1> '555'
false
1> 'ddfdf'
false
9999 > 'dfsdfadf'
false
</code>```

I have tried few different combinations in the code as you can see but got the mixed result and want to know how exactly the comparison works in javascript.

another addition which is even more confusing

```<code>"dasfads" > "dasfdsf"
false
"abc" > "a"
true
"abc" > "agf"
false
"abcf" > "agf"
false
</code>```

答:
Comparing a string to a number will force the string data to evaluate into a number value. If the string data is not convertible to a numerical value it will return a NaN number to the given comparison.

Since NaN is not comparable nor equal to anything at all, not even to another NaN

NaN == NaN > false

The 'greater than' or 'smaller than' NaN comparison will have to return false both ways. Because that's the only correct answer, nothing can be greater nor smaller than the value you don't have. Therefore both claims are false. e.g.: 0 > NaN and 0 < NaN > false.

But keep in mind that comparing two strings of data such as:
"98A" > "999" will return a comparative false,
whereas:
"9A" > "999" will return true

Which is a very powerful thing to know, because knowing this (two strings will be compared by alphabetical order of magnitude) you are able to compare time data without taking the burden of converting those values to numbers and directly go with:

"09:32:28" > "09:31:59" > true

And luckily "PM" > "AM" > true by pure (linguistic) chance.

Body:
I have compared some strings and numbers to see the result as true and false

"dfdf" > 1
false
"dfdf" > 99
false
"dfdf" > 9999
false
"dfdf" > 99999
false
1> ''
true
1> '545'
false
1> '545d'
false
1> '555'
false
1> 'ddfdf'
false
9999 > 'dfsdfadf'
false

I have tried few different combinations in the code as you can see but got the mixed result and want to know how exactly the comparison works in javascript.

another addition which is even more confusing

"dasfads" > "dasfdsf"
false
"abc" > "a"
true
"abc" > "agf"
false
"abcf" > "agf"
false


问:
Consumer/producer locking GUI thread
I made a sample Consumer/Producer thread application, so I can learn how to properly use it.

I want it to allow for one thread to send commands to the GUI thread, to update the GUI with content.

I have it working, but there's one small issue. The GUI thread is my consumer thread, so I have it always checking for new commands (using a while loop). The issue is that because of this while loop, the GUI never displays because it's always stuck in the while loop. Note that the string Queue will eventually be replaced with a more complex object (one that holds data & command type).

I'm not sure how else to allow the GUI thread to consume commands without interrupting GUI functionality. Am I doing something wrong?

Here's my Form1.cs code (the form only contains 1 RichTextBox for showing output called OutputBox).

```<code>using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace MultiThreading
{
   class ThreadCommandQueue
   {
      public static ThreadCommandQueue instance = new ThreadCommandQueue();

      private Queue<string> m_queue;
      private Object m_lock;

      public static ThreadCommandQueue GetInstance()
      {
         return instance;
      }

      private ThreadCommandQueue()
      {
         m_queue = new Queue<string>();
         m_lock = new Object();
      }

      public void Add(
         string data_to_add)
      {
         lock (m_lock)
         {
            m_queue.Enqueue(data_to_add);
         }
      }

      public string Get()
      {
         lock (m_lock)
         {
            if (m_queue.Count > 0)
            {
               return m_queue.Dequeue();
            }

            return null;
         }
      }
   }

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

      private void PopulateThreadCommandQueue()
      {
         int i = 0;
         while(true)
         {
            ThreadCommandQueue.GetInstance().Add("Item #: " + i.ToString());
            i++;
         }
      }

      private void Form1_Load(object sender, EventArgs e)
      {
         // Create the Command Queue....
         ThreadCommandQueue.GetInstance();

         // Create a Testing Producer Thread
         Thread ProducerThread = new Thread(PopulateThreadCommandQueue);
         ProducerThread.Start();

         // The GUI thread is the Consumer, so keep checking the CommandQueue for data...
         while(true)
         {
            string latest = ThreadCommandQueue.GetInstance().Get();
            if(latest != null)
            {
               OutputBox.Text += latest + "\n";
            }
         }
      }
   }
}
</code>```

答:
Okay, the problem here is that you need to poll the message loop all the time to make GUI working and you also need to poll your IPC command queue all the time to make your commands working and you need this polling to happen at the same time on the same thread.

There are multiple ways to resolve this, but the easiest would be to process the message loop and when there is nothing to process, do your IPC command queue processing. For WinForms application this would be something like:

```<code>public Form1()
{
   InitializeComponent();
   Application.Idle += (sender, eargs) => ProcessCommands();
}

private void ProcessCommands()
{
    while(true)
    {
      string latest = ThreadCommandQueue.GetInstance().Get();
      if(string.IsNullOrEmpty(latest)) return;
      OutputBox.Text += latest + "\n";
    }
}
</code>```

Title: Consumer/producer locking GUI thread

Body:
I made a sample Consumer/Producer thread application, so I can learn how to properly use it.

I want it to allow for one thread to send commands to the GUI thread, to update the GUI with content.

I have it working, but there's one small issue. The GUI thread is my consumer thread, so I have it always checking for new commands (using a while loop). The issue is that because of this while loop, the GUI never displays because it's always stuck in the while loop. Note that the string Queue will eventually be replaced with a more complex object (one that holds data & command type).

I'm not sure how else to allow the GUI thread to consume commands without interrupting GUI functionality. Am I doing something wrong?

Here's my Form1.cs code (the form only contains 1 RichTextBox for showing output called OutputBox).

using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace MultiThreading
{
   class ThreadCommandQueue
   {
      public static ThreadCommandQueue instance = new ThreadCommandQueue();

      private Queue<string> m_queue;
      private Object m_lock;

      public static ThreadCommandQueue GetInstance()
      {
         return instance;
      }

      private ThreadCommandQueue()
      {
         m_queue = new Queue<string>();
         m_lock = new Object();
      }

      public void Add(
         string data_to_add)
      {
         lock (m_lock)
         {
            m_queue.Enqueue(data_to_add);
         }
      }

      public string Get()
      {
         lock (m_lock)
         {
            if (m_queue.Count > 0)
            {
               return m_queue.Dequeue();
            }

            return null;
         }
      }
   }

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

      private void PopulateThreadCommandQueue()
      {
         int i = 0;
         while(true)
         {
            ThreadCommandQueue.GetInstance().Add("Item #: " + i.ToString());
            i++;
         }
      }

      private void Form1_Load(object sender, EventArgs e)
      {
         // Create the Command Queue....
         ThreadCommandQueue.GetInstance();

         // Create a Testing Producer Thread
         Thread ProducerThread = new Thread(PopulateThreadCommandQueue);
         ProducerThread.Start();

         // The GUI thread is the Consumer, so keep checking the CommandQueue for data...
         while(true)
         {
            string latest = ThreadCommandQueue.GetInstance().Get();
            if(latest != null)
            {
               OutputBox.Text += latest + "\n";
            }
         }
      }
   }
}

Body:
Okay, the problem here is that you need to poll the message loop all the time to make GUI working and you also need to poll your IPC command queue all the time to make your commands working and you need this polling to happen at the same time on the same thread.

There are multiple ways to resolve this, but the easiest would be to process the message loop and when there is nothing to process, do your IPC command queue processing. For WinForms application this would be something like:

public Form1()
{
   InitializeComponent();
   Application.Idle += (sender, eargs) => ProcessCommands();
}

private void ProcessCommands()
{
    while(true)
    {
      string latest = ThreadCommandQueue.GetInstance().Get();
      if(string.IsNullOrEmpty(latest)) return;
      OutputBox.Text += latest + "\n";
    }
}


问:
Does a processor always reload CR3 when a VMEXIT occurs?
Does a processor always reload CR3 when a VMEXIT occurs?</p>

答: Assuming you are talking about virtualization using Intel VMX technology, then yes. See section 27.5.1 of the Intel SDM.</p>


问:
Properly Format a datetime-local form input via echo from MYSQL Table
I'm attempting to echo the value of arrivalDateTimeDest into a form so that the user can edit this value. I've attempted to accomplish this a few ways, however, the value that's echo's always equals mm/dd/yyyy --:-- --. What am I doing wrong? My attempts are listed below.

```<code><input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date_format($row['arrivalDateTimeDest'],'Y/m/d H:i:s')?>">

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date('Y/m/d H:i:s', $row['arrivalDateTimeDest'])?>">

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date('c', $row['arrivalDateTimeDest'])?>">
</code>```

In light of the recent answers to this post, I've pinpointed the issue, however I cannot yet solve it. When input type = text, I have no issue echoing the value, however, I cannot do this when the input type is set to datetime-local.

答:
Yes This is very simple task to do ,

Convert time from database to timestamp .

$timestamp = strtotime($row['arrivalDateTimeDest']);

Then use date() function to format this date .. in a format which you want

echo date("Y-m-d", $timestamp);

use this where you want to echo the date ... :) :)

Body:
I'm attempting to echo the value of arrivalDateTimeDest into a form so that the user can edit this value. I've attempted to accomplish this a few ways, however, the value that's echo's always equals mm/dd/yyyy --:-- --. What am I doing wrong? My attempts are listed below.

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date_format($row['arrivalDateTimeDest'],'Y/m/d H:i:s')?>">

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date('Y/m/d H:i:s', $row['arrivalDateTimeDest'])?>">

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date('c', $row['arrivalDateTimeDest'])?>">

In light of the recent answers to this post, I've pinpointed the issue, however I cannot yet solve it. When input type = text, I have no issue echoing the value, however, I cannot do this when the input type is set to datetime-local.


问:
how can I quickly convert in python an xlsx file into a csv file?
I have a 140MB Excel file I need to analyze using pandas. The problem is that if I open this file as xlsx it takes python 5 minutes simply to read it. I tried to manually save this file as csv and then it takes Python about a second to open and read it! There are different 2012-2014 solutions that why Python 3 don't really work on my end.

Can somebody suggest how to convert very quickly file 'C:\master_file.xlsx' to 'C:\master_file.csv'?

答:
Use read-only mode in openpyxl. Something like the following should work.</p>

```<code>import csv
import openpyxl

wb = load_workbook("myfile.xlsx", read_only=True)
ws = wb['sheetname']
with open("myfile.csv", "wb") as out:
    writer = csv.writer(out)
    for row in ws:
        values = (cell.value for cell in row)
        writer.writerow(values)
</code>```

Body:
Use read-only mode in openpyxl. Something like the following should work.

import csv
import openpyxl

wb = load_workbook("myfile.xlsx", read_only=True)
ws = wb['sheetname']
with open("myfile.csv", "wb") as out:
    writer = csv.writer(out)
    for row in ws:
        values = (cell.value for cell in row)
        writer.writerow(values)


问:
Omniauth login withouot requesting anything
I am looking to use omniauth for user login. For security purposes I would like to request no data be requested from the provider.

I have tried:

```<code>Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET'],  scope: '', info_fields: ''
end
</code>```

However when I login to facebook I am still advised that my app will receive the user's public profile. When I click "Review the info you provide" I am unable to deselect the public profile information that includes name etc.

Is it possible to receive no identifying details?

答:
No, that is not possible.

user_profile is the most basic permission, and gets asked for automatically during login, even if you don’t specify it.

Is it possible to receive no identifying details?

Well you don’t actually want none at all, because without something to identify a user by, you would not have an actual login.

If your users might be concerned about your app invading their privacy, then I can only recommend that you explain to them in detail what data your app will get access to; and maybe also what parts of that data it will actually use. (If you only need the app-scoped user id for the purpose of identifying them in your login system, but not anything else - then you could only ask for their id. Users would have to trust you on that of course.)

Body:
I am looking to use omniauth for user login. For security purposes I would like to request no data be requested from the provider.

I have tried:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET'],  scope: '', info_fields: ''
end

However when I login to facebook I am still advised that my app will receive the user's public profile. When I click "Review the info you provide" I am unable to deselect the public profile information that includes name etc.

Is it possible to receive no identifying details?


问:
How to set size for local image using knitr for markdown?
I have a local image that I would like to include in an .Rmd file which I will then knit and convert to HTML slides with Pandoc. Per this post, this will insert the local image :

![Image Title](path/to/your/image)

Is there a way to modify this code to also set the image size?

答:
Had the same issue today and found another option with knitr 1.16 when knitting to PDF (which requires that you have pandoc installed):

![Image Title](path/to/your/image){width=70%}

This method may require that you do a bit of trial and error to find the size that works for you. It is especially convenient because it makes putting two images side by side a prettier process. For example:

![Image 1](path/to/image1){width=70%}![Image 2](path/to/image2){width=30%}

You can get creative and stack a couple of these side by side and size them as you see fit. See https://rpubs.com/RatherBit/90926 for more ideas and examples.


问:
How to check if a string starts with another string in C?
Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.

Examples:

```<code>"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc"    -> true
</code>```

答:
Apparently there's no standard C function for this. So:

```<code>bool startsWith(const char *pre, const char *str)
{
    size_t lenpre = strlen(pre),
           lenstr = strlen(str);
    return lenstr < lenpre ? false : memcmp(pre, str, lenpre) == 0;
}
</code>```

Note that the above is nice and clear, but if you're doing it in a tight loop or working with very large strings, it does not offer the best performance, as it scans the full length of both strings up front (strlen). Solutions like wj32's or Christoph's may offer better performance (although this comment about vectorization is beyond my ken of C). Also note Fred Foo's solution which avoids strlen on str (he's right, it's unnecessary if you use strncmp instead of memcmp). Only matters for (very) large strings or repeated use in tight loops, but when it matters, it matters.

Body:
Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.

Examples:

"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc"    -> true

Body:
Apparently there's no standard C function for this. So:

bool startsWith(const char *pre, const char *str)
{
    size_t lenpre = strlen(pre),
           lenstr = strlen(str);
    return lenstr < lenpre ? false : memcmp(pre, str, lenpre) == 0;
}

Note that the above is nice and clear, but if you're doing it in a tight loop or working with very large strings, it does not offer the best performance, as it scans the full length of both strings up front (strlen). Solutions like wj32's or Christoph's may offer better performance (although this comment about vectorization is beyond my ken of C). Also note Fred Foo's solution which avoids strlen on str (he's right, it's unnecessary if you use strncmp instead of memcmp). Only matters for (very) large strings or repeated use in tight loops, but when it matters, it matters.


问:
TFS2017 nuget restore try to connect to nuget.org
I have a TFS server without internet access. I configure my own nuget package feeds in TFS and I try to restore packages of my solution only from this feed. But when I start Nuget restore build step, nuget try to connect to nuget.org and the connection failed. I don't understand how prevent this attempt of unnecessary connection ?

答:
I find the problem. In fact, I think NugetRestore task try to connect to nuget.org to get the last version of nuget.exe.

I skirt the problem with use version 0.* of NugetRestore task and specif the version of nuget to use.


问:
How to generate scaffold for data type with "extra description" in Rails 3?
From Ruby on Rails: best method of handling currency / money, how do you generate a scaffold for the folowing:

```<code>add_column :items, :price, :decimal, :precision => 8, :scale => 2
</code>```

Such as:

```<code>rails generate scaffold LineItem name:string \
                                 price:decimal {:precision => 8, :scale => 2}
</code>```

Also, what is the correct term for "extra description" for the decimal type?

Working in Rails 3.07, Ruby 1.92

答:
This is the accurate and most simple way to do this under Rails 5.x:

rails generate scaffold LineItem name price:decimal{'8,2'}

Pay special attention to the single quotes used when specifying scale and precision.

Body:
From Ruby on Rails: best method of handling currency / money, how do you generate a scaffold for the folowing:

add_column :items, :price, :decimal, :precision => 8, :scale => 2

Such as:

rails generate scaffold LineItem name:string \
                                 price:decimal {:precision => 8, :scale => 2}

Also, what is the correct term for "extra description" for the decimal type?

Working in Rails 3.07, Ruby 1.92


问:
Delete Function org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
Do anyone know how to solve this problem?? I am trying to delete an entity but this error message always appears.

This is the code used:

```<code>@Override
public void remove(t_diklat diklat) {

      Session session = HibernateUtil.getSessionFactory().openSession();

    try {
        session.getTransaction().begin();
        session.delete(diklat);
        session.getTransaction().commit();
    } catch (Exception ex) {

        throw ex;
    }
</code>```

and:

```<code> public String delete() {
 t_diklat diklat = (t_diklat)(listDiklat.getRowData());
        diklatDao dao = new diklat_Impl();
        dao.remove(diklat);
        return "diklat_client";

    }
</code>```

This is my dao

```<code>public interface diklatDao {
    public t_diklat getTbl_diklat(Long id);
    public void Save(t_diklat diklat);
    public void remove(t_diklat diklat);
    public void update(t_diklat diklat);

    public List<t_diklat> ListTable();

}
</code>```

I also add @OneToMany(mappedBy = "diklat_id_5",  cascade = CascadeType.ALL) to my model.class but still nothing.

答:
I am quite sure that the:

```<code>public String delete()
</code>```

method is called within an already opened session as you are retrieving data:

```<code>t_diklat diklat = (t_diklat)(listDiklat.getRowData());
</code>```

just before you hit the dao.remove() method.

Inside the dao, you open another session and try pass an entity that is already associated with the presiously opened and still not closed session.

The solution would be to use:

```<code>Session session = HibernateUtil.getSessionFactory().getCurrentSession();
</code>```

instead of:

```<code>Session session = HibernateUtil.getSessionFactory().openSession();
</code>```

Edit:

Try not to open any new transactions and do not perform a commit in the dao. The outer session management should be enough.. So in your dao just:

```<code>Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.delete(diklat);
</code>```

Body:
Do anyone know how to solve this problem?? I am trying to delete an entity but this error message always appears.

This is the code used:

@Override
public void remove(t_diklat diklat) {

      Session session = HibernateUtil.getSessionFactory().openSession();

    try {
        session.getTransaction().begin();
        session.delete(diklat);
        session.getTransaction().commit();
    } catch (Exception ex) {

        throw ex;
    }

and:

 public String delete() {
 t_diklat diklat = (t_diklat)(listDiklat.getRowData());
        diklatDao dao = new diklat_Impl();
        dao.remove(diklat);
        return "diklat_client";

    }

This is my dao

public interface diklatDao {
    public t_diklat getTbl_diklat(Long id);
    public void Save(t_diklat diklat);
    public void remove(t_diklat diklat);
    public void update(t_diklat diklat);

    public List<t_diklat> ListTable();

}

I also add @OneToMany(mappedBy = "diklat_id_5",  cascade = CascadeType.ALL) to my model.class but still nothing.

Body:
I am quite sure that the:

public String delete()

method is called within an already opened session as you are retrieving data:

t_diklat diklat = (t_diklat)(listDiklat.getRowData());

just before you hit the dao.remove() method.

Inside the dao, you open another session and try pass an entity that is already associated with the presiously opened and still not closed session.

The solution would be to use:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

instead of:

Session session = HibernateUtil.getSessionFactory().openSession();

Edit:

Try not to open any new transactions and do not perform a commit in the dao. The outer session management should be enough.. So in your dao just:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.delete(diklat);


问:
Should renaming a project in Eclipse also rename project folder on file system?
Should renaming a project in Eclipse also rename project folder on file system ?

My project file system name remains the same even when I rename the file on Eclipse.

Should I manually rename the project on the file system to same on Eclipse ?

答:
In Eclipse Oxygen (4.7) the Move option is greyed and renaming the project does not rename the directory. However, if you switch to the Navigator view (may need to find it under Window > Show View > Navigator) the Move option will be available and it will rename the project's directory.

This is a lot faster than having to recreate the project or re-import it.


问:
Youtube embedded video keeps hiding my JavaScript popup dialogs
I tried playing with z-index, and also tried setting the wmode to "opaque". Nonthing worked..

It keeps hiding my popup dialogs..

Here is the current iframe code

```<code><iframe title="YouTube video player" class="youtube-player" type="text/html" width="450" height="297" src="http://www.youtube.com/embed/glqpoDfuAwk" frameborder="0" ></iframe>
</code>```

EDIT: As pointed out below, using "embed" and opaque wmode solves the problem. But I cannot find any solution for YouTube's new style of embedding using iframe

答:
The flash embed code still works (Demo):

```<code><object width="640" height="385">
    <param name="movie" value="http://www.youtube.com/v/vx2u5uUu3DE"></param>
    <param name="allowFullScreen" value="true"></param>
    <param name="allowscriptaccess" value="always"></param>
    <param name="wmode" value="opaque"></param>
    <embed src="http://www.youtube.com/v/vx2u5uUu3DE"
         type="application/x-shockwave-flash" allowscriptaccess="always"
         allowfullscreen="true" width="640" height="385" wmode="opaque"></embed>
  </object>
</code>```

Body:
I tried playing with z-index, and also tried setting the wmode to "opaque". Nonthing worked..

It keeps hiding my popup dialogs..

Here is the current iframe code

EDIT: As pointed out below, using "embed" and opaque wmode solves the problem. But I cannot find any solution for YouTube's new style of embedding using iframe

Body:
The flash embed code still works (Demo):

<object width="640" height="385">
    <param name="movie" value="http://www.youtube.com/v/vx2u5uUu3DE"></param>
    <param name="allowFullScreen" value="true"></param>
    <param name="allowscriptaccess" value="always"></param>
    <param name="wmode" value="opaque"></param>
    <embed src="http://www.youtube.com/v/vx2u5uUu3DE"
         type="application/x-shockwave-flash" allowscriptaccess="always"
         allowfullscreen="true" width="640" height="385" wmode="opaque"></embed>
  </object>


问:
SQL Server take database backup with some data only
I am trying to download my SQL Server database (that is more than 40 GB) from production server to my local machine. I need only schema & some of data as downloading 40 GB backup file & restoring is really tough task for me.

I have tried to use generate scripts to obtain schema, this was successful. But for getting data for (suppose approx. first 500 rows) of all tables, I am not sure how I should approach that.

Please let me know is there any other way to achieve this?

I am using Microsoft's SQL Server Version 12.0.xxx.

Thanks

答:
SQL Server Management Studio provides a wizard which enables you to generate scripts not only for metadata (or schema) but also the scripts for data within database.
Please refer to Script Data in SQL Server
But if your database backup size is very big, the script file will be very huge.
Actually this wizard does not provide a parameter to script only for first 500 rows of each table.

Besides all, if you have foreign keys and constraints on your table definitions, you might not be enough to get only the first 500 rows. You need every referenced lookup data in your database in order to insert data into your transactional tables, or you need the parent for the child data.

This forces you to create a more smart script for data extraction.


问:
How to make tab active on page - HTML & Laravel
Below is an HTML table contained in a tab. Now the issue i am facing is, on page load, the selected teams are supposed to show checked in the table. This is what i have noticed in my application.

For user 1, on page load the first tab is active with the checked team also  showing.

For user 2 and other users, the first tab is not active until i click on the tab before the table shows with the checked team?

I am thinking this is happening because of the $key in there. I actually can't tell why.. Any help will be appreciated .. Thanks

```<code>      <div  class="nav-tabs-custom">

        <ul class="nav nav-tabs">
        @foreach($countries as $country)

           <li ><a href="#tab_{{ $country->id }}" data-toggle="tab" >{!!$country->name!!}</a></li>
           @endforeach

        </ul>
        <div class="tab-content">
        @foreach($countries as $key => $country)

        <div class="tab-pane {{ $key==0 ? 'active' : ''}}" id="tab_{{ $country->id }}">
        <table class="table">
                            <thead>
                                <tr>
                                    <th></th>
                                    <th></th>
                                    <th></th>
                                 </tr>
                           </thead>
                           <tbody id="team_list">
          @foreach($country->teams as $team)
                             <tr>
                           <td>  <input onclick="return team(this)" data-team="{{$team->toJson()}}" type="checkbox" id="{!! $team->id !!}" name="{!! $team->name !!}" value="{!! $team->value !!}"  @foreach ($town->teams as $active_teams)   @if($team->id == $active_teams->id    ) checked @endif @endforeach  /></td>
                                    <td>{{$team->name }}</td>
                                    <td>{{ $team->value}}</td>
                                </tr>
          @endforeach
       </tbody>
       </table>

         </div>
        @endforeach
          </div>

        </div>

      </div>

    </div>
</code>```

答:
In PHP, by default, the list starts with 0, so the user 1 has the key 0, the user 2 has the key 1 ..etc

That is why you have the "user 1" only selected.

Body:
Below is an HTML table contained in a tab. Now the issue i am facing is, on page load, the selected teams are supposed to show checked in the table. This is what i have noticed in my application.

For user 1, on page load the first tab is active with the checked team also  showing.

For user 2 and other users, the first tab is not active until i click on the tab before the table shows with the checked team?

I am thinking this is happening because of the $key in there. I actually can't tell why.. Any help will be appreciated .. Thanks

        @foreach($countries as $country)

id }}" data-toggle="tab" >{!!$country->name!!}

           @endforeach

        @foreach($countries as $key => $country)

id }}">

          @foreach($country->teams as $team)

                             <input onclick="return team(this)" data-team="{{$team->toJson()}}" type="checkbox" id="{!! $team->id !!}" name="{!! $team->name !!}" value="{!! $team->value !!}"  @foreach ($town->teams as $active_teams)   @if($team->id == $active_teams->id    ) checked @endif @endforeach  />
                                    {{$team->name }}
                                    {{ $team->value}}

          @endforeach

        @endforeach


问:
How to read Unicode input and compare Unicode strings in Python?
I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of raw_input?

Also, I would like to test Unicode strings for equality and it looks like a standard == does not work.

答: In the general case, it's probably not possible to compare unicode strings.  The problem is that there are several ways to compose the same characters.  A simple example is accented roman characters.  Although there are codepoints for basically all of the commonly used accented characters, it is also correct to compose them from unaccented base letters and a non-spacing accent.  This issue is more significant in many non-roman alphabets.  </p>

OwnerDisplayName: TokenMacGuy


问:
Java N-Dimensional Arrays
I need to be able to have an n-dimensional field where n is based on an input to the constructor.  But I'm not even sure if that's possible.  Is it?</p>

答:
Here's a nice article that explains how to use reflection to create arrays at run-time: Java Reflection: Arrays. That article explains how to create a one-dimensional array, but java.lang.reflect.Array also contains another newInstance method to create multi-dimensional arrays. For example:

```<code>int[] dimensions = { 10, 10, 10 }; // 3-dimensional array, 10 elements per dimension
Object myArray = Array.newInstance(String.class, dimensions); // 3D array of strings
</code>```

Since the number of dimensions is not known until runtime, you can only handle the array as an Object and you must use the get and set methods of the Array class to manipulate the elements of the array.

Title: Java N-Dimensional Arrays

Body:
Here's a nice article that explains how to use reflection to create arrays at run-time: Java Reflection: Arrays. That article explains how to create a one-dimensional array, but java.lang.reflect.Array also contains another newInstance method to create multi-dimensional arrays. For example:

int[] dimensions = { 10, 10, 10 }; // 3-dimensional array, 10 elements per dimension
Object myArray = Array.newInstance(String.class, dimensions); // 3D array of strings

Since the number of dimensions is not known until runtime, you can only handle the array as an Object and you must use the get and set methods of the Array class to manipulate the elements of the array.


问:
Bootstrap indicators don't work on click
When slide changes indicators are in right position (1-2-3). But when I click on them, they are not responding. Prev and next links are working fine. Here is my code:

```<code><div id="theCarousel" class="carousel-slide hidden-xs" data-interval ="3000">
        <!-- Indicators -->
        <ol class="carousel-indicators">
            <li data-target="#theCarousel" data-slide-to="0" class="active"></li>
            <li data-target="#theCarousel" data-slide-to="1"></li>
            <li data-target="#theCarousel" data-slide-to="2"></li>
        </ol>
        <div class="carousel-inner">
            <div class="item active"><img class="img-responsive" src="eberhard-grossgasteiger-311213.jpg" alt="slide 1"></div>
            <div class="item"><img class="d-block img-fluid" src="annie-spratt-176376.jpg" alt="slide 2"></div>
            <div class="item"><img class="d-block img-fluid" src="joanna-kosinska-129039.jpg" alt="slide 3"></div>
        </div><!-- /carousel-inner -->
        <!-- navigation -->
        <a class="left carousel-control" href="#theCarousel" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
        <a class="right carousel-control" href="#theCarousel" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
    </div><!-- /carousel-slide --
</code>```

Here is JS file:

```<code>// Activate Carouse
$("#theCarousel").carousel();

// Enable Carousel Indicators
$(".item").click(function(){
    $("#theCarousel").carousel(1);
 });

// Enable Carousel Control
 $(".left").click(function(){
     $("#theCarousel").carousel("prev");
 });

 $(".right").click(function(){
     $("#theCarousel").carousel("next");
 });
</code>```

What is wrong?

答:
Click button "Run code snippet" and check its working, No need to add extra script(js), All controls of carousel handled by bootstrap.

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Carousel Example

      Previous

      Next

```

Body:
Click button "Run code snippet" and check its working, No need to add extra script(js), All controls of carousel handled by bootstrap.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Carousel Example</h2>
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner">
      <div class="item active">
        <img src="http://midtowncarpetcleaning.com/wp-content/themes/envision/lib/images/default-placeholder-1000x600.png" alt="Los Angeles" style="width:100%;">
      </div>

      <div class="item">
        <img src="http://midtowncarpetcleaning.com/wp-content/themes/envision/lib/images/default-placeholder-1000x600.png" alt="Chicago" style="width:100%;">
      </div>

      <div class="item">
        <img src="http://midtowncarpetcleaning.com/wp-content/themes/envision/lib/images/default-placeholder-1000x600.png" alt="New york" style="width:100%;">
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>

</body>
</html>


问:
swift 3 filter array of dictionaries by string value of key in dictionary
I have a class such as this

```<code>class FoundItem : NSObject {

var id : String!
var itemName : String!
var itemId : Int!
var foundBy : String!
var timeFound : String!

init(id: String,
    itemName: String,
    itemId: Int,
    foundBy: String,
    timeFound: String)

{
    self.id = id
    self.itemName = itemName
    self.itemId = itemId
    self.foundBy = foundBy
    self.timeFound = timeFound

}
</code>```

and I reference it on my

```<code>class MapViewVC: UIViewController, MKMapViewDelegate {

var found = [FoundItem]()

var filterItemName : String()

}
</code>```

My FoundItem are generated by into an array of dictionaries from my class of FoundItem from a firebase query. I then get a string of that itemName that is generated from an another view controller that is a collection view on the didSelection function. I want to take that string and then filter or search the arrays with the string itemName that is equal from the itemName string from my previous viewController. Then removed the array of dictionaries that are not equal to the itemName. Not just the objects, but the entire array that contains non-equal key, value pair. I have looked for days, and I am stuck on filtering an array of dictionaries created from a class. I have looked and tried NSPredicates, for-in loops, but all that ends up happening is creating a new array or bool that finds my values or keys are equal. Here is the current function I have written.

```<code>func filterArrayBySearch() {

    if self.filterItemName != nil {

        dump(found)

        let namePredicate = NSPredicate(format: "itemName like %@", "\(filterItemName)")
        let nameFilter = found.filter { namePredicate.evaluate(with: $0) }

        var crossRefNames = [String: [FoundItem]]()
        for nameItemArr in found {
            let listName = nameItem.itemName
            let key = listName

            if crossRefNames.index(forKey: key!) != nil {

                crossRefNames[key!]?.append(nameItemArr)

                if !("\(key)" == "\(filterItemName!)") {

                    print("------------- Success have found [[[[[[    \(key!)    ]]]]]] and \(filterItemName!) to be equal!!")

                     // crossRefNames[key!]?.append(nameItemArr)

                } else {

                    print("!! Could not find if \(key!) and \(filterItemName!) are equal !!")
                }

            } else {

                crossRefNames[key!] = [nameItemArr]
            }
        }

    } else {

        print("No Data from Search/FilterVC Controller")
    }
}
</code>```

Can anyone help? It seems like it would be the simple task to find the value and then filter out the dictionaries that are not equal to the itemName string, but I keep hitting a wall. And running into for-in loops myself :P trying different things to achieve the same task.

答:
Sort array of dictionary using the following way

```<code>var dict:[[String:AnyObject]] = sortedArray.filter{($0["parentId"] as! String) == "compareId"}
</code>```

The filter function loops over every item in a collection, and returns a collection containing only items that satisfy an include condition.

We can get single object from this array of dictionary , you can use the following code

```<code>var dict = sortedArray.filter{($0["parentId"] as! String) == "compareId"}.first
</code>```

OR

```<code> let dict = sortedArray.filter{ ($0["parentId"] as! String) == "compareId" }.first
</code>```

Body:
I have a class such as this

class FoundItem : NSObject {

var id : String!
var itemName : String!
var itemId : Int!
var foundBy : String!
var timeFound : String!

init(id: String,
    itemName: String,
    itemId: Int,
    foundBy: String,
    timeFound: String)

{
    self.id = id
    self.itemName = itemName
    self.itemId = itemId
    self.foundBy = foundBy
    self.timeFound = timeFound

}

and I reference it on my

class MapViewVC: UIViewController, MKMapViewDelegate {

var found = [FoundItem]()

var filterItemName : String()

}

My FoundItem are generated by into an array of dictionaries from my class of FoundItem from a firebase query. I then get a string of that itemName that is generated from an another view controller that is a collection view on the didSelection function. I want to take that string and then filter or search the arrays with the string itemName that is equal from the itemName string from my previous viewController. Then removed the array of dictionaries that are not equal to the itemName. Not just the objects, but the entire array that contains non-equal key, value pair. I have looked for days, and I am stuck on filtering an array of dictionaries created from a class. I have looked and tried NSPredicates, for-in loops, but all that ends up happening is creating a new array or bool that finds my values or keys are equal. Here is the current function I have written.

func filterArrayBySearch() {

    if self.filterItemName != nil {

        dump(found)

        let namePredicate = NSPredicate(format: "itemName like %@", "\(filterItemName)")
        let nameFilter = found.filter { namePredicate.evaluate(with: $0) }

        var crossRefNames = [String: [FoundItem]]()
        for nameItemArr in found {
            let listName = nameItem.itemName
            let key = listName

            if crossRefNames.index(forKey: key!) != nil {

                crossRefNames[key!]?.append(nameItemArr)

                if !("\(key)" == "\(filterItemName!)") {

                    print("------------- Success have found [[[[[[    \(key!)    ]]]]]] and \(filterItemName!) to be equal!!")

                     // crossRefNames[key!]?.append(nameItemArr)

                } else {

                    print("!! Could not find if \(key!) and \(filterItemName!) are equal !!")
                }

            } else {

                crossRefNames[key!] = [nameItemArr]
            }
        }

    } else {

        print("No Data from Search/FilterVC Controller")
    }
}

Can anyone help? It seems like it would be the simple task to find the value and then filter out the dictionaries that are not equal to the itemName string, but I keep hitting a wall. And running into for-in loops myself :P trying different things to achieve the same task.

Body:
Sort array of dictionary using the following way

var dict:[[String:AnyObject]] = sortedArray.filter{($0["parentId"] as! String) == "compareId"}

The filter function loops over every item in a collection, and returns a collection containing only items that satisfy an include condition.

We can get single object from this array of dictionary , you can use the following code

var dict = sortedArray.filter{($0["parentId"] as! String) == "compareId"}.first

OR

 let dict = sortedArray.filter{ ($0["parentId"] as! String) == "compareId" }.first


问:
Validate an array from excel file using Laravel validation
Hi I wonder if it possible to validate an array like this in laravel:

```<code>Array
(
    [0] => John
    [1] => 20
    [2] => john@example.com
)
</code>```

because im getting the data from the excel file. I want to validate the [1] => numeric and [2] => email.

Thanks.

答:
You need to create a custom validation like following.

```<code>Validator::extend('check_my_array', function ($attribute, $value, $parameters, $validator) {
    $validation = [];
    foreach($parameters as $parameter)
        $validation[] = "required|{$parameter}";

    $validator = Validator::make($value, $validation);
    return !$validator->fails();
});
</code>```

You can create ValidatorServiceProvider and you can add these lines to boot method of ValidatorServiceProvider. Then you need to add Provider to your providers array in config/app.php.

```<code>App\Providers\ValidatorServiceProvider::class,
</code>```

Or you just add them top of the action of your controller.

At the end you can use it like this in your validation rules.

```<code>$validator = Validator::make(
  ['array' => ['John', 'asd', 'john@example.com']],
  ['array' => 'check_my_array:,numeric,email']
);

if ($validator->fails())
   dd('fail');
else dd('success');
</code>```

Note: Everything after the check_my_array separated by comma is a parameter we use them specific rule for elements of the array.

Body:
Hi I wonder if it possible to validate an array like this in laravel:

Array
(
    [0] => John
    [1] => 20
    [2] => john@example.com
)

because im getting the data from the excel file. I want to validate the [1] => numeric and [2] => email.

Thanks.

Body:
You need to create a custom validation like following.

Validator::extend('check_my_array', function ($attribute, $value, $parameters, $validator) {
    $validation = [];
    foreach($parameters as $parameter)
        $validation[] = "required|{$parameter}";

    $validator = Validator::make($value, $validation);
    return !$validator->fails();
});

You can create ValidatorServiceProvider and you can add these lines to boot method of ValidatorServiceProvider. Then you need to add Provider to your providers array in config/app.php.

App\Providers\ValidatorServiceProvider::class,

Or you just add them top of the action of your controller.

At the end you can use it like this in your validation rules.

$validator = Validator::make(
  ['array' => ['John', 'asd', 'john@example.com']],
  ['array' => 'check_my_array:,numeric,email']
);

if ($validator->fails())
   dd('fail');
else dd('success');

Note: Everything after the check_my_array separated by comma is a parameter we use them specific rule for elements of the array.


问:
How to create dynamic files?
i´m trying to rename ethernet-interfaces on Linux. Each interface with the name enp0s* have to be eth*. First, i create udev-rules for renaming. that works fine. Secondly i have to create new configuration-files for each interface ( ' etc/sysconfig/network-scripts/ifcfg-eth* ' ). I don´t know, how to create the loop to place parameters in each interface. Can somneone help me?

Thats an extract of my playbook:

```<code>- name: Get new interface-names of the new created udev-rules
  become: yes
  shell: cat /etc/udev/rules.d/70-persisten-ipoib.rules.cfg | egrep -i 'eth.'
  register: car

- name: Create new-ifcfg-eth* files
  template:
  with_items: "{{ car.stdout_lines }}"
  register: cat
  template: src= roles/configure_network/templates/create_ifcfg.cfg.j2    dest=/etc/sysconfig/network-scripts/ifcfg-{{ item }}

# Template: roles/configure_network/templates/create_ifcfg.cfg.j2

{% for interface in cat.results %}
NAME="eth{{ item.name }}
TYPE=Ethernet
BOOTPROTO={{item.bootproto|default('dhcp')}}
IPV4_FAILURE_FATAL=no
IPV6INIT=no
{% if item.ipaddress is defined %}
IPADDR={{item.ipaddress}}
{% endif %}
{% if item.netmask is defined %}
NETMASK={{item.netmask}}
{% endif %}
{% if item.gateway is defined %}
GATEWAY={{item.gateway}}
{% endif %}
PEERDNS=no
{% if item.dns is defined %}
DNS1={{item.dns}}
{% endif %}
ONBOOT={{item.onboot|default('yes')}}
{% endfor %}
</code>```

答:
Just fix your syntax:

```<code>- name: Create new-ifcfg-eth* files
  template:
    src: create_ifcfg.cfg.j2
    dest: /etc/sysconfig/network-scripts/ifcfg-{{ item }}
  with_items: "{{ car.stdout_lines }}"
  register: cat
</code>```

Remove double template call, use relative path (no need to define full path to role's own templates), use YAML syntax instead of key=value (you had spaces in them, which are not allowed).

Title: How to create dynamic files?

Body:
i´m trying to rename ethernet-interfaces on Linux. Each interface with the name enp0s* have to be eth*. First, i create udev-rules for renaming. that works fine. Secondly i have to create new configuration-files for each interface ( ' etc/sysconfig/network-scripts/ifcfg-eth* ' ). I don´t know, how to create the loop to place parameters in each interface. Can somneone help me?

Thats an extract of my playbook:

- name: Get new interface-names of the new created udev-rules
  become: yes
  shell: cat /etc/udev/rules.d/70-persisten-ipoib.rules.cfg | egrep -i 'eth.'
  register: car

- name: Create new-ifcfg-eth* files
  template:
  with_items: "{{ car.stdout_lines }}"
  register: cat
  template: src= roles/configure_network/templates/create_ifcfg.cfg.j2    dest=/etc/sysconfig/network-scripts/ifcfg-{{ item }}

# Template: roles/configure_network/templates/create_ifcfg.cfg.j2

{% for interface in cat.results %}
NAME="eth{{ item.name }}
TYPE=Ethernet
BOOTPROTO={{item.bootproto|default('dhcp')}}
IPV4_FAILURE_FATAL=no
IPV6INIT=no
{% if item.ipaddress is defined %}
IPADDR={{item.ipaddress}}
{% endif %}
{% if item.netmask is defined %}
NETMASK={{item.netmask}}
{% endif %}
{% if item.gateway is defined %}
GATEWAY={{item.gateway}}
{% endif %}
PEERDNS=no
{% if item.dns is defined %}
DNS1={{item.dns}}
{% endif %}
ONBOOT={{item.onboot|default('yes')}}
{% endfor %}

Body:
Just fix your syntax:

- name: Create new-ifcfg-eth* files
  template:
    src: create_ifcfg.cfg.j2
    dest: /etc/sysconfig/network-scripts/ifcfg-{{ item }}
  with_items: "{{ car.stdout_lines }}"
  register: cat

Remove double template call, use relative path (no need to define full path to role's own templates), use YAML syntax instead of key=value (you had spaces in them, which are not allowed).