问:
Convert vector<Rect> OpenCV to vector<vector<float>> in C++
I am trying to convert the vector Rect datatype to vector vector float to use non maximum suppression on the vector. vector contains rectangle points of faces. I want to apply nms as seen here:Non Maximum Suppression.

When trying to compile I get following error:

**

```<code>undefined reference to `nms(std::vector<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > > const&, float const&)'
collect2: error: ld returned 1 exit status
</code>```

**

I dont know why it is giving the nms function 2x vector vector float?
Thanks for help!

```<code>   vector<Rect> apply_pre_filters(vector<Rect>faces_vector){

    // Non Max Suppression
    float threshold = 0.5;
    vector<vector<float>> faces_vector_float_container;
    cout << "original vector size" << faces_vector.size() << endl;

    for (int i=0; i < faces_vector.size(); i++) {
        vector<int> faces_vector_int = {faces_vector[i].tl().x,faces_vector[i].tl().y,faces_vector[i].br().x, faces_vector[i].br().y};
        vector<float> faces_vector_float(faces_vector_int.begin(), faces_vector_int.end());

        faces_vector_float_container.push_back(faces_vector_float);
    }

    cout << "modified vector size" << faces_vector_float_container.size() << endl;
    vector<Rect> filtered_faces_vector = nms(faces_vector_float_container, threshold);

    // Change Faces detected flag
    if(faces_vector.size() > 0){
        faces_detected = true;
    }else{
        faces_detected = false;
    }

    return faces_vector;
}
</code>```

答: I added the nms files into the CMakeFileList.txt SOURCE_FILES(). It seems to work now.

Body:
I am trying to convert the vector Rect datatype to vector vector float to use non maximum suppression on the vector. vector contains rectangle points of faces. I want to apply nms as seen here:Non Maximum Suppression.

When trying to compile I get following error:

**

undefined reference to `nms(std::vector<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > > const&, float const&)'
collect2: error: ld returned 1 exit status

**

I dont know why it is giving the nms function 2x vector vector float?
Thanks for help!

   vector<Rect> apply_pre_filters(vector<Rect>faces_vector){

    // Non Max Suppression
    float threshold = 0.5;
    vector<vector<float>> faces_vector_float_container;
    cout << "original vector size" << faces_vector.size() << endl;

    for (int i=0; i < faces_vector.size(); i++) {
        vector<int> faces_vector_int = {faces_vector[i].tl().x,faces_vector[i].tl().y,faces_vector[i].br().x, faces_vector[i].br().y};
        vector<float> faces_vector_float(faces_vector_int.begin(), faces_vector_int.end());

        faces_vector_float_container.push_back(faces_vector_float);
    }

    cout << "modified vector size" << faces_vector_float_container.size() << endl;
    vector<Rect> filtered_faces_vector = nms(faces_vector_float_container, threshold);

    // Change Faces detected flag
    if(faces_vector.size() > 0){
        faces_detected = true;
    }else{
        faces_detected = false;
    }

    return faces_vector;
}


来源: stackexchange

问:
Server selection over Angular 2?
I need few suggestions on choosing server over Angular 2.

Like if i choose Django as server side, why should i choose and what are its advantages.

If i choose Node Js as server, what are its advantages over Django.

My requirement goes like: I have developed a website using Angular 2 which basically involves booking system- like order processing, send notification to customers once order status changes via API calls etc.

Im bit confused over which server to choose in my scenario since im a newbie in both Django and node js.

答:
Well, first of all Django is a lot more than a server. So I would skip that and look into Python servers instead.

Or you could look into node.js since you seem to be more inclined towards javascript.

Also there's small java servers available. But in your case I would probably go with node.js server since it's very easy to set up.

ContentLicense: CC BY-SA 3.0

Title: Server selection over Angular 2?


问:
how to make a property of a foreign table appear on datagridview using LINQ?
I have two tables auto gen from my MySQL database

```<code>public partial class adviser
{
    public int adviserId { get; set; }
    public string employeeNo { get; set; }
    public string lastName { get; set; }
    public string firstName { get; set; }
    public string middleName { get; set; }
    public Nullable<int> statId { get; set; }
    public Nullable<int> createdById { get; set; }
    public Nullable<System.DateTime> createdOn { get; set; }

    public virtual stat stat { get; set; }
    public virtual user user { get; set; }
}

public partial class stat
{
    public stat()
    {
        this.advisers = new HashSet<adviser>();
    }

    public int statId { get; set; }
    public string statName { get; set; }
    public string details { get; set; }

    public virtual ICollection<adviser> advisers { get; set; }
}
</code>```

then i have this method to get the collections of advisers

```<code>public List<adviser> GetList(AdviserParam p)
{
    List<adviser> items;
    using (VotingContext context = new VotingContext())
    {
        items = context.advisers.Include("stat").Where(x  =>
            (x.adviserId == p.AdviserId || p.AdviserId == 0)
            && (x.employeeNo.Contains(p.EmployeeNo) || p.EmployeeNo == "")
            && (x.lastName.Contains(p.LastName) || p.LastName == "")
            && (x.firstName.Contains(p.FirstName) || p.FirstName == "")
            && (x.middleName.Contains(p.MiddleName) || p.MiddleName == "")
            // && (x.statId == 1)
            ).ToList();
    }

    return items;
}
</code>```

then I use these codes to put them into the data grid view (win form), I edited the columns so that it wont display the adviserId and statId properties.

```<code>ItemsGridView.AutoGenerateColumns = false;
ItemsGridView.DataSource = vm.EntityList; // vm.EntityList is where I put the returned advisers from the GetList() method)
</code>```

but the dgv doesn't display the statName (from stats table). How can I make it appear?

答:
To get value from stat object you can select an anonymous type and include all the required properties.

I've shown a simple example to include statName and employeeNo.

```<code>var items = context.advisers.Where(x => x.adviserId == yourAdviserID)
        .Select(a=> new {name = a.stat.statName, employee=a.employeeNo}).ToList();
</code>```

Now if you bind items to Datagridview you'll see only name and employee columns.

If you dont want to display advisorID and statID then just dont include them in your new anonymous type.

Body:
I have two tables auto gen from my MySQL database

public partial class adviser
{
    public int adviserId { get; set; }
    public string employeeNo { get; set; }
    public string lastName { get; set; }
    public string firstName { get; set; }
    public string middleName { get; set; }
    public Nullable<int> statId { get; set; }
    public Nullable<int> createdById { get; set; }
    public Nullable<System.DateTime> createdOn { get; set; }

    public virtual stat stat { get; set; }
    public virtual user user { get; set; }
}

public partial class stat
{
    public stat()
    {
        this.advisers = new HashSet<adviser>();
    }

    public int statId { get; set; }
    public string statName { get; set; }
    public string details { get; set; }

    public virtual ICollection<adviser> advisers { get; set; }
}

then i have this method to get the collections of advisers

public List<adviser> GetList(AdviserParam p)
{
    List<adviser> items;
    using (VotingContext context = new VotingContext())
    {
        items = context.advisers.Include("stat").Where(x  =>
            (x.adviserId == p.AdviserId || p.AdviserId == 0)
            && (x.employeeNo.Contains(p.EmployeeNo) || p.EmployeeNo == "")
            && (x.lastName.Contains(p.LastName) || p.LastName == "")
            && (x.firstName.Contains(p.FirstName) || p.FirstName == "")
            && (x.middleName.Contains(p.MiddleName) || p.MiddleName == "")
            // && (x.statId == 1)
            ).ToList();
    }

    return items;
}

then I use these codes to put them into the data grid view (win form), I edited the columns so that it wont display the adviserId and statId properties.

ItemsGridView.AutoGenerateColumns = false;
ItemsGridView.DataSource = vm.EntityList; // vm.EntityList is where I put the returned advisers from the GetList() method)

but the dgv doesn't display the statName (from stats table). How can I make it appear?

Body:
To get value from stat object you can select an anonymous type and include all the required properties.

I've shown a simple example to include statName and employeeNo.

var items = context.advisers.Where(x => x.adviserId == yourAdviserID)
        .Select(a=> new {name = a.stat.statName, employee=a.employeeNo}).ToList();

Now if you bind items to Datagridview you'll see only name and employee columns.

If you dont want to display advisorID and statID then just dont include them in your new anonymous type.


问:
How to check the length of file which is inside the zip file
I want to check files inside the zip are not empty. I know the unzip -l command but it gives lot of information.

```<code>[abc@localhost test]$ unzip -l empty_file_test.zip
Archive:  empty_file_test.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
    0      07-05-2017 06:43   empty_first_20170505.csv
    0      07-05-2017 06:43   empty_second_20170505.csv
---------                     -------
    0                         2 files
</code>```

I extracted the file names from the zip file by command

```<code>file_names="$(unzip -Z1 empty_file_test.zip)
file_name_array=($file_names)
file1=${file_name_array[0]}
file2=${file_name_array[1]}
</code>```

I tried using -s option but not useful

```<code>if [ -s $file1 ]; then
   echo "file is non zero"
else
   echo "file is empty"
fi
</code>```

It always prints file is empty even though file is not empty.

答:
```<code>unzip -l empty_file_test.zip | awk 'NR>=4{if($1==0){print $4}}'
</code>```

may work for you, which could also be written as

```<code>unzip -l empty_file_test.zip | awk 'NR >= 4 && $1==0{print $4}'
</code>```

Body:
I want to check files inside the zip are not empty. I know the unzip -l command but it gives lot of information.

[abc@localhost test]$ unzip -l empty_file_test.zip
Archive:  empty_file_test.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
    0      07-05-2017 06:43   empty_first_20170505.csv
    0      07-05-2017 06:43   empty_second_20170505.csv
---------                     -------
    0                         2 files

I extracted the file names from the zip file by command

file_names="$(unzip -Z1 empty_file_test.zip)
file_name_array=($file_names)
file1=${file_name_array[0]}
file2=${file_name_array[1]}

I tried using -s option but not useful

if [ -s $file1 ]; then
   echo "file is non zero"
else
   echo "file is empty"
fi

It always prints file is empty even though file is not empty.

