问:
CS0411: The type arguments for method X cannot be inferred from the usage when building with TeamCity
This is a long shoot but I have run out of own ideas.

Recently my TeamCity builds have started to throw this error upon me:

File.cs(Row, Col): error CS0411:
  The type arguments for method
  'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,
  System.Func)' cannot be inferred from
  the usage. Try specifying the type
  arguments explicitly.

But there are no errors in my code (or project configuration).

It compiles just fine if I do it either from withing Visual Studio (2010) itself or using MSBuild just as the build agent would do. (Even on the build machine.)

Just for reference, the code looks something like this:

```<code> public ISet<Task> Tasks {get; set;}

 public IEnumerable<GradedTask> FindGradedTasks(){
    return Tasks.Select(GetResult).Where(t=>t.HasResult).ToList(); // error
 }

 public GradedTask GetResult(Task task) {
    return new GradedTask(this, task);
 }
</code>```

Anyone seen anything like this before?
What might be causing this behaviour?

答:
Seems like you are using ISet interface but it is defined only in .NET 4.0

TeamCity is absolutely right.
It is VS bug.
We are has been beaten by this. Accidentally Reshaper introduce Optional argument.
And VS compiles this just fine.
But TeamCity is not.

Body:
This is a long shoot but I have run out of own ideas.

Recently my TeamCity builds have started to throw this error upon me:

File.cs(Row, Col): error CS0411:
  The type arguments for method
  'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,
  System.Func)' cannot be inferred from
  the usage. Try specifying the type
  arguments explicitly.

But there are no errors in my code (or project configuration).

It compiles just fine if I do it either from withing Visual Studio (2010) itself or using MSBuild just as the build agent would do. (Even on the build machine.)

Just for reference, the code looks something like this:

 public ISet<Task> Tasks {get; set;}

 public IEnumerable<GradedTask> FindGradedTasks(){
    return Tasks.Select(GetResult).Where(t=>t.HasResult).ToList(); // error
 }

 public GradedTask GetResult(Task task) {
    return new GradedTask(this, task);
 }

Anyone seen anything like this before?
What might be causing this behaviour?


来源: stackexchange

问:
Azure SQL Server - New field caused error and Full Text Index drop on table
I just tried to add a new field to an existing table in Azure SQL Server using the designer GUI view (not pure T-SQL) of SSMS and got the following error:

'MyTable (dbo)' table saved successfully

Error creating or modifying full-text index FullText_for_[MyTable].

DBCC command ‘CALLFULLTEXT’ is not supported in this version of SQL Server

When I went back to the table, the field was added but the Full Text Index has disappeared. I have just had to re-create it. To confirm: the table already had a Full Text Index set up on it before I added the new field.

Is there anything I did wrong there? Anything I should be wary of? It's a little disconcerting that the table dropped the index.

Incidentally - I have prevent saving changes that require table re-creation unticked in options > designers. I understand this could give scope for the error I saw. If this was most likely the cause, how can a new field be added to a table seamlessly?

答:
Incidentally - I have prevent saving changes that require table re-creation unticked in options > designers. I understand this could give scope for the error I saw. If this was most likely the cause, how can a new field be added to a table seamlessly?

According to this article, if you set the saving changes that require table re-creation unticked in options in SSMS, if you change the table it will how “Saving changes is not permitted” error.

Is there anything I did wrong there? Anything I should be wary of? It's a little disconcerting that the table dropped the index.

According to this article:Current limitations of Full-Text Search capabilities in Azure SQL Database

```<code>Note that Azure SQL Database V12 Full-Text Search functionality represents a subset of the Microsoft SQL Server 2014 release
No support for installation or use of third party filters, including Office and .pdf.
Customers cannot manage service settings for fdhost, all configurations are being managed by the service.
Semantic search, thesaurus and search property lists syntax is not yet enabled.
</code>```

So I guess maybe something wrong with your sql query.

I have written a test demo on my computer(The version of the SSMS is 2014) and it works well. Hope it gives you some tips:

```<code>CREATE TABLE Persons2 (
    PersonID int IDENTITY(1,1) NOT NULL,
    LastName varchar(255),
    FirstName varchar(255),
);

CREATE FULLTEXT CATALOG Persons2_catalog;
GO

CREATE UNIQUE INDEX ui_PersonId ON Persons2(PersonID);

CREATE FULLTEXT INDEX ON Persons2
 (
  LastName
     Language 1033,
  FirstName
     Language 1033
 )
  KEY INDEX ui_PersonId
      ON Persons2_catalog;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Incidentally - I have prevent saving changes that require table re-creation unticked in options > designers. I understand this could give scope for the error I saw. If this was most likely the cause, how can a new field be added to a table seamlessly?

According to this article, if you set the saving changes that require table re-creation unticked in options in SSMS, if you change the table it will how “Saving changes is not permitted” error.

Is there anything I did wrong there? Anything I should be wary of? It's a little disconcerting that the table dropped the index.

According to this article:Current limitations of Full-Text Search capabilities in Azure SQL Database

Note that Azure SQL Database V12 Full-Text Search functionality represents a subset of the Microsoft SQL Server 2014 release
No support for installation or use of third party filters, including Office and .pdf.
Customers cannot manage service settings for fdhost, all configurations are being managed by the service.
Semantic search, thesaurus and search property lists syntax is not yet enabled.

So I guess maybe something wrong with your sql query.

I have written a test demo on my computer(The version of the SSMS is 2014) and it works well. Hope it gives you some tips:

CREATE TABLE Persons2 (
    PersonID int IDENTITY(1,1) NOT NULL,
    LastName varchar(255),
    FirstName varchar(255),
);

CREATE FULLTEXT CATALOG Persons2_catalog;
GO

CREATE UNIQUE INDEX ui_PersonId ON Persons2(PersonID);

CREATE FULLTEXT INDEX ON Persons2
 (
  LastName
     Language 1033,
  FirstName
     Language 1033
 )
  KEY INDEX ui_PersonId
      ON Persons2_catalog;


问:
Django Help: AttributeError: 'module' object has no attribute 'Charfield'
I have seen several similar posts of other attributes found but not this. New to Python and Django- I've done the first part of the several tutorials including Django's "Polls" tutorial and when it gets to the point where I syncdb for my app I invariably get 'AttributeError: 'module' object has no attribute CharField.

In models I have copied exactly as the tutorial says:

from django.db import models

```<code>class Poll(models.Model):
    question = models.Charfield(max_length=200)
    pub_date = models.DateTimeField('date published')
class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
# Create your models here.
</code>```

'polls' is also added to installed apps and I'm using sqlite3, windows 7, python 2.7.

Any help very appreciated! (I'm trying very hard to learn!)

答:
I think in forms.py you are using

```<code>from django.forms import forms
</code>```

Please use this

```<code>from django import forms
</code>```

Body:
I have seen several similar posts of other attributes found but not this. New to Python and Django- I've done the first part of the several tutorials including Django's "Polls" tutorial and when it gets to the point where I syncdb for my app I invariably get 'AttributeError: 'module' object has no attribute CharField.

In models I have copied exactly as the tutorial says:

from django.db import models

class Poll(models.Model):
    question = models.Charfield(max_length=200)
    pub_date = models.DateTimeField('date published')
class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
# Create your models here.

'polls' is also added to installed apps and I'm using sqlite3, windows 7, python 2.7.

Any help very appreciated! (I'm trying very hard to learn!)

Body:
I think in forms.py you are using

from django.forms import forms

Please use this

from django import forms


问:
Layout issue of RecyclerView and CardView

I was trying to show some images and texts using CardView and RecyclerView.But I have some problem about layout.I set all "layout_height" attributes to "wrap_content", but the height of the ImageView is still not what I expected.

MainActivity.java:

```<code>package com.example.android.myapplication;