Body:
unzip -l empty_file_test.zip | awk 'NR>=4{if($1==0){print $4}}'

may work for you, which could also be written as

unzip -l empty_file_test.zip | awk 'NR >= 4 && $1==0{print $4}'


问:
Show/hide a record based on condition inside ng-repeat not working
Below are my records :

```<code>$scope.currentSelection = "Admin";

$scope.records = [
     { id: 'Employee', params:[]},
     { id: 'Skills', params:[]},
     { id: 'Payroll', params:[]},
     { id: 'Appraisal', params:[]},
     { id : 'Statistics',params:[]}
];
</code>```

Now if $scope.currentSelection is admin then I want to show all items with statistics(Employee,Skills,Payroll,Appraisal,Statistics) else I don't want to show Statistics rest other items (Employee,Skills,Payroll,Appraisal) if $scope.currentSelection is Guest or Employee.

But the problem is when currentSelection is Admin then others items are not showing up except statistics.

Note: I don't want to use a filter for this.

But the problem

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {
     $scope.currentSelection = "Admin";
     $scope.records = [
          { id: 'Employee', params:[]},
          { id: 'Skills', params:[]},
          { id: 'Payroll', params:[]},
          { id: 'Appraisal', params:[]},
          { id : 'Statistics',params:[]}
     ];
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <ul ng-app="myApp" ng-controller="MyController">
     <li ng-repeat="item in records">
         <div ng-show="currentSelection=='Admin' && item.id=='Statistics'">{{item.id}}
         </div>
    </li>
</ul></code>```

答:
Use ng-if instance of ng-show

var app = angular.module("myApp", []);
        app.controller("MyController", function ($scope) {
            $scope.currentSelection = "Admin";

 $scope.records = [
{ id: 'Employee', params:[]},
{ id: 'Skills', params:[]},
{ id: 'Payroll', params:[]},
{ id: 'Appraisal', params:[]},
{ id : 'Statistics',params:[]}
];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyController">
 <ul  ng-repeat="item in records">
     <li ng-if="currentSelection === 'Admin' && item.id!=='Statistics'">
         <div>{{item.id}}</div>
    </li>
</ul>
</div></code>```

Body:
Below are my records :

$scope.currentSelection = "Admin";

$scope.records = [
     { id: 'Employee', params:[]},
     { id: 'Skills', params:[]},
     { id: 'Payroll', params:[]},
     { id: 'Appraisal', params:[]},
     { id : 'Statistics',params:[]}
];

Now if $scope.currentSelection is admin then I want to show all items with statistics(Employee,Skills,Payroll,Appraisal,Statistics) else I don't want to show Statistics rest other items (Employee,Skills,Payroll,Appraisal) if $scope.currentSelection is Guest or Employee.

But the problem is when currentSelection is Admin then others items are not showing up except statistics.

Note: I don't want to use a filter for this.

But the problem

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {
     $scope.currentSelection = "Admin";
     $scope.records = [
          { id: 'Employee', params:[]},
          { id: 'Skills', params:[]},
          { id: 'Payroll', params:[]},
          { id: 'Appraisal', params:[]},
          { id : 'Statistics',params:[]}
     ];
 });

{{item.id}}

Body:
Use ng-if instance of ng-show

var app = angular.module("myApp", []);
        app.controller("MyController", function ($scope) {
            $scope.currentSelection = "Admin";

 $scope.records = [
{ id: 'Employee', params:[]},
{ id: 'Skills', params:[]},
{ id: 'Payroll', params:[]},
{ id: 'Appraisal', params:[]},
{ id : 'Statistics',params:[]}
];
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyController">
 <ul  ng-repeat="item in records">
     <li ng-if="currentSelection === 'Admin' && item.id!=='Statistics'">
         <div>{{item.id}}</div>
    </li>
</ul>
</div>


问:
PHP, SQL Insert no works
i would like to know why i am not able to insert new data to my Database.
in vardump i get good result but nothing is added to my database

Database : c_id = AutoInc. | a_id | u_id | c_head | c_content | c_date
  =TIMESTAMP

```<code>if (isset($_POST['c_submit'])) {
   $sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '$_SESSION[username]'";
   $vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
   if (mysqli_num_rows($vysledokHladania) == 1) {
       while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
            $sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES ($_GET[a_id], $db_data_prihlaseneho_uzivatela[u_id], $_POST[c_hlavicka], $_POST[c_obsah], 'NOW()')";
            mysqli_query($connect_to_db, $sql_vloz_komentar);
        }
    }
}
</code>```

答:
do you escape the varchar character ?
Other posible error is the date format  in database.
Postecho $sql_vloz_komentar for view the insert statement and the structure of table

```<code>if (isset($_POST['c_submit'])) {
   $sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '$_SESSION[username]'";
   $vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
   if (mysqli_num_rows($vysledokHladania) == 1) {
       while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
            $sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES ($_GET[a_id], $db_data_prihlaseneho_uzivatela[u_id], '$_POST[c_hlavicka]', '$_POST[c_obsah]', 'NOW()')";
            mysqli_query($connect_to_db, $sql_vloz_komentar);
        }
    }
}
</code>```

Title: PHP, SQL Insert no works

Body:
i would like to know why i am not able to insert new data to my Database.
in vardump i get good result but nothing is added to my database

Database : c_id = AutoInc. | a_id | u_id | c_head | c_content | c_date
  =TIMESTAMP

if (isset($_POST['c_submit'])) {
   $sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '$_SESSION[username]'";
   $vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
   if (mysqli_num_rows($vysledokHladania) == 1) {
       while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
            $sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES ($_GET[a_id], $db_data_prihlaseneho_uzivatela[u_id], $_POST[c_hlavicka], $_POST[c_obsah], 'NOW()')";
            mysqli_query($connect_to_db, $sql_vloz_komentar);
        }
    }
}

Body:
do you escape the varchar character ?
Other posible error is the date format  in database.
Postecho $sql_vloz_komentar for view the insert statement and the structure of table

if (isset($_POST['c_submit'])) {
   $sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '$_SESSION[username]'";
   $vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
   if (mysqli_num_rows($vysledokHladania) == 1) {
       while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
            $sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES ($_GET[a_id], $db_data_prihlaseneho_uzivatela[u_id], '$_POST[c_hlavicka]', '$_POST[c_obsah]', 'NOW()')";
            mysqli_query($connect_to_db, $sql_vloz_komentar);
        }
    }
}


问:
How I install Multi vendor magento marketplace module extension?
I want to buy Multi vendor magento marketplace to convert my magento into multi vendor magento marketplace.
I have see "Medma Magento Marketplace Module extension" on magento store?

Do you have any previous experience with Medma Magento Marketplace Module extension.
If yes then please tell me how you Install it?
http://www.medma.net/knowledge-base/Magento-marketplace-module/2-14

答:
There few steps which help you to install Medma marketplace extension on Magento store:

Login to your website as admin and navigate to “System -> Magento
Connect -> Magento Connect Manager”.

Choose the downloaded extension zip (Medma marketplace) file and
click on “Upload” button, under “Direct package file upload” section.

After completion of installation logout and login again as admin.
Navigation to Medma -> MarketPlace on the Navigation Menu


问:
JQuery tooltip that supports new line
I'm looking for a lightweight jquery plugin for displaying tooltips when the user hovers over an element. I would like the plugin to get the content from the title attribute and also it's important that I can make new lines.

Any help is appreciated!

答:
Simple custom jQuery extension:

```<code>$.fn.extend({
  myToolTip: function() {
    this.hover(
      // mouse in ...
      function () {
        var $this = $(this);
        if ($this.attr("title")) {
          $this.data("$tooltip", $("<div class='myToolTip'></div>")
            .text($this.attr("title"))
            .html(function(i, html) { return html.replace(/\n/g, "<br/>"); })
            .css({
              position: "absolute",
              top: $this.position().top + $this.outerHeight(),
              left: $this.position().left
            })
            .appendTo("body")
          );
        }
      },
      // mouse out ...
      function () {
        var $tooltip = $(this).data("$tooltip");
        if ($tooltip) $tooltip.remove();
      }
    );
  }
});
</code>```

This creates a
 (use CSS to style it) and positions it beneath the element in question on mouseenter. On mouseleave the tooltip is removed again. Line breaks in the element's title will become
 in the
's contents, everything else will appear verbatim.

Call the extension via $(".someElements").myToolTip();.

ContentLicense: CC BY-SA 2.5

Title: JQuery tooltip that supports new line

Body:
Simple custom jQuery extension:

$.fn.extend({
  myToolTip: function() {
    this.hover(
      // mouse in ...
      function () {
        var $this = $(this);
        if ($this.attr("title")) {
          $this.data("$tooltip", $("<div class='myToolTip'></div>")
            .text($this.attr("title"))
            .html(function(i, html) { return html.replace(/\n/g, "<br/>"); })
            .css({
              position: "absolute",
              top: $this.position().top + $this.outerHeight(),
              left: $this.position().left
            })
            .appendTo("body")
          );
        }
      },
      // mouse out ...
      function () {
        var $tooltip = $(this).data("$tooltip");
        if ($tooltip) $tooltip.remove();
      }
    );
  }
});

This creates a <div class="myToolTip"> (use CSS to style it) and positions it beneath the element in question on mouseenter. On mouseleave the tooltip is removed again. Line breaks in the element's title will become <br> in the <div>'s contents, everything else will appear verbatim.

Call the extension via $(".someElements").myToolTip();.


问:
SparkJava with AppEngine on Gradle
I create new project based on Google Tutorial and switch to Java 1.8,
add SparkJava dependencies:

```<code>dependencies {
    compile 'com.google.appengine:appengine:+'
    compile 'com.sparkjava:spark-core:2.5.5'
    compile 'com.google.cloud:google-cloud-datastore:0.13.0-beta'
}
</code>```

and create web.xml configuration based on SparkJava documentation:

```<code><web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
    <filter>
        <filter-name>SparkFilter</filter-name>
        <filter-class>spark.servlet.SparkFilter</filter-class>
        <init-param>
            <param-name>applicationClass</param-name>
            <param-value>me.drozdzynski.test.App</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>SparkFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
</code>```

after compile and start Local Google Development Server, I have error:

```<code>WARNING: failed JettyContainerService$ApiProxyHandler@14028087: java.lang.NoClassDefFoundError: java.util.Optional is a restricted class. Please see the Google  App Engine developer's guide for more details.
Apr 19, 2017 7:22:01 AM com.google.apphosting.utils.jetty.JettyLogger warn
WARNING: Error starting handlers
java.lang.NoClassDefFoundError: java.util.Optional is a restricted class. Please see the Google  App Engine developer's guide for more details.
    at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:50)
    at spark.Service.<init>(Service.java:74)
    at spark.Service.ignite(Service.java:99)
    at spark.Spark$SingletonHolder.<clinit>(Spark.java:49)
    at spark.Spark.getInstance(Spark.java:53)
    at spark.Spark.<clinit>(Spark.java:59)
    at me.drozdzynski.test.App.init(App.java:11)
    at spark.servlet.SparkFilter.init(SparkFilter.java:69)
    at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:662)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.jetty.Server.doStart(Server.java:224)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:268)
    at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:284)
    at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
    at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:87)
    at com.google.appengine.tools.development.Modules.startup(Modules.java:105)
    at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:262)
    at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:45)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:217)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:215)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:215)
    at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:349)
    at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:47)
    at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:222)
    at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:213)
</code>```

答:
java8 now available on GAE, now all public JDK APIs are supported

https://cloud.google.com/appengine/docs/standard/java/runtime-java8

Title: SparkJava with AppEngine on Gradle

Body:
I create new project based on Google Tutorial and switch to Java 1.8,
add SparkJava dependencies:

dependencies {
    compile 'com.google.appengine:appengine:+'
    compile 'com.sparkjava:spark-core:2.5.5'
    compile 'com.google.cloud:google-cloud-datastore:0.13.0-beta'
}

and create web.xml configuration based on SparkJava documentation:

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
    <filter>
        <filter-name>SparkFilter</filter-name>
        <filter-class>spark.servlet.SparkFilter</filter-class>
        <init-param>
            <param-name>applicationClass</param-name>
            <param-value>me.drozdzynski.test.App</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>SparkFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

after compile and start Local Google Development Server, I have error:

WARNING: failed JettyContainerService$ApiProxyHandler@14028087: java.lang.NoClassDefFoundError: java.util.Optional is a restricted class. Please see the Google  App Engine developer's guide for more details.
Apr 19, 2017 7:22:01 AM com.google.apphosting.utils.jetty.JettyLogger warn
WARNING: Error starting handlers
java.lang.NoClassDefFoundError: java.util.Optional is a restricted class. Please see the Google  App Engine developer's guide for more details.
    at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:50)
    at spark.Service.<init>(Service.java:74)
    at spark.Service.ignite(Service.java:99)
    at spark.Spark$SingletonHolder.<clinit>(Spark.java:49)
    at spark.Spark.getInstance(Spark.java:53)
    at spark.Spark.<clinit>(Spark.java:59)
    at me.drozdzynski.test.App.init(App.java:11)
    at spark.servlet.SparkFilter.init(SparkFilter.java:69)
    at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:662)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.jetty.Server.doStart(Server.java:224)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:268)
    at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:284)
    at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
    at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:87)
    at com.google.appengine.tools.development.Modules.startup(Modules.java:105)
    at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:262)
    at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:45)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:217)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:215)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:215)
    at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:349)
    at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:47)
    at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:222)
    at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:213)


问:
Schemas installed with extension orafce on PostgreSQL
I installed orafce extension on PostgreSQL 9.5. I saw that it is better to create a specific schema for all extensions and that what I did. I connected to template 1 and performed the next commands :

```<code>template1=# create schema extensions;
CREATE SCHEMA
template1=# grant usage on schema extensions to public;
GRANT
template1=# grant execute on all functions in schema extensions to public;
GRANT
template1=# alter default privileges in schema extensions grant execute on
functions to public;
ALTER DEFAULT PRIVILEGES
template1=# alter default privileges in schema extensions grant usage on
types to public;
ALTER DEFAULT PRIVILEGES
template1=# create extension orafce schema extensions;
CREATE EXTENSION
template1=# show search_path;
search_path
 -----------------
"$user", public
(1 row)

template1=# set search_path="$user",public,extensions;
SET
</code>```

After that I created a new database test1 and a new user mariel1. In addition I edited postgresql.conf and set the search_path to be "$user",public,extensions.

I connected to the database - psql -d test1 -U mariel1. Now when I try to use the function sysdate for example the database doesn't recognize the function:

```<code>postgres=# select sysdate() from dual;
ERROR:  function sysdate() does not exist
LINE 1: select sysdate() from dual;
           ^
HINT:  No function matches the given name and argument types. You might need
to add explicit type casts.
postgres=# select extensions.sysdate() from dual;
ERROR:  schema "extensions" does not exist
LINE 1: select extensions.sysdate() from dual;
</code>```

After some searching I saw that some of the functions available under other schemas like oracle, utl_file and more. I want to understand why the functions of orafce (oracle.sysdate etc...) created under different schemas (oracle,utl_file..) and not under my new schema extensions.

答: Extension in PostgreSQL is Database level not schema level or instance level. You cannot create same Extension in same database. But you can create same extension in multiple databases. that's how extension in PostgreSQL work.

ContentLicense: CC BY-SA 4.0

Body:
I installed orafce extension on PostgreSQL 9.5. I saw that it is better to create a specific schema for all extensions and that what I did. I connected to template 1 and performed the next commands :

template1=# create schema extensions;
CREATE SCHEMA
template1=# grant usage on schema extensions to public;
GRANT
template1=# grant execute on all functions in schema extensions to public;
GRANT
template1=# alter default privileges in schema extensions grant execute on
functions to public;
ALTER DEFAULT PRIVILEGES
template1=# alter default privileges in schema extensions grant usage on
types to public;
ALTER DEFAULT PRIVILEGES
template1=# create extension orafce schema extensions;
CREATE EXTENSION
template1=# show search_path;
search_path
 -----------------
"$user", public
(1 row)

template1=# set search_path="$user",public,extensions;
SET

After that I created a new database test1 and a new user mariel1. In addition I edited postgresql.conf and set the search_path to be "$user",public,extensions.

I connected to the database - psql -d test1 -U mariel1. Now when I try to use the function sysdate for example the database doesn't recognize the function:

postgres=# select sysdate() from dual;
ERROR:  function sysdate() does not exist
LINE 1: select sysdate() from dual;
           ^
HINT:  No function matches the given name and argument types. You might need
to add explicit type casts.
postgres=# select extensions.sysdate() from dual;
ERROR:  schema "extensions" does not exist
LINE 1: select extensions.sysdate() from dual;

After some searching I saw that some of the functions available under other schemas like oracle, utl_file and more. I want to understand why the functions of orafce (oracle.sysdate etc...) created under different schemas (oracle,utl_file..) and not under my new schema extensions.


问:
Array.at(index) over Array[index]
I start to learn std::array and found function to access array with .at(index of element). Is there any reason to it over array.[index of element] style?(e.g speed, exception or other).

答:
Consider (link)

```<code>const_reference operator[](size_type pos) const;
</code>```

and (link)

```<code>const_reference at(size_type pos) const;
</code>```

They both return a reference to the element at the specified location: pos. However, the former does not perform bounds checking, whereas the latter does.
In case !(pos < size()) the latter will throw an std::out_of_range exception.

Title: Array.at(index) over Array[index]

Body:
Consider (link)

const_reference operator[](size_type pos) const;

and (link)

const_reference at(size_type pos) const;

They both return a reference to the element at the specified location: pos. However, the former does not perform bounds checking, whereas the latter does.
In case !(pos < size()) the latter will throw an std::out_of_range exception.


问:
Generator expressions Python
I have a list of dictionaries like the following:

```<code>lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]
</code>```

I wrote a generator expression like:

```<code>next((itm for itm in lst if itm['a']==5))
</code>```

Now the strange part is that though this works for the key value pair of 'a'
it throws an error for all other expressions the next time.
Expression:

```<code>next((itm for itm in lst if itm['b']==6))
</code>```