import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

    private List<Theme> mThemeList;
    private RecyclerView mList;

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

        mThemeList = getThemes();
        mList = (RecyclerView) findViewById(R.id.theme_list);
        mList.setLayoutManager(new GridLayoutManager(this, 2));
        mList.setAdapter(new ThemeAdapter());
    }

    private class ThemeAdapter extends RecyclerView.Adapter<ThemeAdapter.ViewHolder> {

        @Override
        public ThemeAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.theme_item, null, false);

            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Theme theme = mThemeList.get(position);
            holder.name.setText(theme.getName());
            holder.preview.setImageDrawable(theme.getPreview());
        }

        @Override
        public int getItemCount() {
            return mThemeList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            public TextView name;
            public ImageView preview;

            public ViewHolder(View itemView) {
                super(itemView);

                name = (TextView) itemView.findViewById(R.id.theme_name);
                preview = (ImageView) itemView.findViewById(R.id.theme_preview);
            }
        }
    }

    private List<Theme> getThemes() {
        List<Theme> themes = null;
        Theme theme = null;
        XmlResourceParser parser = getResources().getXml(R.xml.themes);
        try {
            while (parser.getEventType() != XmlResourceParser.END_DOCUMENT) {
                switch (parser.getEventType()) {
                    case XmlResourceParser.START_DOCUMENT:
                        themes = new ArrayList<>(3);
                        break;
                    case XmlResourceParser.START_TAG:
                        String tag = parser.getName();
                        if (Theme.TAG_THEME.equals(tag)) {
                            theme = new Theme();
                        } else if (Theme.TAG_ID.equals(tag)) {
                            parser.next();
                            theme.setId(Integer.parseInt(parser.getText()));
                        } else if (Theme.TAG_NAME.equals(tag)) {
                            parser.next();
                            theme.setName(parser.getText());
                        } else if (Theme.TAG_PREFIX.equals(tag)) {
                            parser.next();
                            theme.setPrefix(parser.getText());
                        } else if (Theme.TAG_PREVIEW.equals(tag)) {
                            parser.next();
                            theme.setPreview(loadPreviewDrawable(parser.getText()));
                        }
                        break;
                    case XmlResourceParser.END_TAG:
                        if (Theme.TAG_THEME.equals(parser.getName())) {
                            themes.add(theme);
                            theme = null;
                        }
                        break;
                    default:
                        break;
                }
                parser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return themes;
    }

    private Drawable loadPreviewDrawable(String resName) {
        Resources resources = getResources();
        int resId = resources.getIdentifier(resName, "drawable", getPackageName());
        Drawable drawable = resources.getDrawable(resId, null);
        return drawable;
    }
}
</code>```

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.myapplication.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/theme_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

theme_item.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:cardBackgroundColor="#DDDDDD"
    app:cardCornerRadius="5dp"
    app:cardElevation="10dp"
    app:cardUseCompatPadding="true"
    app:contentPadding="10dp">

    <ImageView
        android:id="@+id/theme_preview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top" />

    <TextView
        android:id="@+id/theme_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:textSize="18sp" />

</android.support.v7.widget.CardView>
</code>```

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" <!--You need to change this-->
    app:cardBackgroundColor="#DDDDDD"
    app:cardCornerRadius="5dp"
    app:cardElevation="10dp"
    app:cardUseCompatPadding="true"
    app:contentPadding="10dp">

    <ImageView
        android:id="@+id/theme_preview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top" />

    <TextView
        android:id="@+id/theme_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:textSize="18sp" />

</android.support.v7.widget.CardView>
</code>```

Body:
I was trying to show some images and texts using CardView and RecyclerView.But I have some problem about layout.I set all "layout_height" attributes to "wrap_content", but the height of the ImageView is still not what I expected.

MainActivity.java:

package com.example.android.myapplication;

import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

    private List<Theme> mThemeList;
    private RecyclerView mList;

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

        mThemeList = getThemes();
        mList = (RecyclerView) findViewById(R.id.theme_list);
        mList.setLayoutManager(new GridLayoutManager(this, 2));
        mList.setAdapter(new ThemeAdapter());
    }

    private class ThemeAdapter extends RecyclerView.Adapter<ThemeAdapter.ViewHolder> {

        @Override
        public ThemeAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.theme_item, null, false);

            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Theme theme = mThemeList.get(position);
            holder.name.setText(theme.getName());
            holder.preview.setImageDrawable(theme.getPreview());
        }

        @Override
        public int getItemCount() {
            return mThemeList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            public TextView name;
            public ImageView preview;

            public ViewHolder(View itemView) {
                super(itemView);

                name = (TextView) itemView.findViewById(R.id.theme_name);
                preview = (ImageView) itemView.findViewById(R.id.theme_preview);
            }
        }
    }

    private List<Theme> getThemes() {
        List<Theme> themes = null;
        Theme theme = null;
        XmlResourceParser parser = getResources().getXml(R.xml.themes);
        try {
            while (parser.getEventType() != XmlResourceParser.END_DOCUMENT) {
                switch (parser.getEventType()) {
                    case XmlResourceParser.START_DOCUMENT:
                        themes = new ArrayList<>(3);
                        break;
                    case XmlResourceParser.START_TAG:
                        String tag = parser.getName();
                        if (Theme.TAG_THEME.equals(tag)) {
                            theme = new Theme();
                        } else if (Theme.TAG_ID.equals(tag)) {
                            parser.next();
                            theme.setId(Integer.parseInt(parser.getText()));
                        } else if (Theme.TAG_NAME.equals(tag)) {
                            parser.next();
                            theme.setName(parser.getText());
                        } else if (Theme.TAG_PREFIX.equals(tag)) {
                            parser.next();
                            theme.setPrefix(parser.getText());
                        } else if (Theme.TAG_PREVIEW.equals(tag)) {
                            parser.next();
                            theme.setPreview(loadPreviewDrawable(parser.getText()));
                        }
                        break;
                    case XmlResourceParser.END_TAG:
                        if (Theme.TAG_THEME.equals(parser.getName())) {
                            themes.add(theme);
                            theme = null;
                        }
                        break;
                    default:
                        break;
                }
                parser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return themes;
    }

    private Drawable loadPreviewDrawable(String resName) {
        Resources resources = getResources();
        int resId = resources.getIdentifier(resName, "drawable", getPackageName());
        Drawable drawable = resources.getDrawable(resId, null);
        return drawable;
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.myapplication.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/theme_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

theme_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:cardBackgroundColor="#DDDDDD"
    app:cardCornerRadius="5dp"
    app:cardElevation="10dp"
    app:cardUseCompatPadding="true"
    app:contentPadding="10dp">

    <ImageView
        android:id="@+id/theme_preview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top" />

    <TextView
        android:id="@+id/theme_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:textSize="18sp" />

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


问:
Numerical solution of exponential equation using Python or other software
I want to find numerical solutions to the following exponential equation where a,b,c,d are constants and I want to solve for r, which is not equal to 1.

a^r + b^r = c^r + d^r                        (Equation 1)

I define a function in order to use Scipy.optimize.fsolve:

```<code>    from scipy.optimize import fsolve
    def func(r,a,b,c,d):
        if r==1:
            return 10**5
        else:
            return ( a**(1-r)  +  b**(1-r) ) - ( c**(1-r)  + d**(1-r)  )

    fsolve(funcp,0.1, args=(5,5,4,7))
</code>```

However, the fsolve always returns 1 as the solution, which is not what I want. Can someone help me with this issue? Or in general, tell me how to solve (Equation 1). I used an online numerical solver long time ago, but I cannot find it anymore. That's why I am trying to figure it out using Python.

答:
You need to apply some mathematical reasoning when choosing the initial guess. Consider your problem f(r) = (51-r + 51-r) − (41-r + 71-r)

When r ≤ 1, f(r) is always negative and decreasing (since 71-r is growing much faster than other terms). Therefore, all root-finding algorithms will be pushed to right towards 1 until reaching this local solution.

You need to pick a point far away from 1 on the right to find the nontrivial solution:

```<code>>>> scipy.optimize.fsolve(lambda r: 5**(1-r)+5**(1-r)-4**(1-r)-7**(1-r), 2.0)
array([ 2.48866034])
</code>```

Simply setting f(1) = 105 is not going to have any effect, as the root-finding algorithm won't check f(1) until the very last step(note).

If you wish to apply a penalty, the penalty must be applied to a range of value around 1. One way to do so, without affecting the position of other roots, is to divide the whole function by (r − 1):

```<code>>>> scipy.optimize.fsolve(lambda r: (5**(1-r)+5**(1-r)-4**(1-r)-7**(1-r)) / (r-1), 0.1)
array([ 2.48866034])
</code>```

(note): they may climb like f(0.1) → f(0.4) → f(0.7) → f(0.86) → f(0.96) → f(0.997) → … and stop as soon as |f(x)| < 10-5, so your f(1) is never evaluated

Body:
I want to find numerical solutions to the following exponential equation where a,b,c,d are constants and I want to solve for r, which is not equal to 1.

a^r + b^r = c^r + d^r                        (Equation 1)

I define a function in order to use Scipy.optimize.fsolve:

    from scipy.optimize import fsolve
    def func(r,a,b,c,d):
        if r==1:
            return 10**5
        else:
            return ( a**(1-r)  +  b**(1-r) ) - ( c**(1-r)  + d**(1-r)  )

    fsolve(funcp,0.1, args=(5,5,4,7))

However, the fsolve always returns 1 as the solution, which is not what I want. Can someone help me with this issue? Or in general, tell me how to solve (Equation 1). I used an online numerical solver long time ago, but I cannot find it anymore. That's why I am trying to figure it out using Python.

Body:
You need to apply some mathematical reasoning when choosing the initial guess. Consider your problem f(r) = (51-r + 51-r) − (41-r + 71-r)

When r ≤ 1, f(r) is always negative and decreasing (since 71-r is growing much faster than other terms). Therefore, all root-finding algorithms will be pushed to right towards 1 until reaching this local solution.

You need to pick a point far away from 1 on the right to find the nontrivial solution:

>>> scipy.optimize.fsolve(lambda r: 5**(1-r)+5**(1-r)-4**(1-r)-7**(1-r), 2.0)
array([ 2.48866034])

Simply setting f(1) = 105 is not going to have any effect, as the root-finding algorithm won't check f(1) until the very last step(note).

If you wish to apply a penalty, the penalty must be applied to a range of value around 1. One way to do so, without affecting the position of other roots, is to divide the whole function by (r − 1):

>>> scipy.optimize.fsolve(lambda r: (5**(1-r)+5**(1-r)-4**(1-r)-7**(1-r)) / (r-1), 0.1)
array([ 2.48866034])

(note): they may climb like f(0.1) → f(0.4) → f(0.7) → f(0.86) → f(0.96) → f(0.997) → … and stop as soon as |f(x)| < 10-5, so your f(1) is never evaluated


问:
How to send serial data with some delay in QT
I need to send data via serial communication. This data then will be displayed on a label. I have a com port in my system. I have connected the tx rx line so the data I am sending is the data I am receiving.

```<code>connect(&Serial, SIGNAL(readyRead()), this, SLOT(SerialRead()));

void MainWindow::SerialWrite()
{
  Serial.write("2");
  Serial.waitForBytesWritten(3000);
}

void MainWindow::SerialRead()
{

 //reeving data and displaying data on label
}
</code>```

Now I need to send 5 data continuous with some delay like below

```<code>Serial.write("1");
Serial.waitForBytesWritten(3000);
delay();
Serial.write("2");
Serial.waitForBytesWritten(3000);
delay();
Serial.write("3");
Serial.waitForBytesWritten(3000);
delay();
Serial.write("4");
Serial.waitForBytesWritten(3000);
delay();
Serial.write("5");
Serial.waitForBytesWritten(3000);
delay();
</code>```

So that it is displayed one by one with some delay. How to acheive this

答:
QThread has static public members to simply delay the execution of the current thread by a specific amount. These are

QThread::sleep(unsigned long) for seconds

QThread::msleep(unsigned long) for milliseconds

QThread::usleep(unsigned long) for microseconds

Body:
I need to send data via serial communication. This data then will be displayed on a label. I have a com port in my system. I have connected the tx rx line so the data I am sending is the data I am receiving.

connect(&Serial, SIGNAL(readyRead()), this, SLOT(SerialRead()));

void MainWindow::SerialWrite()
{
  Serial.write("2");
  Serial.waitForBytesWritten(3000);
}

void MainWindow::SerialRead()
{

 //reeving data and displaying data on label
}

Now I need to send 5 data continuous with some delay like below

Serial.write("1");
Serial.waitForBytesWritten(3000);
delay();
Serial.write("2");
Serial.waitForBytesWritten(3000);
delay();
Serial.write("3");
Serial.waitForBytesWritten(3000);
delay();
Serial.write("4");
Serial.waitForBytesWritten(3000);
delay();
Serial.write("5");
Serial.waitForBytesWritten(3000);
delay();

So that it is displayed one by one with some delay. How to acheive this


问:
Dot at start and end using regex
Hello I am trying to validate an input using regex in Javascript, what my requirement is that I can have at most one dot ('.') in the string and that can't be at the start and end.
I got a solution in

```<code>/^[^\.].*[^\.]$/;
</code>```

But the issue is input "x" is considered as invalid
valid inputs are like
"x", "x.x", "xx.x" , "x.xx" like so
invalid like ".x" and "x."

答:
With your current regex, you are targeting a string that should be at least 2 characters long, as both [^\.] parts are a mandatory character.

Your regex should include an extra check in case there is just one character, which you can do like this:
^([^\.]|([^\.]+\.?[^\.]+))$

Title: Dot at start and end using regex

Body:
Hello I am trying to validate an input using regex in Javascript, what my requirement is that I can have at most one dot ('.') in the string and that can't be at the start and end.
I got a solution in

/^[^\.].*[^\.]$/;

But the issue is input "x" is considered as invalid
valid inputs are like
"x", "x.x", "xx.x" , "x.xx" like so
invalid like ".x" and "x."


问:
How to update id set from 1?
I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

```<code>id  name
3   ABC
5   XYZ
9   PQR
</code>```

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

```<code>id  name
1   ABC
2   XYZ
3   PQR
</code>```

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks

答:
This query will work for your scenario:</p>

```<code>ALTER TABLE tablename DROP id

ALTER TABLE tablename ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id), AUTO_INCREMENT=1
</code>```

Title: How to update id set from 1?

Body:
I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

id  name
3   ABC
5   XYZ
9   PQR

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

id  name
1   ABC
2   XYZ
3   PQR

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks

Body:
This query will work for your scenario:

ALTER TABLE tablename DROP id

ALTER TABLE tablename ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id), AUTO_INCREMENT=1


问:
In a GLSL fragment shader, how to access to texel at a specific mipmap level?
I am using OpenGL to do some GPGPU computations through the combination of one vertex shader and one fragment shader. I need to do computations on a image at different scale. I would like to use mipmaps since their generation can be automatic and hardware accelerated. However I can't manage to get access to the mipmap textures in the fragment shader.

I enabled automatic mipmap generation:
    glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);

I tried using texture2DLod in the shader with no luck, it simply kept giving the normal texture. I also tried using glTextureParameteri(GL_BASE_LEVEL, X) in the main program and it did not change anything.

How would you do that?

I am using Linux. My graphic card is a Nvidia Quadro quite old. Here is my glxinfo output with all the supported extensions.

答:
try:

```<code>glGenerateMipmapEXT(GL_TEXTURE_2D);
</code>```

after you bind the texture. (And before doing the rendering of course)

The glTexParameteri-GL_GENERATE_MIPMAP is deprecated I think...
MfG Digi

Body:
try:

glGenerateMipmapEXT(GL_TEXTURE_2D);

after you bind the texture. (And before doing the rendering of course)

The glTexParameteri-GL_GENERATE_MIPMAP is deprecated I think...
MfG Digi


问:
Interpretation of GAP in CPLEX
This is a part of the engine-log output that I get from a small-scale mixed integer linear optimization problem that I solved in CPLEX 12.7.0

```<code>    Nodes                                         Cuts/
   Node  Left     Objective  IInf  Best Integer    Best Bound    ItCnt     Gap

      0     0      280.0338    78                    280.0338       72
      0     0      428.8558    28                    Cuts: 89      137
      0     0      429.5221    34                     Cuts: 2      142
      0     0      429.7745    34                  MIRcuts: 2      143