Error:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
KeyError: 'b'
</code>```

答:
Obviously itm['b'] will raise a KeyError if there is no 'b' key in a dictionary. One way would be to do

```<code>next((itm for itm in lst if 'b' in itm and itm['b']==6))
</code>```

If you don't expect None in any of the dictionaries then you can simplify it to

```<code>next((itm for itm in lst if itm.get('b')==6))
</code>```

(this will work the same since you compare to 6, but it would give wrong result if you would compare to None)

or safely with a placeholder

```<code>PLACEHOLDER = object()
next((itm for itm in lst if itm.get('b', PLACEHOLDER)==6))
</code>```

Title: Generator expressions Python

Body:
I have a list of dictionaries like the following:

lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]

I wrote a generator expression like:

next((itm for itm in lst if itm['a']==5))

Now the strange part is that though this works for the key value pair of 'a'
it throws an error for all other expressions the next time.
Expression:

next((itm for itm in lst if itm['b']==6))

Error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
KeyError: 'b'

Body:
Obviously itm['b'] will raise a KeyError if there is no 'b' key in a dictionary. One way would be to do

next((itm for itm in lst if 'b' in itm and itm['b']==6))

If you don't expect None in any of the dictionaries then you can simplify it to

next((itm for itm in lst if itm.get('b')==6))

(this will work the same since you compare to 6, but it would give wrong result if you would compare to None)

or safely with a placeholder

PLACEHOLDER = object()
next((itm for itm in lst if itm.get('b', PLACEHOLDER)==6))


问:
Here FindSequence Limit Waypoint
I need to get an optimized sequence of a route with up to max 120 waypoints.

I was trying to use "Here API" but with trial plan (I guess) even though I enter 10/20/30/40 destinations (waypoints), it always calculates only the top 5 destinations.

Is a plan problem?

thanks!

Maurizio

答:
I'm using it successfully with up to 119 waypoints. I'm a customer (not trial).

Endpoint I'm using:  https://wse.api.here.com/2/findsequence.json

Hope it helps

Title: Here FindSequence Limit Waypoint


问:
Random data in Unit Tests?
I have a coworker who writes unit tests for objects which fill their fields with random data. His reason is that it gives a wider range of testing, since it will test a lot of different values, whereas a normal test only uses a single static value.

I've given him a number of different reasons against this, the main ones being:

random values means the test isn't truly repeatable (which also means that if the test can randomly fail, it can do so on the build server and break the build)

if it's a random value and the test fails, we need to a) fix the object and b) force ourselves to test for that value every time, so we know it works, but since it's random we don't know what the value was

Another coworker added:

If I am testing an exception, random values will not ensure that the test ends up in the expected state

random data is used for flushing out a system and load testing, not for unit tests

Can anyone else add additional reasons I can give him to get him to stop doing this?

(Or alternately, is this an acceptable method of writing unit tests, and I and my other coworker are wrong?)

答: One advantage for someone looking at the tests is that arbitrary data is clearly not important. I've seen too many tests that involved dozens of pieces of data and it can be difficult to tell what needs to be that way and what just happens to be that way. E.g. If an address validation method is tested with a specific zip code and all other data is random then you can be pretty sure the zip code is the only important part.</p>

OwnerDisplayName: Adam V

Title: Random data in Unit Tests?

LastEditorDisplayName: travis


答:
That's not weird. For every itm in the lst. It will first evaluate the filter clause. Now if the filter clause is itm['b'] == 6, it will thus try to fetch the 'b' key from that dictionary. But since the first dictionary has no such key, it will raise an error.

For the first filter example, that is not a problem, since the first dictionary has an 'a' key. The next(..) is only interested in the first element emitted by the generator. So it never asks to filter more elements.

You can use .get(..) here to make the lookup more failsafe:

```<code>next((itm for itm in lst if itm<b>.get('b',None)</b>==6))</code>```

In case the dictionary has no such key, the .get(..) part will return None. And since None is not equal to 6, the filter will thus omit the first dictionary and look further for another match. Note that if you do not specify a default value, None is the default value, so an equivalent statement is:

```<code>next((itm for itm in lst if itm.get('b')==6))</code>```

We can also omit the parenthesis of the generator: only if there are multiple arguments, we need these additional parenthesis:

```<code>next(itm for itm in lst if itm.get('b')==6)</code>```

Title: Generator expressions Python

Body:
That's not weird. For every itm in the lst. It will first evaluate the filter clause. Now if the filter clause is itm['b'] == 6, it will thus try to fetch the 'b' key from that dictionary. But since the first dictionary has no such key, it will raise an error.

For the first filter example, that is not a problem, since the first dictionary has an 'a' key. The next(..) is only interested in the first element emitted by the generator. So it never asks to filter more elements.

You can use .get(..) here to make the lookup more failsafe:

next((itm for itm in lst if itm.get('b',None)==6))

In case the dictionary has no such key, the .get(..) part will return None. And since None is not equal to 6, the filter will thus omit the first dictionary and look further for another match. Note that if you do not specify a default value, None is the default value, so an equivalent statement is:

next((itm for itm in lst if itm.get('b')==6))

We can also omit the parenthesis of the generator: only if there are multiple arguments, we need these additional parenthesis:

next(itm for itm in lst if itm.get('b')==6)


问:
#<NoMethodError: undefined method `any?' for nil:NilClass>
I am trying to build a simple app using datamapper with multiple data models. At one time, I it working were I had a parent and a child model that were associated.  However, I have messed something up and cannot get one of my two models to work.  I will the simplified code I am using to just try and see if the second model(called Songs) is working.  The routes for the model titled Soundtrack work.

This is my first time posting, so apologize in advance if I have not shared enough.  Just let me know and I will add more.

Jon

Model and Routes:

```<code>require 'data_mapper'
require 'dm-timestamps'

#models

configure :development do
  DataMapper.setup(:default, "sqlite3://#{ Dir.pwd}/development.db")
end

configure :production do
  DataMapper.setup(:default, ENV['DATABASE_URL'])
end

class Soundtrack
  include DataMapper::Resource
  property :id, Serial
  property :genre, String
  property :tagline, String
  property :created_at, DateTime
  property :title, String
  property :createdby, String
end

class Songs
  include DataMapper::Resource
  property :id, Serial
  property :songtitle, String
  property :artist, String
  property :scene, String
end

DataMapper.finalize

configure :development do
  DataMapper.auto_migrate!
end

#Routes

get '/soundtrack' do
  @soundtrack = Soundtrack.all
  slim :soundtrack
end

get '/singletrack' do
  @songs = Songs.all
  slim :singletrack
end

get '/soundtrack/new' do
  @soundtrack = Soundtrack.new
  slim :new_soundtrack
end

get '/soundtrack/:id' do
  @soundtrack = Soundtrack.get(params[:id])
  slim :show_soundtrack
end

get '/soundtrack/:id/edit' do
  @soundtrack = Soundtrack.get(params[:id])
  slim :edit_soundtrack
end

post '/soundtrack' do
  @soundtrack = Soundtrack.create(params[:soundtrack])
  redirect to("/soundtrack/#{@soundtrack.id}")
end

post '/soundtrack/:id' do
   @soundtrack = Soundtrack.get(params[:id]).songinfo.create params['songinfo']
   redirect back
end

post '/songs/:id' do
   @songs = Songs.create(params[:songs])
   redirect back
end

put '/soundtrack/:id' do
    soundtrack = Soundtrack.get(params[:id])
    soundtrack.update(params[:soundtrack])
    redirect to('/soundtrack/[:id]')
end

delete '/soundtrack/:id' do
    Soundtrack.get(params[:id]).destroy
    redirect to('/soundtrack')
end

delete '/songinfo/:id' do
    Songinfo.get(params[:id]).destroy
    redirect back
end
</code>```

HTML (Slim):

```<code>.frame
  .row
    <div class="table-responsive">
      <table class="table">
        thead.background-black
          <tr>
            th.text-title Song
            th.text-title Artist
            th.text-title Scene

          </tr>
        </thead>
        <tbody>
           - if @songs.any?
            tr#songs
              -@songs.each do |songs|
                tr
                  th #{songs.songtitle}
                  th #{soundtrack.artist}
                  th #{soundtrack.scene}
                </tr>
           - else
             tr
               th  No songs have been created yet!
        </tbody>
      </table>
    </div>

    .col-md-2
.col-md-10
  pre.pre-black

    row
      form-horizontal
        form-group
           col-sm-2
             label for="Song Title"
               p.text-title.form-lower Soundtrack Title
             col-sm-2
               input.form-control type="string" name="songs[songtitle]" value="#{@songs.songtitle}"

    row
      form-horizontal
        form-group
          col-sm-2
            label for="Song Artist"
             p.text-title.form-lower Song Artist
            col-sm-10
            input.form-control type="string" name="songs[artist]" value="#{@songs.artist}"

    row
      form-horizontal
        form-group
          col-sm-2
            label for="Scene"
              p.text-title.form-lower Scene in Moveie
          col-sm-10
            input.form-control type="string" name="songs[scene]" value="#{@songs.scene}"

    .col-md-6
      h3.bump class==current?("/songs") Add A New Song
      .form method="POST" action="/songs"
        input.lower.link-size type="submit" class="text-center" value="Save Song"
</code>```

Gem File:

```<code>source :rubygems
gem "sinatra"
gem "slim"
gem "data_mapper"
gem "dm-timestamps"
gem "thin"
gem "dm-postgres-adapter", :group => :production
gem "dm-sqlite-adapter", :group => :development
gem 'pg', '~> 0.18.4'
</code>```

答:
Check using

```<code>@songs.present?
</code>```

To learn more about any?, present?, empty?, blank? look at this link.

Body:
I am trying to build a simple app using datamapper with multiple data models. At one time, I it working were I had a parent and a child model that were associated.  However, I have messed something up and cannot get one of my two models to work.  I will the simplified code I am using to just try and see if the second model(called Songs) is working.  The routes for the model titled Soundtrack work.

This is my first time posting, so apologize in advance if I have not shared enough.  Just let me know and I will add more.

Jon

Model and Routes:

require 'data_mapper'
require 'dm-timestamps'

#models

configure :development do
  DataMapper.setup(:default, "sqlite3://#{ Dir.pwd}/development.db")
end

configure :production do
  DataMapper.setup(:default, ENV['DATABASE_URL'])
end

class Soundtrack
  include DataMapper::Resource
  property :id, Serial
  property :genre, String
  property :tagline, String
  property :created_at, DateTime
  property :title, String
  property :createdby, String
end

class Songs
  include DataMapper::Resource
  property :id, Serial
  property :songtitle, String
  property :artist, String
  property :scene, String
end

DataMapper.finalize

configure :development do
  DataMapper.auto_migrate!
end

#Routes

get '/soundtrack' do
  @soundtrack = Soundtrack.all
  slim :soundtrack
end

get '/singletrack' do
  @songs = Songs.all
  slim :singletrack
end

get '/soundtrack/new' do
  @soundtrack = Soundtrack.new
  slim :new_soundtrack
end

get '/soundtrack/:id' do
  @soundtrack = Soundtrack.get(params[:id])
  slim :show_soundtrack
end

get '/soundtrack/:id/edit' do
  @soundtrack = Soundtrack.get(params[:id])
  slim :edit_soundtrack
end

post '/soundtrack' do
  @soundtrack = Soundtrack.create(params[:soundtrack])
  redirect to("/soundtrack/#{@soundtrack.id}")
end

post '/soundtrack/:id' do
   @soundtrack = Soundtrack.get(params[:id]).songinfo.create params['songinfo']
   redirect back
end

post '/songs/:id' do
   @songs = Songs.create(params[:songs])
   redirect back
end

put '/soundtrack/:id' do
    soundtrack = Soundtrack.get(params[:id])
    soundtrack.update(params[:soundtrack])
    redirect to('/soundtrack/[:id]')
end