*     0+    0                          460.9166      429.7745             6.76%
      0     2      429.7745    34      460.9166      429.8666      143    6.74%
Elapsed time = 0.49 sec. (31.07 ticks, tree = 0.01 MB, solutions = 1)
*    35     8      integral     0      438.1448      435.6381      211    0.57%

Cover cuts applied:  17
Implied bound cuts applied:  10
Flow cuts applied:  11
Mixed integer rounding cuts applied:  9
Gomory fractional cuts applied:  24

Root node processing (before b&c):
  Real time             =    0.45 sec. (31.09 ticks)
Sequential b&c:
  Real time             =    0.08 sec. (20.80 ticks)
                          ------------
Total (root+branch&cut) =    0.53 sec. (51.89 ticks)
</code>```

What I understand from this, is that the best integer solution (for the objective function) found has the value of 438.1448, whereas the relaxed solution (non integer values) has the value of 435.6381 as best bound solution.

( 438.1448 / 435.6381 ) - 1 = 0.57% GAP

Does this mean that the solution still has that small gap, however it is proven to be the optimal solution? I had the (maybe wrong) idea that optimality is proven by a 0% gap.

I'm not sure how to interpret it correctly. Thanks for your help in advance.

答:
Yes you are right. The optimality is proven if the upper bound and the lower bound evaluate the same value, i.e. CPLEX could prove an optimality gap of 0%.

Since CPLEX stops with a solution that has a gap of 0.57%, I would assume that you configured an MIP-gap <1%. If you are interested in a solution with proven optimal, you should change the MIPGap parameter to zero. See also here.

Title: Interpretation of GAP in CPLEX

Body:
This is a part of the engine-log output that I get from a small-scale mixed integer linear optimization problem that I solved in CPLEX 12.7.0

    Nodes                                         Cuts/
   Node  Left     Objective  IInf  Best Integer    Best Bound    ItCnt     Gap

      0     0      280.0338    78                    280.0338       72
      0     0      428.8558    28                    Cuts: 89      137
      0     0      429.5221    34                     Cuts: 2      142
      0     0      429.7745    34                  MIRcuts: 2      143
*     0+    0                          460.9166      429.7745             6.76%
      0     2      429.7745    34      460.9166      429.8666      143    6.74%
Elapsed time = 0.49 sec. (31.07 ticks, tree = 0.01 MB, solutions = 1)
*    35     8      integral     0      438.1448      435.6381      211    0.57%

Cover cuts applied:  17
Implied bound cuts applied:  10
Flow cuts applied:  11
Mixed integer rounding cuts applied:  9
Gomory fractional cuts applied:  24

Root node processing (before b&c):
  Real time             =    0.45 sec. (31.09 ticks)
Sequential b&c:
  Real time             =    0.08 sec. (20.80 ticks)
                          ------------
Total (root+branch&cut) =    0.53 sec. (51.89 ticks)

What I understand from this, is that the best integer solution (for the objective function) found has the value of 438.1448, whereas the relaxed solution (non integer values) has the value of 435.6381 as best bound solution.

( 438.1448 / 435.6381 ) - 1 = 0.57% GAP

Does this mean that the solution still has that small gap, however it is proven to be the optimal solution? I had the (maybe wrong) idea that optimality is proven by a 0% gap.

I'm not sure how to interpret it correctly. Thanks for your help in advance.

ContentLicense: CC BY-SA 4.0


问:
Need help parsing php date using moment.js
My PHP script is giving me following date:

```<code>"Friday, 31-Mar-17 07:45:47 UTC"
</code>```

I want to parse this date using moment.js and I want to store each parsed token into separate JavaScript variable. How can I do this in moment.js?

答:
Simply use moment(String, String) to parse it. Then you can use format() or getters to get each parsed token:

var m = moment.utc("Friday, 31-Mar-17 07:45:47 UTC", "dddd, DD-MMM-YY HH:mm:ss Z");
console.log(m.format());
var dayOfWeek = m.format('dddd'); // Friday
var dayOfMonth = m.date(); // 31
var shortMonthName = m.format('MMM'); // Mar
var shortYear = m.format('YY'); // 17
var minutes = m.minutes(); // 45

console.log(dayOfWeek, dayOfMonth, shortMonthName, shortYear, minutes);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
My PHP script is giving me following date:

"Friday, 31-Mar-17 07:45:47 UTC"

I want to parse this date using moment.js and I want to store each parsed token into separate JavaScript variable. How can I do this in moment.js?

Body:
Simply use moment(String, String) to parse it. Then you can use format() or getters to get each parsed token:

var m = moment.utc("Friday, 31-Mar-17 07:45:47 UTC", "dddd, DD-MMM-YY HH:mm:ss Z");
console.log(m.format());
var dayOfWeek = m.format('dddd'); // Friday
var dayOfMonth = m.date(); // 31
var shortMonthName = m.format('MMM'); // Mar
var shortYear = m.format('YY'); // 17
var minutes = m.minutes(); // 45

console.log(dayOfWeek, dayOfMonth, shortMonthName, shortYear, minutes);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
PHP- I'm trying to loop an sql query in php code for mutiple checkbox selection
What I'm basically trying to do is retrieve an entire row from mysql database on checkbox selection. This code works fine for single selection. But on multiple selection it still retrieves a single row. How do I loop through it?

```<code>$sql = "Select * from $DB_TBLName WHERE Delivery_no = '{$_REQUEST['check'][0]}'" ;
echo $sql;
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
if(isset($_POST['submit'])){
   if(!empty($_POST['check'])) {
      // Loop to store and display values of individual checked checkbox.
      foreach($_POST['check'] as $selected) {
         echo $selected ;
      }
   }
}
$sep = "\t";
for ($i = 0; $i < mysql_num_fields($result); $i++) {
   echo mysql_field_name($result,$i) . "\t";
}
print("\n");
while($row = mysql_fetch_row($result)){
   $schema_insert = "";
   for($j=0; $j<mysql_num_fields($result);$j++) {
      if(!isset($row[$j]))
         $schema_insert .= "NULL".$sep;
      elseif ($row[$j] != "")
         $schema_insert .= "$row[$j]".$sep;
      else
         $schema_insert .= "".$sep;
   }
   $schema_insert = str_replace($sep."$", "", $schema_insert);
   $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
   $schema_insert .= "\t";
   print(trim($schema_insert));
   print "\n";
}
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
</code>```

HTML CODE

```<code><td class="border-right" align="center"><input type="checkbox" name="check[]" id="check[]" value= "<?php echo $row['Delivery_no']; ?>" /></td>
<td><?php echo $row['Delivery_no'];?></td>
<td><?php echo $row['Invoice_no'];?></td>
<td><?php echo $row['Bill_date'];?></td>
<td><?php echo $row['Bill_to_party'];?></td>
<td><?php echo $row['Quantity'];?></td>
<td><?php echo $row['Brand']; } ?></td>
</tr>
</table>
<br>
<input type= "submit" name="submit" id="submit" value="submit" class="btn btn-primary button-loading">
</code>```

答:
You appear to build up the SQL at the start but only ever use the first element of the checks input array.

You need to use all the elements

Simply knocked together, something like this:-

```<code>if (is_array($_REQUEST['check']) and count($_REQUEST['check']) > 0)
{
    $checks = implode(',', array_map('intval', $_REQUEST['check']));

    $sql = "Select * from $DB_TBLName WHERE Delivery_no IN ($checks)" ;
    echo $sql;
    $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
    if(isset($_POST['submit'])){
       if(!empty($_POST['check'])) {
          // Loop to store and display values of individual checked checkbox.
          foreach($_POST['check'] as $selected) {
             echo $selected ;
          }
       }
    }
    $sep = "\t";
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
       echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    while($row = mysql_fetch_row($result)){
       $schema_insert = "";
       for($j=0; $j<mysql_num_fields($result);$j++) {
          if(!isset($row[$j]))
             $schema_insert .= "NULL".$sep;
          elseif ($row[$j] != "")
             $schema_insert .= "$row[$j]".$sep;
          else
             $schema_insert .= "".$sep;
       }
       $schema_insert = str_replace($sep."$", "", $schema_insert);
       $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
       $schema_insert .= "\t";
       print(trim($schema_insert));
       print "\n";
    }
    $file_ending = "xls";
    header("Content-Type: application/xls");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
}
</code>```

Note - you are using the old obsolete mysql_* functions rather than the current mysqli_* functions (or the PDO equivalents). I would advise you to swap over. This would also allow you to use parameterised queries which are safer. Your current query is wide open to SQL injection attacks.

Body:
What I'm basically trying to do is retrieve an entire row from mysql database on checkbox selection. This code works fine for single selection. But on multiple selection it still retrieves a single row. How do I loop through it?

$sql = "Select * from $DB_TBLName WHERE Delivery_no = '{$_REQUEST['check'][0]}'" ;
echo $sql;
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:
" . mysql_error(). "
" . mysql_errno());
if(isset($_POST['submit'])){
   if(!empty($_POST['check'])) {
      // Loop to store and display values of individual checked checkbox.
      foreach($_POST['check'] as $selected) {
         echo $selected ;
      }
   }
}
$sep = "\t";
for ($i = 0; $i < mysql_num_fields($result); $i++) {
   echo mysql_field_name($result,$i) . "\t";
}
print("\n");
while($row = mysql_fetch_row($result)){
   $schema_insert = "";
   for($j=0; $j<mysql_num_fields($result);$j++) {
      if(!isset($row[$j]))
         $schema_insert .= "NULL".$sep;
      elseif ($row[$j] != "")
         $schema_insert .= "$row[$j]".$sep;
      else
         $schema_insert .= "".$sep;
   }
   $schema_insert = str_replace($sep."$", "", $schema_insert);
   $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
   $schema_insert .= "\t";
   print(trim($schema_insert));
   print "\n";
}
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");

HTML CODE

<input type="checkbox" name="check[]" id="check[]" value= "<?php echo $row['Delivery_no']; ?>" />
<?php echo $row['Delivery_no'];?>
<?php echo $row['Invoice_no'];?>
<?php echo $row['Bill_date'];?>
<?php echo $row['Bill_to_party'];?>
<?php echo $row['Quantity'];?>
<?php echo $row['Brand']; } ?>

<input type= "submit" name="submit" id="submit" value="submit" class="btn btn-primary button-loading">

Body:
You appear to build up the SQL at the start but only ever use the first element of the checks input array.

You need to use all the elements

Simply knocked together, something like this:-

if (is_array($_REQUEST['check']) and count($_REQUEST['check']) > 0)
{
    $checks = implode(',', array_map('intval', $_REQUEST['check']));

    $sql = "Select * from $DB_TBLName WHERE Delivery_no IN ($checks)" ;
    echo $sql;
    $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
    if(isset($_POST['submit'])){
       if(!empty($_POST['check'])) {
          // Loop to store and display values of individual checked checkbox.
          foreach($_POST['check'] as $selected) {
             echo $selected ;
          }
       }
    }
    $sep = "\t";
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
       echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    while($row = mysql_fetch_row($result)){
       $schema_insert = "";
       for($j=0; $j<mysql_num_fields($result);$j++) {
          if(!isset($row[$j]))
             $schema_insert .= "NULL".$sep;
          elseif ($row[$j] != "")
             $schema_insert .= "$row[$j]".$sep;
          else
             $schema_insert .= "".$sep;
       }
       $schema_insert = str_replace($sep."$", "", $schema_insert);
       $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
       $schema_insert .= "\t";
       print(trim($schema_insert));
       print "\n";
    }
    $file_ending = "xls";
    header("Content-Type: application/xls");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
}

Note - you are using the old obsolete mysql_* functions rather than the current mysqli_* functions (or the PDO equivalents). I would advise you to swap over. This would also allow you to use parameterised queries which are safer. Your current query is wide open to SQL injection attacks.


问:
How do I size a UITextView to its content?
Is there a good way to adjust the size of a UITextView to conform to its content? Say for instance I have a UITextView that contains one line of text:

```<code>"Hello world"
</code>```

I then add another line of text:

```<code>"Goodbye world"
</code>```

Is there a good way in Cocoa Touch to get the rect that will hold all of the lines in the text view so that I can adjust the parent view accordingly?

As another example, look at the notes' field for events in the Calendar application - note how the cell (and the UITextView it contains) expands to hold all lines of text in the notes' string.

答:
Here is the answer if you need resize textView and tableViewCell dynamically in staticTableView

[https://stackoverflow.com/a/43137182/5360675][1]

OwnerDisplayName: drewh

Body:
Is there a good way to adjust the size of a UITextView to conform to its content? Say for instance I have a UITextView that contains one line of text:

"Hello world"

I then add another line of text:

"Goodbye world"

Is there a good way in Cocoa Touch to get the rect that will hold all of the lines in the text view so that I can adjust the parent view accordingly?

As another example, look at the notes' field for events in the Calendar application - note how the cell (and the UITextView it contains) expands to hold all lines of text in the notes' string.


问:
Wagtail - how do I add extra form fields (not from page model) to admin page edit form and get wagtail rendering
This is what I tried. It works but the extra field text1 is rendered as a plain input field with no label and no cool wagtail rendering. How can I add extra fields to the form and get cool wagtail rendering please?

Here is a link to the WagtailAdminPageForm documentation:

```<code>class Review(models.Model):

    page = models.OneToOneField(
        'wagtailcore.Page',
        verbose_name=('page'),
        related_name='review',
        on_delete=models.CASCADE)
    text1 = models.CharField(null=True, blank=True, max_length=50)

class RandomPageForm(WagtailAdminPageForm):
    """ Custom form for RandomPage """

    text1 = forms.CharField() # <-- extra field here!

    def __init__(self, data=None, files=None, parent_page=None, *args, **kwargs):
        super(RandomPageForm, self).__init__(data, files, *args, **kwargs)

        if self.instance.id:
            review, created = Review.objects.get_or_create(page_id=self.instance.id)
            print "set form.text1 to model.text1"
            self.fields['text1'].initial = review.text1

        # !!! Below has no effect
        self.instance.content_panels = Page.content_panels + [
            FieldPanel('body'),
            FieldPanel('text1'),
        ]

    def save(self, commit=True):
        page = super(RandomPageForm, self).save(commit=False)
        review, created = Review.objects.get_or_create(page=page)
        review.text1 = self.data["text1"]
        review.save()
        return page

class RandomPage(Page):

    body = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('body', classname="full"),
    ]

    base_form_class = RandomPageForm
</code>```

答:
Editing the panel definition on a per-instance basis won't work, because the panel definition is compiled into an EditHandler object that gets cached at the class level: https://github.com/wagtail/wagtail/blob/48949e69a7a7039cb751f1ee33ecb32187004030/wagtail/wagtailadmin/edit_handlers.py#L804

In the case of the code snippet you posted, it looks like moving FieldPanel('text1') into RandomPage's content_panels snippet ought to do the job (although I've never tried that with a non-model field).

Body:
This is what I tried. It works but the extra field text1 is rendered as a plain input field with no label and no cool wagtail rendering. How can I add extra fields to the form and get cool wagtail rendering please?

Here is a link to the WagtailAdminPageForm documentation:

class Review(models.Model):

    page = models.OneToOneField(
        'wagtailcore.Page',
        verbose_name=('page'),
        related_name='review',
        on_delete=models.CASCADE)
    text1 = models.CharField(null=True, blank=True, max_length=50)

class RandomPageForm(WagtailAdminPageForm):
    """ Custom form for RandomPage """

    text1 = forms.CharField() # <-- extra field here!

    def __init__(self, data=None, files=None, parent_page=None, *args, **kwargs):
        super(RandomPageForm, self).__init__(data, files, *args, **kwargs)

        if self.instance.id:
            review, created = Review.objects.get_or_create(page_id=self.instance.id)
            print "set form.text1 to model.text1"
            self.fields['text1'].initial = review.text1

        # !!! Below has no effect
        self.instance.content_panels = Page.content_panels + [
            FieldPanel('body'),
            FieldPanel('text1'),
        ]

    def save(self, commit=True):
        page = super(RandomPageForm, self).save(commit=False)
        review, created = Review.objects.get_or_create(page=page)
        review.text1 = self.data["text1"]
        review.save()
        return page

class RandomPage(Page):

    body = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('body', classname="full"),
    ]

    base_form_class = RandomPageForm


问:
facebook chatbot localization of greeting message not working
I'm trying to localize the greeting message in my facebook chatbot. Here is the curl command I sent to do this:
curl -X POST -H "Content-Type: application/json" -d '{
  "greeting":[
    {
      "locale":"default",
      "text":"Hi {{user_first_name}}"
    },
    {
      "locale":"ar_AR",
      "text":"مرحبا {{user_first_name}}"

    }
  ]
}'  "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=MY_TOKEN_HERE"

This command succeeded.

When my smartphone's language is set to english I get the english one normally. However, when I switch my phone to arabic, I get question marks instead of the arabic text saying 'مرحبا'.

I would like to know why I'm getting question marks even though my text is in arabic. What I ultimately want to do (If possible) is to set the default text to arabic text so it always shows that even if the smartphone's language is set to english or something else.

P.S. I got the arabic locale string representation from here.

答:
You need to properly escape non-ASCII characters.

{"text":"\u0645\u0631\u062d\u0628\u0627 {{user_first_name}}"} would be the proper JSON representation of an array containing one element with the key text and the content مرحبا {{user_first_name}}


问:
IPython Auto Scroll?
In IPython, if I run a cell, the browser scrolls to put the cell near the bottom of the page. If this happens when I plot a chart, then I can't see the chart and have to scroll down manually. How can I stop this happening?</p>

答:
I feel your frustration!

This will probably depend on where you plotter functionality is within your ipython notebook, but one solution (especially if it is in the last cell) is to create many blank cells below your plotter cell (say 10 to 20) then use Ctrl + Enter to run the plotter cell. This may need some playing around with but I have gotten this to work for me!

(I think the idea of Ctrl + Enter is to keep the cell where it is)

Title: IPython Auto Scroll?


问:
ActionScript 3 addEventListener to a Sprite
I try to add an event handler to a sprite object but it doesn't affect anyway what is my problem?

```
...
my_sprite_object.addEventListener(MouseEvent.CLICK, handleEvent);