delete '/soundtrack/:id' do
    Soundtrack.get(params[:id]).destroy
    redirect to('/soundtrack')
end

delete '/songinfo/:id' do
    Songinfo.get(params[:id]).destroy
    redirect back
end

HTML (Slim):

.frame
  .row

        thead.background-black

            th.text-title Song
            th.text-title Artist
            th.text-title Scene

           - if @songs.any?
            tr#songs
              -@songs.each do |songs|
                tr
                  th #{songs.songtitle}
                  th #{soundtrack.artist}
                  th #{soundtrack.scene}

           - else
             tr
               th  No songs have been created yet!

    .col-md-2
.col-md-10
  pre.pre-black

    row
      form-horizontal
        form-group
           col-sm-2
             label for="Song Title"
               p.text-title.form-lower Soundtrack Title
             col-sm-2
               input.form-control type="string" name="songs[songtitle]" value="#{@songs.songtitle}"

    row
      form-horizontal
        form-group
          col-sm-2
            label for="Song Artist"
             p.text-title.form-lower Song Artist
            col-sm-10
            input.form-control type="string" name="songs[artist]" value="#{@songs.artist}"

    row
      form-horizontal
        form-group
          col-sm-2
            label for="Scene"
              p.text-title.form-lower Scene in Moveie
          col-sm-10
            input.form-control type="string" name="songs[scene]" value="#{@songs.scene}"

    .col-md-6
      h3.bump class==current?("/songs") Add A New Song
      .form method="POST" action="/songs"
        input.lower.link-size type="submit" class="text-center" value="Save Song"

Gem File:

source :rubygems
gem "sinatra"
gem "slim"
gem "data_mapper"
gem "dm-timestamps"
gem "thin"
gem "dm-postgres-adapter", :group => :production
gem "dm-sqlite-adapter", :group => :development
gem 'pg', '~> 0.18.4'

Body:
Check using

@songs.present?

To learn more about any?, present?, empty?, blank? look at this link.


问:
How to get radio button selected value from dynamically generated radio buttons?
Hi I am developing web application in angularjs. I am generating radiobuttons dynamically using ng-repeat as below.

```<code><ul>
    <li ng-repeat="level in permissions">
        <input name="level.perm_levelname" type="radio" ng-model="level.perm_levelname" value="{{level.perm_levelname}}"> {{level.perm_levelname}}
        <a ng-click="gotopermMap({permisssionID: level.id})">View</a>
    </li>
</ul>
<input type="button" value="APPLY" ng-click="apply()" />
</code>```

I am trying to get selected radio button as below.

```<code> $scope.apply=function()
        {
            var permname = $scope.name;
            console.log($scope.level.perm_levelname);
        }
</code>```

I am getting error  Cannot read property 'perm_levelname' of undefined. May i get help here to get selected radio button? Thank you

答:
Use ng-click event for radio button to get current selected value and assign the value a scope object. then get the value from saved scope abject while you click apply button.

DEMO:

function TodoCtrl($scope) {

$scope.permissions= [{perm_levelname:"hai"},{perm_levelname:"bye"},{perm_levelname:"come"},{perm_levelname:"go"}]
      $scope.apply=function()
        {
        alert($scope.currecntClickValue);
        }
         $scope.currecntClick=function(currecntClickValue)
         {
          $scope.currecntClickValue=currecntClickValue.perm_levelname;
         }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">
 <ul>
     <li ng-repeat="level in permissions">
       <input name="groupName" type="radio" ng-click="currecntClick(level)" ng-value="level.perm_levelname">
       {{level.perm_levelname}}
       View
     </li>
   </ul>
   <input type="button" value="APPLY" ng-click="apply()"/>
  </div>
</div></code>```

Body:
Hi I am developing web application in angularjs. I am generating radiobuttons dynamically using ng-repeat as below.

        <input name="level.perm_levelname" type="radio" ng-model="level.perm_levelname" value="{{level.perm_levelname}}"> {{level.perm_levelname}}
        View

<input type="button" value="APPLY" ng-click="apply()" />

I am trying to get selected radio button as below.

 $scope.apply=function()
        {
            var permname = $scope.name;
            console.log($scope.level.perm_levelname);
        }

I am getting error  Cannot read property 'perm_levelname' of undefined. May i get help here to get selected radio button? Thank you

Body:
Use ng-click event for radio button to get current selected value and assign the value a scope object. then get the value from saved scope abject while you click apply button.

DEMO:

function TodoCtrl($scope) {

$scope.permissions= [{perm_levelname:"hai"},{perm_levelname:"bye"},{perm_levelname:"come"},{perm_levelname:"go"}]
      $scope.apply=function()
        {
        alert($scope.currecntClickValue);
        }
         $scope.currecntClick=function(currecntClickValue)
         {
          $scope.currecntClickValue=currecntClickValue.perm_levelname;
         }
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">
 <ul>
     <li ng-repeat="level in permissions">
       <input name="groupName" type="radio" ng-click="currecntClick(level)" ng-value="level.perm_levelname">
       {{level.perm_levelname}}
       <a href="#" ng-click="gotopermMap({permisssionID: level.id})">View</a>
     </li>
   </ul>
   <input type="button" value="APPLY" ng-click="apply()"/>
  </div>
</div>


问:
didSelectItemAtIndexPath: sometimes not called
I have a strange behaviour of my UICollectionView. Sometimes didSelectItemAtIndexPath: not called. But if I select another item and them I'm available to click previous item.

Delegates are ok.

Gesture recognizers are disabled

UICollectionView is in front. Nothing before this

My Code:

```<code>- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.activeCollectionViewObjects.count > section) {
            NSArray *array = self.activeCollectionViewObjects[section];
            return array.count;
        }
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    VenueLayoutCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kVenueLayoutCellReuseIdentifier forIndexPath:indexPath];
    self.activeCollectionViewCellsDictionary[indexPath] = cell;
    if (self.activeCollectionViewObjects.count > indexPath.section) {
        NSArray *rows = self.activeCollectionViewObjects[indexPath.section];
        if (rows.count > indexPath.row) {
            if ([rows[indexPath.row] isKindOfClass:[VenueLayoutCellObject class]]) {
                VenueLayoutCellObject *object = rows[indexPath.row];
                cell.cellObject = object;

            }
        }
    }
    [cell layoutIfNeeded];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
   NSLog(@"hello");
}
</code>```

Where could I be wrong? Thanks in advance

Gesture Recognizers are disabled now. I've set the breakpoint and they doesn't hire

答:
make sure to call the proper CollectionView delegate

```<code>- (void)collectionView:(UICollectionView *)collectionView     didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
</code>```

You may be calling

```<code>- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;
</code>```

Body:
I have a strange behaviour of my UICollectionView. Sometimes didSelectItemAtIndexPath: not called. But if I select another item and them I'm available to click previous item.

Delegates are ok.

Gesture recognizers are disabled

UICollectionView is in front. Nothing before this

My Code:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.activeCollectionViewObjects.count > section) {
            NSArray *array = self.activeCollectionViewObjects[section];
            return array.count;
        }
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    VenueLayoutCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kVenueLayoutCellReuseIdentifier forIndexPath:indexPath];
    self.activeCollectionViewCellsDictionary[indexPath] = cell;
    if (self.activeCollectionViewObjects.count > indexPath.section) {
        NSArray *rows = self.activeCollectionViewObjects[indexPath.section];
        if (rows.count > indexPath.row) {
            if ([rows[indexPath.row] isKindOfClass:[VenueLayoutCellObject class]]) {
                VenueLayoutCellObject *object = rows[indexPath.row];
                cell.cellObject = object;

            }
        }
    }
    [cell layoutIfNeeded];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
   NSLog(@"hello");
}

Where could I be wrong? Thanks in advance

Gesture Recognizers are disabled now. I've set the breakpoint and they doesn't hire

Body:
make sure to call the proper CollectionView delegate

- (void)collectionView:(UICollectionView *)collectionView     didSelectItemAtIndexPath:(NSIndexPath *)indexPath;

You may be calling

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;


问:
Can't load expo app: Something went wrong
I've created an expo app with exp init MyApp command and started it by running exp start in MyApp directory.

Then I'm scanning barcode which was printed in console with expo mobile app on android device.

Then "Something went wrong" screen is rendered instead of the app.

View log shows "Uncaught Error: Couldn't load exp://.....".

No errors in expo packager console output.

It used to work sometimes ago.

答: In my case, I had "host" set to 'localhost' in the XDE - which of course won't work on my physical device ;-) So, if you want to debug on a physical device, make sure your host is set to LAN instead. (Tunnel would work too, but would make debugging painstakingly slow)</p>


问:
Data is only loading on reload?
Im getting data from factory. after request im defining some properties.

```<code>http.get( 'app/propertyType/get.php').then(function (response)
             {

            if (response.data) {
                var data = response.data;

                dataFactory.propertyTypes = angular.extend({
                    asArray: data
                }
                });
            }
        });
 getPropertyTypes: function () {
                return this.propertyTypes;
            }
</code>```

Thats how im getting in controller..

```<code>       $scope.propertyTypes = DataFactory.getPropertyTypes();
        $scope.$watch(function () {
            return DataFactory.getPropertyTypes();
        }, function (newValue) {
            if (newValue) {
                $scope.propertyTypes = newValue;
            }
        });
</code>```

so it needs a reload to successfully load data..how to solve this problem? whenever i change the route it should be already loaded in page.

答: To reload the state on any condition , you can use $state.reload();

Title: Data is only loading on reload?

Body:
Im getting data from factory. after request im defining some properties.

http.get( 'app/propertyType/get.php').then(function (response)
             {

            if (response.data) {
                var data = response.data;

                dataFactory.propertyTypes = angular.extend({
                    asArray: data
                }
                });
            }
        });
 getPropertyTypes: function () {
                return this.propertyTypes;
            }

Thats how im getting in controller..

       $scope.propertyTypes = DataFactory.getPropertyTypes();
        $scope.$watch(function () {
            return DataFactory.getPropertyTypes();
        }, function (newValue) {
            if (newValue) {
                $scope.propertyTypes = newValue;
            }
        });

so it needs a reload to successfully load data..how to solve this problem? whenever i change the route it should be already loaded in page.


问:
Highlight multiple fields on validate javascript
I want when textfields empty it will highlight it. Following is my code its only highlight one field at one time. If both fields empty it will highlight one field.

```<code><script>
function ValidateForm(){

    var summary=document.getElementById("<%=summary.ClientID%>");
    if (summary.value == "" && txtTest.value == "") {
        summary.style.backgroundColor = "Yellow";
        return false;
    }
    var txtTest = document.getElementById("<%=txtTest.ClientID%>");
    if (txtTest.value == "" ) {

        txtTest.style.backgroundColor = "Yellow";
        return false;
    }

   return true;

}
</script>
</code>```

Please help me to solve this problem. I don't want to use default validators.

答:
instead of returning false in error condition use flag to indicate error.

by default flag is true and if there is an  error  it should be set to false.

finally return error flag.

```<code> <script>
 function ValidateForm(){
var flag=true;
var summary=document.getElementById("<%=summary.ClientID%>");

if (summary.value == "" && txtTest.value == "") {
    summary.style.backgroundColor = "Yellow";
    flag=false;
}
var txtTest = document.getElementById("<%=txtTest.ClientID%>");
if (txtTest.value == "" ) {

    txtTest.style.backgroundColor = "Yellow";
    flag=false;
}

 return flag;

}
</script>
</code>```

Body:
I want when textfields empty it will highlight it. Following is my code its only highlight one field at one time. If both fields empty it will highlight one field.

Please help me to solve this problem. I don't want to use default validators.

Body:
instead of returning false in error condition use flag to indicate error.

by default flag is true and if there is an  error  it should be set to false.

finally return error flag.

 <script>
 function ValidateForm(){
var flag=true;
var summary=document.getElementById("<%=summary.ClientID%>");

if (summary.value == "" && txtTest.value == "") {
    summary.style.backgroundColor = "Yellow";
    flag=false;
}
var txtTest = document.getElementById("<%=txtTest.ClientID%>");
if (txtTest.value == "" ) {

    txtTest.style.backgroundColor = "Yellow";
    flag=false;
}

 return flag;

}
</script>


问:
sqlite3 Null Foreign Key won't be accepted through .import
I'm trying to populate a DB with some data and this particular Foreign Key can be present or empty (null?). Therefore, this is what I'm using:

```<code>PRAGMA foreign_keys=on;

CREATE TABLE TABLE1(t1 text NOT NULL, t2 text NOT NULL, fl1 float NOT NULL,
nullable_fk text NULL,
PRIMARY KEY (t1, t2), FOREIGN KEY (nullable_fk ) REFERENCES PARENT_TABLE(nullable_fk )
ON DELETE CASCADE ON UPDATE NO ACTION);

CREATE TABLE PARENT_TABLE(nullable_fk text NOT NULL, var integer, PRIMARY KEY (nullable_fk));
INSERT INTO PARENT_TABLE(nullable_fk, integer) VALUES ("asd", 123);

CREATE TABLE AUX_TABLE(t1 text NOT NULL, PRIMARY KEY (t1));
INSERT INTO AUX_TABLE(t1) VALUES ("bla");

INSERT INTO TABLE1(t1, t2, fl1, nullable_fk) VALUES ("bla", "bla", 1.1, NULL);
</code>```

This is working fine. However if I try importing, it will fail:

```<code>File being imported (file name test.txt):
"ble"^"646"^0.170^NULL

Commands being used:
.separator ^
.import test.txt TABLE1

RESULT -> test.txt:1: INSERT failed: FOREIGN KEY constraint failed
</code>```

If after that I try doing INSERT INTO with the values from the file, it will work just fine.

Does anyone knows what is the catch with the .import command?

Thanks!

EDIT: I've seen from other pages that importing NULL wont work from CSV files, which is kind of what I was trying to do, and the recommendation would be to put a value in there and update afterwards. However, since the Foreign Key must be present in the other table (PARENT_TABLE), would the correct way to do this be to create a "temporary garbage entry" in PARENT_TABLE, use this in place of the NULL keys, update the keys to NULL and then delete this entry from PARENT_TABLE?

Is there a better way?

答:
.import imports text files, so it is not possible to have NULL values: you get an empty string, or the string "NULL" if you try to spell it out.

You can import the file into a temporary table, adjust any 'wrong' values in there, and then copy to the actual table.

Alternatively, you can temporarily disable foreign key checking.

Body:
I'm trying to populate a DB with some data and this particular Foreign Key can be present or empty (null?). Therefore, this is what I'm using:

PRAGMA foreign_keys=on;

CREATE TABLE TABLE1(t1 text NOT NULL, t2 text NOT NULL, fl1 float NOT NULL,
nullable_fk text NULL,
PRIMARY KEY (t1, t2), FOREIGN KEY (nullable_fk ) REFERENCES PARENT_TABLE(nullable_fk )
ON DELETE CASCADE ON UPDATE NO ACTION);

CREATE TABLE PARENT_TABLE(nullable_fk text NOT NULL, var integer, PRIMARY KEY (nullable_fk));
INSERT INTO PARENT_TABLE(nullable_fk, integer) VALUES ("asd", 123);

CREATE TABLE AUX_TABLE(t1 text NOT NULL, PRIMARY KEY (t1));
INSERT INTO AUX_TABLE(t1) VALUES ("bla");

INSERT INTO TABLE1(t1, t2, fl1, nullable_fk) VALUES ("bla", "bla", 1.1, NULL);

This is working fine. However if I try importing, it will fail:

File being imported (file name test.txt):
"ble"^"646"^0.170^NULL

Commands being used:
.separator ^
.import test.txt TABLE1

RESULT -> test.txt:1: INSERT failed: FOREIGN KEY constraint failed

If after that I try doing INSERT INTO with the values from the file, it will work just fine.

Does anyone knows what is the catch with the .import command?

Thanks!

EDIT: I've seen from other pages that importing NULL wont work from CSV files, which is kind of what I was trying to do, and the recommendation would be to put a value in there and update afterwards. However, since the Foreign Key must be present in the other table (PARENT_TABLE), would the correct way to do this be to create a "temporary garbage entry" in PARENT_TABLE, use this in place of the NULL keys, update the keys to NULL and then delete this entry from PARENT_TABLE?

Is there a better way?


问:
Query Join Condition
I Have two tables named account and assignedgroup. In account table there are two columns named ID and sourceaccount and In assignedgroup I have two columns named ID and assignedgroup.

I want to select ID by joining account and assignedgroup tables. I did something like this:

```<code>select a.ID
from account a
  left outer join assignedgroup b
   on a.sourceaccount = b.assignedgorup
</code>```

But I get Null as output the reason being that The values in sourceaccount are like this

sourceaccount:

```<code>sample
sample
</code>```

and whereas the values in assignedgroup are like this

assignedgroup:

```<code>sample-L1
sample-P-L1
</code>```

Can anyone help me on how to join these two tables?

I want to get all the ID's whenever there is a sample value in both sourceaccount and assignedgroup.

It is comparing sample with sample-L1 since those are not equal it is returning null but I want the ID even if it has values like that. I mean if somepart of the column values matches then also I want those values to be displayed

答:
```<code>SELECT  a.id
FROM    account a
LEFT JOIN
        assignedgroup b
ON      b.assignedgorup LIKE a.sourceaccount + '-%'
</code>```

Title: Query Join Condition

Body:
I Have two tables named account and assignedgroup. In account table there are two columns named ID and sourceaccount and In assignedgroup I have two columns named ID and assignedgroup.

I want to select ID by joining account and assignedgroup tables. I did something like this:

select a.ID
from account a
  left outer join assignedgroup b
   on a.sourceaccount = b.assignedgorup

But I get Null as output the reason being that The values in sourceaccount are like this

sourceaccount:

sample
sample

and whereas the values in assignedgroup are like this

assignedgroup:

sample-L1
sample-P-L1

Can anyone help me on how to join these two tables?

I want to get all the ID's whenever there is a sample value in both sourceaccount and assignedgroup.

It is comparing sample with sample-L1 since those are not equal it is returning null but I want the ID even if it has values like that. I mean if somepart of the column values matches then also I want those values to be displayed


问:
The module ".dll" was loaded but the entry-point was not found
I have a DLL which cause to an error when I run the application.
The error says that the service is not registered. So I run command regsvr32 with the name of the DLL.
But it gives me an error, now the error is:

The module 'mydll.dll' was loaded but the entry-point 'DllRegisterServer' was not found.

Make sure that 'mydll.dll' is a valid DLL or OCX file and then try again

I worked on Windows 7 64-bit. On Windows XP it works fine!.
Does someone know what it can be?
Thanks!

答:
What solved it for me was using :

regasm.exe 'xx.dll' /tlb /codebase /register

It is however, important to understand the difference between regasm.exe and regsvr.exe:

What is difference between RegAsm.exe and regsvr32? How to generate a tlb file using regsvr32?


答:
first you should get txtTest var before evaluating it,
then instead of returning after each if, do it at bottom for validation</p>

```<code>var summary=document.getElementById("<%=summary.ClientID%>");
var txtTest = document.getElementById("<%=txtTest.ClientID%>");

if (summary.value == "") {
    summary.style.backgroundColor = "Yellow";
}

if (txtTest.value == "" ) {
    txtTest.style.backgroundColor = "Yellow";
}
return !(summary.value == "" || txtTest.value == "")
</code>```

Title: Highlight multiple fields on validate javascript

Body:
first you should get txtTest var before evaluating it,
then instead of returning after each if, do it at bottom for validation

var summary=document.getElementById("<%=summary.ClientID%>");
var txtTest = document.getElementById("<%=txtTest.ClientID%>");

if (summary.value == "") {
    summary.style.backgroundColor = "Yellow";
}

if (txtTest.value == "" ) {
    txtTest.style.backgroundColor = "Yellow";
}
return !(summary.value == "" || txtTest.value == "")


问:
How to stop elements resizing when I change the zoom on page
I'm a newbie to HTML and CSS, facing a problem where when I resize my page, the elements go berserk. I've tried everything from creating a main wrapper and adding max widths and heights, but all to no avail. Here is my code in CSS so that you can take a look.</p>

```<code>body {
  background-image: url(3eMAHaa.jpg)
}