addChild(my_sprite_object);
...

public function handleEvent(event:MouseEvent):void {
//do some stuff here
}
```

Sultan

答:
Have you set the Sprite.buttonMode to true?

If yes, can it be that something else is already capturing the click event and is not letting it bubble further?

ContentLicense: CC BY-SA 2.5

Body:
I try to add an event handler to a sprite object but it doesn't affect anyway what is my problem?

...
my_sprite_object.addEventListener(MouseEvent.CLICK, handleEvent);

addChild(my_sprite_object);
...

public function handleEvent(event:MouseEvent):void {
//do some stuff here
}

Sultan


问:
redirecting page after login in codeigniter
I am quite newbie to codeigniter, I have login system to start with on site, and have 2 scenario:

If user is already logged in, and if clicks on url from other site(different domain), then it will redirect to given link.

If user is not logged in and click on link from other domain then he will first redirect to login page and then he will redirect again to clicked link.

now my first case works but not second, I tried setting a url in session like,

```<code>$array['login_redirect'] = current_url();

$this->session->set_userdata($array);
</code>```

which is giving me correct url

but after login, session data shows login page url as value for login_redirect.

答:
You can save current url in session when user is not logged in and don't do it when user is on login page - then you can read link from session and it will be link to last visited page.

Another solution is to save url to page in cookie when user clicks on link and then you can read it in PHP and redirect user to correct page.

Third solutiuon is to send this link via POST or GET when user is redirected to login page.

Body:
I am quite newbie to codeigniter, I have login system to start with on site, and have 2 scenario:

If user is already logged in, and if clicks on url from other site(different domain), then it will redirect to given link.

If user is not logged in and click on link from other domain then he will first redirect to login page and then he will redirect again to clicked link.

now my first case works but not second, I tried setting a url in session like,

$array['login_redirect'] = current_url();

$this->session->set_userdata($array);

which is giving me correct url

but after login, session data shows login page url as value for login_redirect.


问:
JavaScript clipboard doesn't work when I use the mouseover event
I have a problem. The JavaScript clipboard doesn't work when I use the mouseover event.If I use the click event, it works. I don't know how can solve this problem.

Code:

function select(data) {
    var el = document.querySelector(data.el)
    var target = document.querySelector(data.target)

    el.addEventListener(data.event, function() {
        target.select();
        if(data.copy) {
            var successful = document.execCommand('copy')

            console.log(successful)
        }
    }, false)
}

select({
    el: '.btn',
    event: 'mouseover',
    target: '[name="txtArea"]',
    copy: true
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <title>Clipboard JS</title>
    <script src="js/clip.js"></script>
</head>
<body>
<input type="text" name="txtArea" value="Lorem ipsum dolor sit amet!">

<button class="btn">Select</button>

<script src="js/custom.js"></script>
</body>
</html></code>```

答:
Because the mouseover event is not allowed to modify the clipboard.

The related links:

https://developer.mozilla.org/en-US/docs/Web/API/Document/queryCommandEnabled

https://w3c.github.io/clipboard-apis/#events-that-are-allowed-to-modify-the-clipboard

https://www.w3.org/TR/html5/browsers.html#allowed-to-show-a-popup

Body:
I have a problem. The JavaScript clipboard doesn't work when I use the mouseover event.If I use the click event, it works. I don't know how can solve this problem.

Code:

function select(data) {
    var el = document.querySelector(data.el)
    var target = document.querySelector(data.target)

    el.addEventListener(data.event, function() {
        target.select();
        if(data.copy) {
            var successful = document.execCommand('copy')

            console.log(successful)
        }
    }, false)
}

select({
    el: '.btn',
    event: 'mouseover',
    target: '[name="txtArea"]',
    copy: true
})

<!DOCTYPE html>

    <title>Clipboard JS</title>

<input type="text" name="txtArea" value="Lorem ipsum dolor sit amet!">

<button class="btn">Select</button>


问:
id showing undefined when trying to implement delete in angularjs
Trying to implement delete funtion in angularjs. The backend in asp.net is working fine. when i check with postman its working fine. now am trying to the front end for that. when i hit the delete button. its not getting the UId. its showing like this.

```<code>http://localhost:50802/api/User/BUser/[object%20Object]
</code>```

am totally new to angular. i dont know whether this angular code is correct or not.And another thing is i need to implement user confirmation popup window also. please help me...

angular controller.

```<code>$scope.DeleteUser = function (data, UId) {
        $http({
            method: "post",
            url: urls.api + 'User/BUser/' + UId,

            data: JSON.stringify(data)
        }).then(function (response) {
            alert(response.data);

        })
    };
</code>```

HTML

```<code> <tr ng-repeat="d in UserList">

                        <td>{{d.description}}</td>
                        <td>{{d.path}}</td>
                        <td><button ng-click="DeleteUser()">Delete </button></td>

                    </tr>
</code>```

here my Asp.net Controller

```<code>[HttpDelete]
        [Route("DeleteBanner/{UId}")]
        public async Task<IHttpActionResult> DeleteBanner(int UId)
        {
            int? result = await _service.DeleteBannerAsync(UId);

            return Ok();

        }
</code>```

答:
Thanks for the valuable comments. i found the error. in the asp.net controller i used HttpDelete. But here Am geting the data in Post method. that is the problem.
and Also as Phil said, I dont need to mind about that Json.stringify(data) things.

here is the Answer.

angular Controller

```<code> $scope.DeleteUser = function (Uid) {
        deleteUser = $window.confirm('Are you sure you want to delete?');
        //console.log(Uid);
        if (deleteUser) {
            $http({
                method: "Delete",
                url: urls.api + 'User/BUser/' + Uid,
            }).then(function (response) {
                alert(response.data);
            })
        }
    };
</code>```

Html

```<code><button ng-click="DeleteUser(d.Uid)">Delete </button>
</code>```

well if i wasted your time really sorry for that. thanks again

Body:
Trying to implement delete funtion in angularjs. The backend in asp.net is working fine. when i check with postman its working fine. now am trying to the front end for that. when i hit the delete button. its not getting the UId. its showing like this.

http://localhost:50802/api/User/BUser/[object%20Object]