div.header {
  border: 1px solid black;
  border-radius: 50px;
  padding-top: 26%;
  padding-bottom: 26%;
  padding-left: 10%;
  padding-right: 10%
}

h1 {
  ;
  position: absolute;
  top: 30%;
  left: 40%;
  color: #FF2B24;
  font-family: helvetica
}

.someimage {
  position: absolute;
  top: 43%;
  left: 32%
}

div.navbox {
  border: 1px solid black;
  border-radius: 50px;
  padding-top: 70px;
  padding-bottom: 70px;
  padding-left: 500px;
  padding-right: 500px;
  position: absolute;
  top: 1%;
  right: 2%
}

img.about {
  border: 1px solid gray;
  position: absolute;
  right: 80%;
  top: 35%
}

}
img.location {
  border: 1px solid gray;
  position: absolute
}
img.contact {
  border: 1px solid gray;
  position: absolute;
  right: 15%;
  top: 35%
}
</code>```

答: Never mind guys, figured it out. I had to set a a bigger DIV as a parent and then change all the other elements to relative positioning so they wouldn't move about. It was a hassle, but it worked! :). Also, try to use pixels instead of % as percentages aren't fixed values and will cause stuff to go crazy when you zoom.</p>

Body:
I'm a newbie to HTML and CSS, facing a problem where when I resize my page, the elements go berserk. I've tried everything from creating a main wrapper and adding max widths and heights, but all to no avail. Here is my code in CSS so that you can take a look.

body {
  background-image: url(3eMAHaa.jpg)
}

div.header {
  border: 1px solid black;
  border-radius: 50px;
  padding-top: 26%;
  padding-bottom: 26%;
  padding-left: 10%;
  padding-right: 10%
}

h1 {
  ;
  position: absolute;
  top: 30%;
  left: 40%;
  color: #FF2B24;
  font-family: helvetica
}

.someimage {
  position: absolute;
  top: 43%;
  left: 32%
}

div.navbox {
  border: 1px solid black;
  border-radius: 50px;
  padding-top: 70px;
  padding-bottom: 70px;
  padding-left: 500px;
  padding-right: 500px;
  position: absolute;
  top: 1%;
  right: 2%
}

img.about {
  border: 1px solid gray;
  position: absolute;
  right: 80%;
  top: 35%
}

}
img.location {
  border: 1px solid gray;
  position: absolute
}
img.contact {
  border: 1px solid gray;
  position: absolute;
  right: 15%;
  top: 35%
}


问:
T-SQL query to find jobs and tables
I want to find the sql server agent jobs that operate upon a particular table. For ex:
I have a table called TAB1 which is updated daily by a job called SAJ1. I need a query to extract this information.</p>

答:
One of the options available is the table msdb.dbo.sysjobsteps that enlists all the jobs and their steps. You can go into the Command column of the output and look for required information.

select * from msdb.dbo.sysjobsteps;

Title: T-SQL query to find jobs and tables


问:
Weighted Spearman rank correlation coefficient in R
This post provides a function for weighted Pearson correlation in R, i.e. function(x, y, weights). Is a corollary available for the Spearman rank correlation coefficient?

答:
Spearman's rank correlation coefficient r_s is calculated in the same way as Pearson's product moment correlation coefficient, except that ordinal rather than interval data are used. However, there is a way to calculate r_p using weights:

LaTeX:

```<code>\begin{align}
  \bar{x}  & = \frac{\sum_{i=1}^n{w_i x_i}}{\sum_{i=1}^n{w_i}} \quad
    \bar{y}   = \frac{\sum_{i=1}^n{w_i y_i}}{\sum_{i=1}^n{w_i}} \\
  s_{x,y}           & = \frac{\sum_{i=1}^n{w_i (x_i - \bar{x}_i) (y_i - \bar{y}_i)}}{\sum_{i=1}^n{w_i}} \quad
              s_x = \frac{\sum_{i=1}^n{w_i (x_i - \bar{x})}}{w_i} \quad
              s_y = \frac{\sum_{i=1}^n{w_i (y_i - \bar{y})}}{w_i} \\
  r(x,y,w) & = \frac{s_{x,y}}{\sqrt{s_x s_y}}
\end{align}
</code>```

equation

Body:
Spearman's rank correlation coefficient r_s is calculated in the same way as Pearson's product moment correlation coefficient, except that ordinal rather than interval data are used. However, there is a way to calculate r_p using weights:

LaTeX:

\begin{align}
  \bar{x}  & = \frac{\sum_{i=1}^n{w_i x_i}}{\sum_{i=1}^n{w_i}} \quad
    \bar{y}   = \frac{\sum_{i=1}^n{w_i y_i}}{\sum_{i=1}^n{w_i}} \\
  s_{x,y}           & = \frac{\sum_{i=1}^n{w_i (x_i - \bar{x}_i) (y_i - \bar{y}_i)}}{\sum_{i=1}^n{w_i}} \quad
              s_x = \frac{\sum_{i=1}^n{w_i (x_i - \bar{x})}}{w_i} \quad
              s_y = \frac{\sum_{i=1}^n{w_i (y_i - \bar{y})}}{w_i} \\
  r(x,y,w) & = \frac{s_{x,y}}{\sqrt{s_x s_y}}
\end{align}

equation


问:
how to manually create $this 2
I have function in JS that get the "$this".

I would like to use this function in another place. can i manually create "$this"?

please see the code:

```<code>function print_results(element) {
    var startRow    = element.attr("startRow");
    var maxRes      = element.attr("maxRes");
}

$(document).on("click", ".moreItins-btn", function(){
    print_results($(this));
});

$('#search-form').on('submit', function(e) {
$(this) = ....
print_results(HERE I WANT TO SENT THE SAME $THIS AS IN THE ABOVE CODE);
}
</code>```

答:
You can simple select that class

like

```<code>$('#search-form').on('submit', function(e) {
var moreItinsObject = $('.moreItins-btn');
print_results(HERE I WANT TO SENT THE SAME $THIS AS IN THE ABOVE CODE);
//here moreItinsObject is same as that $this
}
</code>```

I thing it will help you.

Title: how to manually create $this 2

Body:
I have function in JS that get the "$this".

I would like to use this function in another place. can i manually create "$this"?

please see the code:

function print_results(element) {
    var startRow    = element.attr("startRow");
    var maxRes      = element.attr("maxRes");
}

$(document).on("click", ".moreItins-btn", function(){
    print_results($(this));
});

$('#search-form').on('submit', function(e) {
$(this) = ....
print_results(HERE I WANT TO SENT THE SAME $THIS AS IN THE ABOVE CODE);
}

Body:
You can simple select that class

like

$('#search-form').on('submit', function(e) {
var moreItinsObject = $('.moreItins-btn');
print_results(HERE I WANT TO SENT THE SAME $THIS AS IN THE ABOVE CODE);
//here moreItinsObject is same as that $this
}

I thing it will help you.


问:
Appropriate encryption for financial data
I'm currently building a web application(PHP/MySQL) which saves data from persons. Most of this data is not worth protecting with encryption but some of it is financial information like income and so on. It is not a payment application and does not store information that could be turned into money directly like credit card information but still stuff you don't want to have in a possible leak. This platform has to be sold to customers that want "security", but that can mean anything as the customers themselves do not have any knowledge what they really want, since they are business people and not cryptographers(like me neither).

It is a management platform so the people that have their financial data saved there are not the users of the platform. Users of the platform are merely a login with permissions attached to them. The server itself never has to have access the data. Every operation is done by a user(could also be an admin) that is logged in. Multiple users need to have access to the same data given they have enough permissions.

My question is now how I can protect the financial data from these threats:

Somebody finds an SQL-injection and dumps all tables remotely

Somebody steals the hard drive of the server (database + code)

Where I'm certainly not going: Large scale sniffing attack or compromised servers(like sniffing all traffic on the server itself where SSL doesn't matter) or social engineering/phishing.

I would also like to have a quick summary how much more information(keys, data, etc.) I have to store in comparison to the current system, where there is one simple field for income etc. and a standard login system with username and hashed password.

EDIT: Reformulated question almost entirely following the suggestion of comments/answers

答:
Asymmetric encryption and hybrid encryption are pointless here unless the users generate and retain ownership of the private keys themselves.  I infer from the rest of your question that this isn't the case.

Assuming you want to be able to view this encrypted information without user interaction (e.g. you aren't just storing this information for the user and the information is relevant to your business operations), you have limited storage options.

If your exact threat model is to protect this data in the event of a database leak and nothing else, symmetric encryption is perfect, if properly implemented.

The implication of this is that the symmetric key must be stored on servers that make requests to the database and serve the data to your other (likely front-end) systems.  If any of those servers were to become compromised, then the encrypted data will be leaked.

In summary, use symmetric encryption, but understand that it will only protect you directly from a database leak through something like SQL injection or a similar attack.  A compromised server is a compromised server and generally means full data access given enough time.

EDIT: If you intend to require user interaction to view the secured data, then apokryfos's comment above accurately details what to do to secure the information.  Generate a symmetric key from the users password and use this to encrypt an additional symmetric key.  Use this secondary symmetric key to actually encrypt the data.  Using two keys makes a user password change easier.


问:
scala: best wat to save csv coming from kafka to parquet format?
I'm new to scala/java, so please bear with me.
I have a spark streaming and scala program that receives a csv file coming from kafka. I understand that what I get right now is a ReceiverInputDStream with plain lines (no schema yet).
I need to save the data I receive in parquet format in HDFS. I guess I could simply save the lines as they come in a parquet file (can I?).
But also I understand it's better to give some schema (columns and types) to the plain lines so parquet can convert the data to columnar format and achieve a better compression rate. Am I right?
So the question is, how do I convert my ReceiverInputDStream to something with a schema (column1 type1,... columnN typeN)? What object type is needed?
ANd then how do I save this new object to parquet?
Thank you.</p>

答:
If you happen to use Spark, you can do

```<code>spark.read.parquet(parquetPath).write.csv(newcsvPath)
</code>```

Or you can use the same thing but Spark Streaming as a Kafka client

Body:
If you happen to use Spark, you can do

spark.read.parquet(parquetPath).write.csv(newcsvPath)

Or you can use the same thing but Spark Streaming as a Kafka client


问:
espresso onView inconsistent performance
I am using Junit4 and Espresso for my tests. I am facing a weird issue with espresso tests - when I call onView sometimes everything is executed like it is supposed to, but sometimes my test freezes and after 60 seconds I get something like this "android.support.test.espresso.AppNotIdleException: Looped for 63 iterations over 60 SECONDS. The following Idle Conditions failed ASYNC_TASKS_HAVE_IDLED"
For example :

```<code>    onView(withId(R.id.zone_button_continue)).perform(click());
    onView(withId(R.id.loginButton)).check(matches(isDisplayed()));
    onView(withId(R.id.number)).check(matches(isDisplayed()));
    onView(withId(R.id.password)).check(matches(isDisplayed()));
    onView(withId(R.id.number)).perform(typeText(phoneNumber));
    onView(withId(R.id.password)).perform(typeText(password));
    onView(withId(R.id.loginButton)).perform(click());
</code>```

everything gets executed correctly, except the last line - for some reason it can't find that loginButton, but it is there 100% percent. I can do

```<code>activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            activity.findViewById(R.id.loginButton).performClick();
             }
    });