am totally new to angular. i dont know whether this angular code is correct or not.And another thing is i need to implement user confirmation popup window also. please help me...

angular controller.

$scope.DeleteUser = function (data, UId) {
        $http({
            method: "post",
            url: urls.api + 'User/BUser/' + UId,

            data: JSON.stringify(data)
        }).then(function (response) {
            alert(response.data);

        })
    };

HTML

                        {{d.description}}
                        {{d.path}}
                        <button ng-click="DeleteUser()">Delete </button>

here my Asp.net Controller

[HttpDelete]
        [Route("DeleteBanner/{UId}")]
        public async Task<IHttpActionResult> DeleteBanner(int UId)
        {
            int? result = await _service.DeleteBannerAsync(UId);

            return Ok();

        }

Body:
Thanks for the valuable comments. i found the error. in the asp.net controller i used HttpDelete. But here Am geting the data in Post method. that is the problem.
and Also as Phil said, I dont need to mind about that Json.stringify(data) things.

here is the Answer.

angular Controller

 $scope.DeleteUser = function (Uid) {
        deleteUser = $window.confirm('Are you sure you want to delete?');
        //console.log(Uid);
        if (deleteUser) {
            $http({
                method: "Delete",
                url: urls.api + 'User/BUser/' + Uid,
            }).then(function (response) {
                alert(response.data);
            })
        }
    };

Html

<button ng-click="DeleteUser(d.Uid)">Delete </button>

well if i wasted your time really sorry for that. thanks again


问:
Looping over plots
I try to generate a lot of plots and save them in separate files. Each plot should be based on a variable from a dataframe.

This works when using the numbers of the variables:

```<code>for(i in names(df)[19:20]) {
   png(paste(i, "png", sep = "."), width = 400, height = 400)
   print(ggplot(df) + geom_histogram(aes_string(x= i), binwidth= 0.4) +
   theme_bw())
   dev.off()
}
</code>```

However, it doesn't work if I'm using variable names instead of the ordered number. I don't understand why.

```<code>for(i in names(df)[c("varname1","varname2","varname3")]) {
   png(paste(i, "png", sep = "."), width = 400, height = 400)
   print(ggplot(df) + geom_histogram(aes_string(x= i), binwidth= 0.4) +
   theme_bw())
   dev.off()
}
</code>```

I get the following error message at the latter question (if it's exactly the same variable as in the first example):

"Error: StatBin requires a continuous x variable the x variable is discrete. Perhaps you want stat="count"? "

Any ideas?

答:
names(df) is an unnamed vector, so it doesn't make sense to select named values from that vector.

What you're looking for is

```<code>for(i in c("varname1","varname2","varname3")) {
   png(paste(i, "png", sep = "."), width = 400, height = 400)
   print(ggplot(df) + geom_histogram(aes_string(x= i), binwidth= 0.4) +
   theme_bw())
   dev.off()
}
</code>```

Title: Looping over plots

Body:
I try to generate a lot of plots and save them in separate files. Each plot should be based on a variable from a dataframe.

This works when using the numbers of the variables:

for(i in names(df)[19:20]) {
   png(paste(i, "png", sep = "."), width = 400, height = 400)
   print(ggplot(df) + geom_histogram(aes_string(x= i), binwidth= 0.4) +
   theme_bw())
   dev.off()
}

However, it doesn't work if I'm using variable names instead of the ordered number. I don't understand why.

for(i in names(df)[c("varname1","varname2","varname3")]) {
   png(paste(i, "png", sep = "."), width = 400, height = 400)
   print(ggplot(df) + geom_histogram(aes_string(x= i), binwidth= 0.4) +
   theme_bw())
   dev.off()
}

I get the following error message at the latter question (if it's exactly the same variable as in the first example):

"Error: StatBin requires a continuous x variable the x variable is discrete. Perhaps you want stat="count"? "

Any ideas?

Body:
names(df) is an unnamed vector, so it doesn't make sense to select named values from that vector.

What you're looking for is

for(i in c("varname1","varname2","varname3")) {
   png(paste(i, "png", sep = "."), width = 400, height = 400)
   print(ggplot(df) + geom_histogram(aes_string(x= i), binwidth= 0.4) +
   theme_bw())
   dev.off()
}


问:
How to check two arrays of objects by propery id and if there is mach add property from one to anothe
How to compare two arrays of objects by id and then if id's match add property cr with value to matching object in the array arr.

```<code>var arr = [{
    id: 1,
    username: 'fred'
}, {
    id: 2,
    username: 'bill'
}, {
    id: 3,
    username: 'ted'
}];

var arr1 =[{
    id:1,
    cr:1313
}, {
    id:2,
    cr:304
}];
</code>```

I have searched for similar questions but could not find any or did not see that.

答:
You could use a hash table and assign the value to the hashed object.

var arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }],
    arr1 = [{ id: 1, cr: 1313 }, { id: 2, cr: 304 }],
    hash = Object.create(null);

arr.forEach(function (a) {
    hash[a.id] = a;
});
arr1.forEach(function (a) {
    (hash[a.id] || {}).cr = a.cr;
});

console.log(arr);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
How to compare two arrays of objects by id and then if id's match add property cr with value to matching object in the array arr.

var arr = [{
    id: 1,
    username: 'fred'
}, {
    id: 2,
    username: 'bill'
}, {
    id: 3,
    username: 'ted'
}];

var arr1 =[{
    id:1,
    cr:1313
}, {
    id:2,
    cr:304
}];

I have searched for similar questions but could not find any or did not see that.

Body:
You could use a hash table and assign the value to the hashed object.

var arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }],
    arr1 = [{ id: 1, cr: 1313 }, { id: 2, cr: 304 }],
    hash = Object.create(null);

arr.forEach(function (a) {
    hash[a.id] = a;
});
arr1.forEach(function (a) {
    (hash[a.id] || {}).cr = a.cr;
});

console.log(arr);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Echo file URL from Laravel storage
Im using this code in my laravel view to echo a files path, but its coming up in chrome dev tools with a 404 response.

image) }}">

which echos this onto the page

http://localhost:8000/storage/public/bd0e2f7f.png

The file lives there and this is the correct name for the file so im not entirely sure why its coming up with a 404!

答:
It looks like even though it sees like your path is fine from the app root folder it's not where laravel is looking for it. Laravel will look inside app/public for your path, resulting in an internal app/public/storage/public/bd0e2f7f.png which, unless you've created a symbolic link between the app/storage/public and `app/public, wont find the file.

The solution, taken from the documentation, is to run:

```<code>php artisan storage:link
</code>```

from the command line which creates the above-mentioned link, and will allow you to access the file with the url http://localhost:8000/storage/bd0e2f7f.png, not http://localhost:8000/storage/public/bd0e2f7f.png

From the docs

The storage/app/public directory may be used to store user-generated files, such as profile avatars, that should be publicly accessible. You should create a symbolic link at  public/storage which points to this directory. You may create the link using the  php artisan storage:link command.
source

Title: Echo file URL from Laravel storage

Body:
It looks like even though it sees like your path is fine from the app root folder it's not where laravel is looking for it. Laravel will look inside app/public for your path, resulting in an internal app/public/storage/public/bd0e2f7f.png which, unless you've created a symbolic link between the app/storage/public and `app/public, wont find the file.

The solution, taken from the documentation, is to run:

php artisan storage:link

from the command line which creates the above-mentioned link, and will allow you to access the file with the url http://localhost:8000/storage/bd0e2f7f.png, not http://localhost:8000/storage/public/bd0e2f7f.png

From the docs

The storage/app/public directory may be used to store user-generated files, such as profile avatars, that should be publicly accessible. You should create a symbolic link at  public/storage which points to this directory. You may create the link using the  php artisan storage:link command.
source


问:
<rich:listShuttle> usage
```<code><rich:listShuttle sourceValue="#{positionList.resultlist)}"

      targetValue="#{cvHome.instance.positions}"

       var="pos"
       sourceCaptionLabel="Current Positions"
       targetCaptionLabel="Interested Positions"
       sourceListWidth="300"
       targetListWidth="300"">
     <rich:column>
          <f:facet name="header">Positon Name</f:facet>
          <h:outputText value="#{pos.name}"/>
     </rich:column>
     <s:convertEntity/>
</rich:listShuttle>
</code>```

Error: javax.el.PropertyNotFoundException: /cvGiris.xhtml @526,48 sourceValue="#{positionList.resultList}": Property 'resultList' not writable on type java.util.List

How can i handle with this problem ???

答:
The exception is telling that the setter is missing. Add it to the bean with the name positionList:

```<code>public void setResultList(List<Result> resultList) {
    this.resultList = resultList;
}
</code>```

Title: <rich:listShuttle> usage

Body:
<rich:listShuttle sourceValue="#{positionList.resultlist)}"

      targetValue="#{cvHome.instance.positions}"

       var="pos"
       sourceCaptionLabel="Current Positions"
       targetCaptionLabel="Interested Positions"
       sourceListWidth="300"
       targetListWidth="300"">
     <rich:column>
          <f:facet name="header">Positon Name</f:facet>
          <h:outputText value="#{pos.name}"/>
     </rich:column>
     <s:convertEntity/>
</rich:listShuttle>

Error: javax.el.PropertyNotFoundException: /cvGiris.xhtml @526,48 sourceValue="#{positionList.resultList}": Property 'resultList' not writable on type java.util.List

How can i handle with this problem ???

Body:
The exception is telling that the setter is missing. Add it to the bean with the name positionList:

public void setResultList(List<Result> resultList) {
    this.resultList = resultList;
}


问:
Creating Query on statement (TSQL)
I've got a log file with different functions and steps:

What I need is the Duration of the whole function.
This is my Statement so far:

```<code>SELECT [Id]
      ,[Func]
      ,[Step]
      ,[Timestamp]
      ,CAST((SELECT [Timestamp]
             FROM [LiPimDb].[dbo].[Log_Export_Catalog]
             WHERE [Id] = [Log].[Id]+1)-[Timestamp]AS TIME(3)) AS Duration

FROM [LiPimDb].[dbo].[Log_Export_Catalog] AS [Log]

WHERE Func = 'SP_Create_Export_Catalog'
</code>```

Do I Need to get a subquery and then get the sum of Duration?

答:
It looks like simple GROUP BY is all you need:

```<code>SELECT
    Func
    ,DATEDIFF(second, MAX(Timestamp), MIN(Timestamp)) AS DurationSeconds
FROM [LiPimDb].[dbo].[Log_Export_Catalog] AS [Log]
WHERE Func = 'SP_Create_Export_Catalog'
GROUP BY Func
</code>```

Remove the WHERE filter to see the duration for each function.

Title: Creating Query on statement (TSQL)

Body:
I've got a log file with different functions and steps:

What I need is the Duration of the whole function.
This is my Statement so far:

SELECT [Id]
      ,[Func]
      ,[Step]
      ,[Timestamp]
      ,CAST((SELECT [Timestamp]
             FROM [LiPimDb].[dbo].[Log_Export_Catalog]
             WHERE [Id] = [Log].[Id]+1)-[Timestamp]AS TIME(3)) AS Duration

FROM [LiPimDb].[dbo].[Log_Export_Catalog] AS [Log]

WHERE Func = 'SP_Create_Export_Catalog'

Do I Need to get a subquery and then get the sum of Duration?

Body:
It looks like simple GROUP BY is all you need:

SELECT
    Func
    ,DATEDIFF(second, MAX(Timestamp), MIN(Timestamp)) AS DurationSeconds
FROM [LiPimDb].[dbo].[Log_Export_Catalog] AS [Log]
WHERE Func = 'SP_Create_Export_Catalog'
GROUP BY Func

Remove the WHERE filter to see the duration for each function.


问:
Longest common suffix
I  I would like to find the longest common suffix of two strings in Scala.

```<code>def longestSuffix(s1: String, s2: String) = {
  val it = (s1.reverseIterator zip s2.reverseIterator) takeWhile {case (x, y) => x == y}
  it.map (_._1).toList.reverse.mkString
}
</code>```

This code is clumsy and probably inefficient (e.g. because of reversing). How would find the longest common suffix functionally, i.e. without mutable variables ?

答:
I came up with a solution like this:```def commonSuffix(s1: String, s2: String): String = {
  val n = (s1.reverseIterator zip s2.reverseIterator) // mutable !
            .takeWhile {case (a, b) => a == b}
            .size
  s1.substring(s1.length - n) // is it efficient ?
}```

Note that I am using substring for efficiency (not sure if it's correct).

This solution also is not completely "functional" since I am using reverseIterator despite it's mutable because I did not find another way to iterate over strings in reverse order. How would you suggest fix/improve it ?

Title: Longest common suffix

Body:
I  I would like to find the longest common suffix of two strings in Scala.

def longestSuffix(s1: String, s2: String) = {
  val it = (s1.reverseIterator zip s2.reverseIterator) takeWhile {case (x, y) => x == y}
  it.map (_._1).toList.reverse.mkString
}

This code is clumsy and probably inefficient (e.g. because of reversing). How would find the longest common suffix functionally, i.e. without mutable variables ?

Body:
I came up with a solution like this:
def commonSuffix(s1: String, s2: String): String = {
  val n = (s1.reverseIterator zip s2.reverseIterator) // mutable !
            .takeWhile {case (a, b) => a == b}
            .size
  s1.substring(s1.length - n) // is it efficient ?
}

Note that I am using substring for efficiency (not sure if it's correct).

This solution also is not completely "functional" since I am using reverseIterator despite it's mutable because I did not find another way to iterate over strings in reverse order. How would you suggest fix/improve it ?


问:
sci-kit learn: random forest classifier giving ValueError
So my random forest classifier was running just fine until I added in new features. I keep getting the following error code when I try to run it:

```<code>   \Anaconda2\lib\site-packages\sklearn\utils\validation.pyc in _assert_all_finite(X)
         56             and not np.isfinite(X).all()):
         57         raise ValueError("Input contains NaN, infinity"
    ---> 58                          " or a value too large for %r." % X.dtype)
         59
         60

    ValueError: Input contains NaN, infinity or a value too large for dtype('float32').
</code>```

train and test are both np.DataFrame objects read from csv files. I'm trying to add some more features for a better predictor, but end up getting the above error whenever I try fitting. I did try removing NaN and infinite values but still get the same error.

Below is my code:

```<code>from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss
def features(df):
    df["num_photos"] = df["photos"].apply(len)
    df["num_features"] = df["features"].apply(len)
    df["year_created"] = df["created"].dt.year
    df["month_created"] = df["created"].dt.month
    df["day_created"] = df["created"].dt.day
    df["desc_len"] = df["description"].apply(lambda x: len(x.split(" ")))
    #New features begin here
    df["pricePerBed"] = df['price'] / df['bedrooms']
    df["pricePerBath"] = df['price'] / df['bathrooms']
    df["pricePerRoom"] = df['price'] / (df['bedrooms'] + df['bathrooms'])
    df["bedPerBath"] = df['bedrooms'] / df['bathrooms']
    df["bedBathDiff"] = df['bedrooms'] - df['bathrooms']
    df["bedBathSum"] = df["bedrooms"] + df['bathrooms']
    df["bedsPerc"] = df["bedrooms"] / (df['bedrooms'] + df['bathrooms'])

    df = df.replace([np.inf, -np.inf], np.nan)
    df = df.fillna(1)

    return df

features(train)
features(test)

key_features = ["bathrooms", "bedrooms", "latitude", "longitude", "year_created",
                "month_created", "day_created", "price", "num_photos", "num_features", "desc_len",
                "pricePerBed",
                "pricePerBath",
                "pricePerRoom",
                #"bedPerBath",
                "bedBathDiff",
                "bedBathSum"]

X = train[key_features]
y = train["interest_level"]

X.fillna(1) #I tried getting rid of NaN

X.isnull().any()
</code>```

The bedPerBath variable was giving a True for isnull().any() so I left it out, and the rest all gave me False. However, when I try to fit the estimator I still get the "ValueError".

```<code>X_train, X_cv, y_train, y_cv = train_test_split(X, y, test_size = 0.3)

X_train.isnull().any()

clfRF = RandomForestClassifier(n_estimators = 1000)
clfRF.fit(X_train, y_train)

#CV
y_cv_pred = clfRF.predict_proba(X_cv)
log_loss(y_cv, y_cv_pred)
</code>```

I noticed the error message says too large for dtype('float32'), while my values are largely float64, could this be leading to the error? If so why?

Thank you.

答:
try:</p>

```<code>import numpy as np
X_train, X_cv, y_train, y_cv = train_test_split(np.nan_to_num(X), y, test_size = 0.3)

clfRF = RandomForestClassifier(n_estimators = 1000)
clfRF.fit(X_train, y_train)

#CV
y_cv_pred = clfRF.predict_proba(X_cv)
log_loss(y_cv, y_cv_pred)
</code>```

Body:
So my random forest classifier was running just fine until I added in new features. I keep getting the following error code when I try to run it:

   \Anaconda2\lib\site-packages\sklearn\utils\validation.pyc in _assert_all_finite(X)
         56             and not np.isfinite(X).all()):
         57         raise ValueError("Input contains NaN, infinity"
    ---> 58                          " or a value too large for %r." % X.dtype)
         59
         60

    ValueError: Input contains NaN, infinity or a value too large for dtype('float32').

train and test are both np.DataFrame objects read from csv files. I'm trying to add some more features for a better predictor, but end up getting the above error whenever I try fitting. I did try removing NaN and infinite values but still get the same error.

Below is my code:

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss
def features(df):
    df["num_photos"] = df["photos"].apply(len)
    df["num_features"] = df["features"].apply(len)
    df["year_created"] = df["created"].dt.year
    df["month_created"] = df["created"].dt.month
    df["day_created"] = df["created"].dt.day
    df["desc_len"] = df["description"].apply(lambda x: len(x.split(" ")))
    #New features begin here
    df["pricePerBed"] = df['price'] / df['bedrooms']
    df["pricePerBath"] = df['price'] / df['bathrooms']
    df["pricePerRoom"] = df['price'] / (df['bedrooms'] + df['bathrooms'])
    df["bedPerBath"] = df['bedrooms'] / df['bathrooms']
    df["bedBathDiff"] = df['bedrooms'] - df['bathrooms']
    df["bedBathSum"] = df["bedrooms"] + df['bathrooms']
    df["bedsPerc"] = df["bedrooms"] / (df['bedrooms'] + df['bathrooms'])

    df = df.replace([np.inf, -np.inf], np.nan)
    df = df.fillna(1)

    return df

features(train)
features(test)

key_features = ["bathrooms", "bedrooms", "latitude", "longitude", "year_created",
                "month_created", "day_created", "price", "num_photos", "num_features", "desc_len",
                "pricePerBed",
                "pricePerBath",
                "pricePerRoom",
                #"bedPerBath",
                "bedBathDiff",
                "bedBathSum"]

X = train[key_features]
y = train["interest_level"]

X.fillna(1) #I tried getting rid of NaN

X.isnull().any()

The bedPerBath variable was giving a True for isnull().any() so I left it out, and the rest all gave me False. However, when I try to fit the estimator I still get the "ValueError".

X_train, X_cv, y_train, y_cv = train_test_split(X, y, test_size = 0.3)

X_train.isnull().any()

clfRF = RandomForestClassifier(n_estimators = 1000)
clfRF.fit(X_train, y_train)

#CV
y_cv_pred = clfRF.predict_proba(X_cv)
log_loss(y_cv, y_cv_pred)

I noticed the error message says too large for dtype('float32'), while my values are largely float64, could this be leading to the error? If so why?

Thank you.

Body:
try:

import numpy as np
X_train, X_cv, y_train, y_cv = train_test_split(np.nan_to_num(X), y, test_size = 0.3)

clfRF = RandomForestClassifier(n_estimators = 1000)
clfRF.fit(X_train, y_train)

#CV
y_cv_pred = clfRF.predict_proba(X_cv)
log_loss(y_cv, y_cv_pred)


问:
YARDoc (Documentation generator) for PHP
Does anybody know a comparable documentation for PHP/CakePHP ?

http://yardoc.org/ makes a pretty decent looking documentation for Ruby and I'm looking for a comparable-quality looking for PHP.

答:
Burzum's answer was correct sometime back but now api_generator project is unmaintained and they are suggesting to use APIGen or PHPDocumentor instead.

I've used PHPDocumentor and it generates really nice, easy to understand API Doc.

Hope it help someone.


问:
How to run selenium scripts written in java from jmeter?
I am trying to use my Selenium scripts in java with JMeter's WebDriver  Sampler.

Inside the webdriver sampler, the language is seleced to java, and the following code added:

```<code>package automationFramework;

public class FirstTestCase {

    public static void main(String[] args) {

        // Create a new instance of the Firefox driver
        WebDriver driver = new ChromeDriver();

        //Launch the Online Store Website
        driver.get("www.google.com");

        // Print a Log In message to the screen
        System.out.println("Successfully opened the website www.google.com");

        //Wait for 5 Sec
        Thread.sleep(5);

        // Close the driver
        driver.quit();
    }
}
</code>```

I am facing the following error:

```<code>java.net.MalformedURLException: unknown protocol: data
at java.net.URL.<init>(URL.java:600)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at com.googlecode.jmeter.plugins.webdriver.sampler.WebDriverSampler.sample(WebDriverSampler.java:80)
at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:475)
at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:418)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:249)
at java.lang.Thread.run(Thread.java:745)
</code>```

However, tests written in javascripts work just fine.

What is the problem here? How to solve it?

答: Another way you could do this is extract you webdriver test in a jar file then run in using a junit test in JMeter.</p>

Body:
I am trying to use my Selenium scripts in java with JMeter's WebDriver  Sampler.

Inside the webdriver sampler, the language is seleced to java, and the following code added:

package automationFramework;

public class FirstTestCase {

    public static void main(String[] args) {

        // Create a new instance of the Firefox driver
        WebDriver driver = new ChromeDriver();

        //Launch the Online Store Website
        driver.get("www.google.com");

        // Print a Log In message to the screen
        System.out.println("Successfully opened the website www.google.com");

        //Wait for 5 Sec
        Thread.sleep(5);

        // Close the driver
        driver.quit();
    }
}

I am facing the following error:

java.net.MalformedURLException: unknown protocol: data
at java.net.URL.<init>(URL.java:600)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at com.googlecode.jmeter.plugins.webdriver.sampler.WebDriverSampler.sample(WebDriverSampler.java:80)
at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:475)
at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:418)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:249)
at java.lang.Thread.run(Thread.java:745)

However, tests written in javascripts work just fine.

What is the problem here? How to solve it?


问:
PHP values from select into array for json
Hey i am trying to add my selected resultset into an array to send it as a response to my angularjs function

this is my code

```<code>include 'dbconnect.php';

global $mysqli;

$sql = "SELECT `id`, `name`, `stock`, `pzn` FROM `pda_articles`";

$result = mysqli_query($mysqli, $sql) OR die(mysqli_error($mysqli));

$data = array();

if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    print json_encode($data);
} else {
    echo "no";
}
</code>```

$data[] = $row should work but it doesnt.. $data[] = $row['id'] works but i have no idea how to add the other columns...

maybe you could help me

this is my output with console.log

Thanks :)

答:
if i write $data = var_dump($row); and open it into the browser it gives me that output:

array(4) { ["id"]=> string(1) "1" ["name"]=> string(22) "Handschuhe Vinyl Gr. M" ["stock"]=> string(1) "7" ["pzn"]=> string(6) "990304" } array(4) { ["id"]=> string(1) "2" ["name"]=> string(22) "Handschuhe Latex Gr. M" ["stock"]=> string(1) "7" ["pzn"]=> string(6) "990238" } array(4) { ["id"]=> string(1) "3" ["name"]=> string(22) "Handschuhe Latex Gr. L" ["stock"]=> string(1) "2" ["pzn"]=> string(6) "990267" } array(4) { ["id"]=> string(1) "4" ["name"]=> string(26) "Fl�chendesinfektionsmittel" ["stock"]=> string(1) "8" ["pzn"]=> string(8) "10795578" } null

Body:
Hey i am trying to add my selected resultset into an array to send it as a response to my angularjs function

this is my code

include 'dbconnect.php';

global $mysqli;

$sql = "SELECT `id`, `name`, `stock`, `pzn` FROM `pda_articles`";

$result = mysqli_query($mysqli, $sql) OR die(mysqli_error($mysqli));

$data = array();

if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    print json_encode($data);
} else {
    echo "no";
}

$data[] = $row should work but it doesnt.. $data[] = $row['id'] works but i have no idea how to add the other columns...

maybe you could help me

this is my output with console.log

Thanks :)


问:
Why should a Java programmer care about year 2038 bug?
Year 2038 Bug is all over the web, But this seems to be a unix issue. How will this affect java Date ?</p>

答:
What makes you think it does?  Java's Date class stores a 64-bit long (not 32-bit, as with Y2K38).  It also stores milliseconds, which decreases the range, but only slightly (equivalent of ~10 bits).

In Java, we have the year 292278994 bug.


问:
Convert array values to object keys
I do a get which returns me a json object like so:

"data": [
  [
    "2016 Pass/Fail Rates by Test Centre",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    ""
  ],
  [
    "",
    "Passes",
    "",
    "No ID",
    "",
    "Fails",
    "",
    "Fail Dangerous",
    "",
    "Total"
  ],
  [
    "Sometown",
    "8,725",
    "53.40%",
    "140",
    "0.90%",
    "7,417",
    "45.40%",
    "48",
    "0.30%",
    "16,330"
  ],
  [
    "Some Other Town",
    "12,778",
    "44.80%",
    "193",
    "0.70%",
    "15,422",
    "54.10%",
    "103",
    "0.40%",
    "28,496"
  ],
  [...many more identically formatted arrays...]
```
<p>and I would like to end up with:</p>
<pre class="lang-js prettyprint-override"><code>[{
    "Location": "Sometown",
    "Passes": 8,
    725,
    "Pass%": 53.40 % ,
    "No ID": 140,
    "NoID%": 0.90 % ,
    "Fails": 7,
    417,
    "Fail%": 45.40 % ,
    "Fail Dangerous": 48,
    "FailDangerous%": 0.30 % ,
    "Total": 16,
    330
  }, {
    "Location": "Some Other Town",
    "Passes": 8,
    725,
    etc etc...
</code>```

So I want to ignore the first array inside the "data" array, use the values of the second array as keys (and replace the empty strings with something more useful) and the values in all remaining arrays as values in the resulting object.

So it is quite the multipart problem, though I suspect a fairly simple one.  What is the simplest way to do that - and if different, what is the leanest way to do it in terms of processing/page load?

Thanks in advance,

答:
You can iterate over your array while adding your index and value into an object...

You can find an example on how you can iterate objects and arrays here and an example here

Generally, to add an item to object

```<code>var array = [{"Location":"Sometown"}, {"Location2":"Sometown2"},    {"Location3":"Sometown3"}],
object = {};
array.forEach(function(element, index) {
    object[index] = element;
});
console.log(object);
</code>```

Title: Convert array values to object keys

Body:
I do a get which returns me a json object like so:

"data": [
  [
    "2016 Pass/Fail Rates by Test Centre",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    ""
  ],
  [
    "",
    "Passes",
    "",
    "No ID",
    "",
    "Fails",
    "",
    "Fail Dangerous",
    "",
    "Total"
  ],
  [
    "Sometown",
    "8,725",
    "53.40%",
    "140",
    "0.90%",
    "7,417",
    "45.40%",
    "48",
    "0.30%",
    "16,330"
  ],
  [
    "Some Other Town",
    "12,778",
    "44.80%",
    "193",
    "0.70%",
    "15,422",
    "54.10%",
    "103",
    "0.40%",
    "28,496"
  ],
  [...many more identically formatted arrays...]

and I would like to end up with:

[{
    "Location": "Sometown",
    "Passes": 8,
    725,
    "Pass%": 53.40 % ,
    "No ID": 140,
    "NoID%": 0.90 % ,
    "Fails": 7,
    417,
    "Fail%": 45.40 % ,
    "Fail Dangerous": 48,
    "FailDangerous%": 0.30 % ,
    "Total": 16,
    330
  }, {
    "Location": "Some Other Town",
    "Passes": 8,
    725,
    etc etc...

So I want to ignore the first array inside the "data" array, use the values of the second array as keys (and replace the empty strings with something more useful) and the values in all remaining arrays as values in the resulting object.

So it is quite the multipart problem, though I suspect a fairly simple one.  What is the simplest way to do that - and if different, what is the leanest way to do it in terms of processing/page load?

Thanks in advance,

Body:
You can iterate over your array while adding your index and value into an object...

You can find an example on how you can iterate objects and arrays here and an example here

Generally, to add an item to object

var array = [{"Location":"Sometown"}, {"Location2":"Sometown2"},    {"Location3":"Sometown3"}],
object = {};
array.forEach(function(element, index) {
    object[index] = element;
});
console.log(object);