</code>```

and that works. I have similar problems throughout most of my activities -  sometimes onView is working sometimes not.

What could cause such an inconsistency? I have been fighting with this issue for a while, and it makes my testing very frustrating and difficult. My conclusions this far is that something is wrong with my gradle dependencies or there is some kind of bug in my application that prevents espresso to work properly. But it is strange that in the example above everything with onView is working except last line and everything is happening in one activity and that makes me doubt that the bug is within my application.
Here are my gradle dependencies:

```<code>compile files('src/main/libs/guice-3.0-no_aop.jar')
compile files('src/main/libs/javax.inject-1.jar')
compile files('src/main/libs/roboguice-2.0.jar')
compile files('src/main/libs/junit-4.11.jar')
compile files('src/main/libs/hamcrest-core-1.3.jar')
compile files('src/main/libs/GeoLib.jar')
compile files('src/main/libs/GeoPolygons.jar')
compile files('src/main/libs/universal-image-loader-1.9.4.jar')
compile files('src/main/libs/javax.annotation-3.2-b06-sources.jar')
compile ('uk.co.chrisjenx:calligraphy:2.1.0'){
    exclude group:'com.android.support'
}
compile 'com.squareup:otto:1.3.5'
compile ('com.google.android.gms:play-services:6.5.87'){
    exclude group:'com.android.support'
}
compile 'com.android.support:support-annotations:22.2.1'
compile ('com.android.support:appcompat-v7:22.2.0'){
    exclude group:'com.android.support'
}
compile ('com.android.support:support-v4:22.2.0'){
    exclude group:'com.android.support', module:'support-annotations'
}
compile ('com.android.support:palette-v7:22.2.0'){
    exclude group:'com.android.support'
}
compile 'com.google.code.findbugs:jsr305:2.0.1'

compile 'com.nineoldandroids:library:2.4.0'
compile 'pl.charmas.android:android-reactive-location:0.4@aar'
compile 'io.reactivex:rxjava:1.0.3'
compile files('src/main/libs/FlurryAnalytics-6.1.0.jar')
compile 'com.github.castorflex.smoothprogressbar:library:1.1.0'
//    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
androidTestCompile('com.android.support.test:runner:0.4.1') {
    exclude group: 'com.android.support', module: 'support-annotations'
}
// Set this dependency to use JUnit 4 rules
androidTestCompile('com.android.support.test:rules:0.4.1') {
    exclude group: 'com.android.support', module: 'support-annotations'
}
// Set this dependency to build and run Espresso tests
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1') {
    exclude group: 'com.android.support', module: 'support-annotations'
}

androidTestCompile('com.android.support.test.espresso:espresso-intents:2.2.1') {
    exclude group: 'com.android.support', module: 'support-annotations'
}
androidTestCompile('com.android.support.test.espresso:espresso-web:2.2.1') {
    // PackagingOptions modified to make this work
    exclude group: 'com.android.support', module: 'support-annotations'
}
testCompile 'junit:junit:4.11'
testCompile ('org.mockito:mockito-core:1.9.5'){
    exclude group: 'org.hamcrest'
}
compile 'org.mod4j.org.apache.commons:lang:2.1.0'
</code>```

Please help me with this problem, I am completely out of ideas and stuck with it.

答:
The easiest way to see why you get an AppNotIdleExceptionwith the message "The following Idle Conditions failed ASYNC_TASKS_HAVE_IDLED", is to:

Run the tests in debug mode in Android Studio

Wait until the tests hang

Before the (default) 60 seconds have passed, pause the tests

Look in the "Threads" list and see your threads named "AsyncTask #1" and so on. Expand the one being in state RUNNING. There you see what part of the code is keeping the app busy

This was the result for my case, so I had to disable the Facebook SDK for my tests to make them stable again:

Body:
I am using Junit4 and Espresso for my tests. I am facing a weird issue with espresso tests - when I call onView sometimes everything is executed like it is supposed to, but sometimes my test freezes and after 60 seconds I get something like this "android.support.test.espresso.AppNotIdleException: Looped for 63 iterations over 60 SECONDS. The following Idle Conditions failed ASYNC_TASKS_HAVE_IDLED"
For example :

    onView(withId(R.id.zone_button_continue)).perform(click());
    onView(withId(R.id.loginButton)).check(matches(isDisplayed()));
    onView(withId(R.id.number)).check(matches(isDisplayed()));
    onView(withId(R.id.password)).check(matches(isDisplayed()));
    onView(withId(R.id.number)).perform(typeText(phoneNumber));
    onView(withId(R.id.password)).perform(typeText(password));
    onView(withId(R.id.loginButton)).perform(click());

everything gets executed correctly, except the last line - for some reason it can't find that loginButton, but it is there 100% percent. I can do

activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            activity.findViewById(R.id.loginButton).performClick();
             }
    });

and that works. I have similar problems throughout most of my activities -  sometimes onView is working sometimes not.

What could cause such an inconsistency? I have been fighting with this issue for a while, and it makes my testing very frustrating and difficult. My conclusions this far is that something is wrong with my gradle dependencies or there is some kind of bug in my application that prevents espresso to work properly. But it is strange that in the example above everything with onView is working except last line and everything is happening in one activity and that makes me doubt that the bug is within my application.
Here are my gradle dependencies:

compile files('src/main/libs/guice-3.0-no_aop.jar')
compile files('src/main/libs/javax.inject-1.jar')
compile files('src/main/libs/roboguice-2.0.jar')
compile files('src/main/libs/junit-4.11.jar')
compile files('src/main/libs/hamcrest-core-1.3.jar')
compile files('src/main/libs/GeoLib.jar')
compile files('src/main/libs/GeoPolygons.jar')
compile files('src/main/libs/universal-image-loader-1.9.4.jar')
compile files('src/main/libs/javax.annotation-3.2-b06-sources.jar')
compile ('uk.co.chrisjenx:calligraphy:2.1.0'){
    exclude group:'com.android.support'
}
compile 'com.squareup:otto:1.3.5'
compile ('com.google.android.gms:play-services:6.5.87'){
    exclude group:'com.android.support'
}
compile 'com.android.support:support-annotations:22.2.1'
compile ('com.android.support:appcompat-v7:22.2.0'){
    exclude group:'com.android.support'
}
compile ('com.android.support:support-v4:22.2.0'){
    exclude group:'com.android.support', module:'support-annotations'
}
compile ('com.android.support:palette-v7:22.2.0'){
    exclude group:'com.android.support'
}
compile 'com.google.code.findbugs:jsr305:2.0.1'

compile 'com.nineoldandroids:library:2.4.0'
compile 'pl.charmas.android:android-reactive-location:0.4@aar'
compile 'io.reactivex:rxjava:1.0.3'
compile files('src/main/libs/FlurryAnalytics-6.1.0.jar')
compile 'com.github.castorflex.smoothprogressbar:library:1.1.0'
//    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
androidTestCompile('com.android.support.test:runner:0.4.1') {
    exclude group: 'com.android.support', module: 'support-annotations'
}
// Set this dependency to use JUnit 4 rules
androidTestCompile('com.android.support.test:rules:0.4.1') {
    exclude group: 'com.android.support', module: 'support-annotations'
}
// Set this dependency to build and run Espresso tests
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1') {
    exclude group: 'com.android.support', module: 'support-annotations'
}

androidTestCompile('com.android.support.test.espresso:espresso-intents:2.2.1') {
    exclude group: 'com.android.support', module: 'support-annotations'
}
androidTestCompile('com.android.support.test.espresso:espresso-web:2.2.1') {
    // PackagingOptions modified to make this work
    exclude group: 'com.android.support', module: 'support-annotations'
}
testCompile 'junit:junit:4.11'
testCompile ('org.mockito:mockito-core:1.9.5'){
    exclude group: 'org.hamcrest'
}
compile 'org.mod4j.org.apache.commons:lang:2.1.0'

Please help me with this problem, I am completely out of ideas and stuck with it.


问:
iTunes Connect SUBMIT button won't work
Basically I tap the submit button it spins and then goes back to the default state. I can't submit app...

I added eBay EPN stuff but that was the same as last build. + checking that I do have ads on the bottom (if that was the thing I'm getting auto-stopped by) did noting and the button still would not go. :(

How do I get this to work so I can submit my build...?

答:
it's hard to say what's exact problem,try below steps

Major thing is make sure you are using Safari browser for iTunes
connect process.It quite better than all others.

Sign out your iTunes connect account & try again the process.if possible then add new version of app.

If still you have the problem then no way Contact iTunes support team.

Title: iTunes Connect SUBMIT button won't work