问:
SQLite Open Helper creates empty db
I am so sorry to open a question that has been asked before, but I have already read a lot of replies, tried to change my code to fix it, and I still can't create tables to my SQLite database.

I have also tried to uninstall the app and reinstall, deleted the previous database files to be replace, and the output is always the same.

This is my Open Helper class:

```<code>import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseClass extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "Dados.db";
    private static final int DATABASE_VERSION=1;

    private String primeiraquery = "create table Informacoes (Identificacao VARCHAR(255))";
    Context context;

    public DataBaseClass(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context=context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(primeiraquery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
</code>```

Changing the query to add ' ' or no space between the table name and () also produced the same output.

And this is MainActivity.class

```<code>import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.appname.DataBaseClasses.DataBaseClass;

public class MainActivity extends AppCompatActivity {

    DataBaseClass database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        database=new DataBaseClass(this);
        createBasedados();
    }

    public void createBasedados(){
        database.getReadableDatabase();
    }
}
</code>```

No matter what, I always get Dados.db with 4KB, and when I open it, it's empty, no tables were created.

Other than that, the databases folder also has Dados.db-shm and Dados.db-wal

I also tried the DatabseHelper from Codebind but once again, the output was always the same, empty file with no tables.

UPDATE (2019-06-01 17:29:24Z):

@CommonWares pointed out that

Are you copying all of the files, or are you just copying the .db file? You need all of them.

I was just copying the .db file. After copying all of the 3, I can now see the tables of the database, instead of an empty file.

答:
Please try this :

1.maybe create table Informacoes need id primary key

change VARCHAR(255) to varchar

change  DATABASE_VERSION=1;  to  DATABASE_VERSION=2;

public class DataBaseClass extends SQLiteOpenHelper {

```<code>private static final String DATABASE_NAME = "Dados.db";
private static final int DATABASE_VERSION=2;

private String primeiraquery = "create table Informacoes (_id integer primary key autoincrement,Identificacao varchar)";
Context context;

public DataBaseClass(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.context=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(primeiraquery);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
</code>```

}

Title: SQLite Open Helper creates empty db

Body:
I am so sorry to open a question that has been asked before, but I have already read a lot of replies, tried to change my code to fix it, and I still can't create tables to my SQLite database.

I have also tried to uninstall the app and reinstall, deleted the previous database files to be replace, and the output is always the same.

This is my Open Helper class:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseClass extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "Dados.db";
    private static final int DATABASE_VERSION=1;

    private String primeiraquery = "create table Informacoes (Identificacao VARCHAR(255))";
    Context context;

    public DataBaseClass(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context=context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(primeiraquery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

Changing the query to add ' ' or no space between the table name and () also produced the same output.

And this is MainActivity.class

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.appname.DataBaseClasses.DataBaseClass;

public class MainActivity extends AppCompatActivity {

    DataBaseClass database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        database=new DataBaseClass(this);
        createBasedados();
    }

    public void createBasedados(){
        database.getReadableDatabase();
    }
}

No matter what, I always get Dados.db with 4KB, and when I open it, it's empty, no tables were created.

Other than that, the databases folder also has Dados.db-shm and Dados.db-wal

I also tried the DatabseHelper from Codebind but once again, the output was always the same, empty file with no tables.

UPDATE (2019-06-01 17:29:24Z):

@CommonWares pointed out that

Are you copying all of the files, or are you just copying the .db file? You need all of them.

I was just copying the .db file. After copying all of the 3, I can now see the tables of the database, instead of an empty file.

Body:
Please try this :

1.maybe create table Informacoes need id primary key

change VARCHAR(255) to varchar

change  DATABASE_VERSION=1;  to  DATABASE_VERSION=2;

public class DataBaseClass extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "Dados.db";
private static final int DATABASE_VERSION=2;

private String primeiraquery = "create table Informacoes (_id integer primary key autoincrement,Identificacao varchar)";
Context context;

public DataBaseClass(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.context=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(primeiraquery);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}


来源: stackexchange

问:
Is naming variables after their type a bad practice?
I'm programming C++ using the underscore naming style (as opposed to camel case) which is also used by the STL and boost. However, since both types and variables/functions are named all lower case, a member variable declaration as follows will lead to compiler errors (or at least trouble):

```<code>position position;
</code>```

A member variable named position which is of type position. I don't know how else to name it: It's generally a position, but it is also the position of the object. In camel case, this would be fine with the compiler:

```<code>Position position;
</code>```

But in C++ it causes problems. I don't want to switch to camel case, use Hungarian notation or add a trailing underscore because of that, so I'm wondering: Is it a good practice to name a member like a type anyways?

In C, it is pretty common to use cryptic one-letter variables for this:

```<code>int i;
</code>```

But I find that a bit, well, cryptic:

```<code>position p;
</code>```

Are there any rules of thumb for variable naming I can use to avoid this?

There are more examples in my code if you need something to work on:

```<code>mouse_over(entity entity) // Returns true if the mouse is over the entity

manager &manager; // A reference to the framework's manager

audio audio; // The audio subsystem
</code>```

Edit:

I was curious to see if Bjarne Stroustrup himself has something to say on this issue. Apparently, he hasn't, but he suggests coding conventions that would work around my compiler problems:

For example, capitalize nonstandard library user-defined types and start nontypes with a lowercase letter

That'd be consistent with STL and boost, so I might use that. However, most of you agree that this naming should be avoided whether it compiles or not. So does Stroustrup:

it is unwise to choose names that differ only by capitalization.

答:
No, I do this on occasions and it does not cause problems in the Microsoft world. For example,

```<code>class compiler
{
    symbol_table symbol_table;
};
</code>```

has never caused any confusion. By the way, I called my cat 'cat' and that hasn't caused confusion either.

ContentLicense: CC BY-SA 2.5

Body:
I'm programming C++ using the underscore naming style (as opposed to camel case) which is also used by the STL and boost. However, since both types and variables/functions are named all lower case, a member variable declaration as follows will lead to compiler errors (or at least trouble):

position position;

A member variable named position which is of type position. I don't know how else to name it: It's generally a position, but it is also the position of the object. In camel case, this would be fine with the compiler:

Position position;

But in C++ it causes problems. I don't want to switch to camel case, use Hungarian notation or add a trailing underscore because of that, so I'm wondering: Is it a good practice to name a member like a type anyways?

In C, it is pretty common to use cryptic one-letter variables for this:

int i;

But I find that a bit, well, cryptic:

position p;

Are there any rules of thumb for variable naming I can use to avoid this?

There are more examples in my code if you need something to work on:

mouse_over(entity entity) // Returns true if the mouse is over the entity

manager &manager; // A reference to the framework's manager

audio audio; // The audio subsystem

Edit:

I was curious to see if Bjarne Stroustrup himself has something to say on this issue. Apparently, he hasn't, but he suggests coding conventions that would work around my compiler problems:

For example, capitalize nonstandard library user-defined types and start nontypes with a lowercase letter

That'd be consistent with STL and boost, so I might use that. However, most of you agree that this naming should be avoided whether it compiles or not. So does Stroustrup:

it is unwise to choose names that differ only by capitalization.

Body:
No, I do this on occasions and it does not cause problems in the Microsoft world. For example,

class compiler
{
    symbol_table symbol_table;
};

has never caused any confusion. By the way, I called my cat 'cat' and that hasn't caused confusion either.

ContentLicense: CC BY-SA 4.0


问:
NodeRED: How to access configuration node?
How can a configuration node be accessed (for read and write) or even be created inside a function node?

My scenario: I have a ModbusTCP node that uses configuration nodes for host/port settings. I need to create different configuration nodes inside my flow.

答:
Generally you would define a config node as part of your package and provide a property on your main node to link to it. You could then have lots of different config nodes configured with different values. In general, I would probably have preferred having properties on the main node if it varies for all of them and just have the shared stuff like credentials, server address etc in a common config node.
All nodes can have whatever properties you would like and they can be set in the UI.
Properties on nodes: https://nodered.org/docs/creating-nodes/properties
defining a config node: https://nodered.org/docs/creating-nodes/config-nodes

You access your config from the config parameter sent to the node when loaded

```<code>function komfoventNode (config) {
    RED.nodes.createNode(this, config);
    this.komfoUser = RED.nodes.getNode(config.user);
</code>```

The komfoventNode has a property defined as user, which points to my komfoventConfig node.

```<code>defaults: {
            displayNname: {value:""},
            user: {value:"",type:"komfoventConfig", required:true}
        }
</code>```

Body:
Generally you would define a config node as part of your package and provide a property on your main node to link to it. You could then have lots of different config nodes configured with different values. In general, I would probably have preferred having properties on the main node if it varies for all of them and just have the shared stuff like credentials, server address etc in a common config node.
All nodes can have whatever properties you would like and they can be set in the UI.
Properties on nodes: https://nodered.org/docs/creating-nodes/properties
defining a config node: https://nodered.org/docs/creating-nodes/config-nodes

You access your config from the config parameter sent to the node when loaded

function komfoventNode (config) {
    RED.nodes.createNode(this, config);
    this.komfoUser = RED.nodes.getNode(config.user);

The komfoventNode has a property defined as user, which points to my komfoventConfig node.

defaults: {
            displayNname: {value:""},
            user: {value:"",type:"komfoventConfig", required:true}
        }


问:
Python 3 : Getter is not returning the data it should be
I have a parent Class that has a setter that returns queryFiltre value and a getter that is supposed to pass the queryFiltre value to my child Class. queryFiltre Should return an SQL query like "SELECT * FROM Report WHERE GA_RPM > 0 and CAMPAIGN LIKE '%TT%'... ".

The print() in the setter returns a SQL query, but the print() of the getter when called in the child Class returns something like " <main.SimpleGrid object at 0x042AF2B0>".

What's wrong with my code? Please bear with me as I'm still learning and oop is still an abstract concept in my head.

I've added comments in the code so you can see what happens where:

```<code>class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)

        ########### DATABASE CONNECT
        self.path =os.path.dirname(os.path.realpath(__file__))
        self.dbfile = os.path.join(self.path , "report.db")
        self.db_conn = sqlite3.connect(self.dbfile)
        self.theCursor =  self.db_conn.cursor()
        ########### SETTING FILE CONNECT
        self.configFile = os.path.join(self.path , "config.ini")
        self.config = configparser.ConfigParser()
        self.config.read(self.configFile)

        ########### Calling th Getter and Setter
        self.queryFiltre = self.setQueryFiltre(self)
        self.getQueryFiltre()

    ########### Setter
    def setQueryFiltre(self,queryFiltre):

            if self.config.get('Network', 'taboola') == "true" and self.config.get('Network', 'ob') == "true":
                network = ""
            elif self.config.get('Network', 'taboola') == "true" and self.config.get('Network', 'ob') == "false":
                network = " and CAMPAIGN LIKE '%TB%'"
            elif self.config.get('Network', 'outbrain') == "true" and self.config.get('Network', 'tb') == "false":
                network = " and CAMPAIGN LIKE '%OB%'"
            else:
                network = ""

            queryFiltre = "SELECT * FROM Report WHERE  GA_RPM > 0 " + network + "  and STATUS = '1' ORDER BY CLICKS DESC"

            ########### The print below returns the right value of queryFiltre
            print(queryFiltre)

            return queryFiltre

        ########### Getter
        def getQueryFiltre(queryFiltre):
            queryFiltre = queryFiltre
            return queryFiltre

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, 0, "Native Ads Reports V1.0", size=(1400,800))
        self.grid = SimpleGrid(self, log)

        ########### Calling the Getter of the parent Class
        self.queryFiltre = self.grid.getQueryFiltre()

        ########### DATABASE CONNECT
        self.path =os.path.dirname(os.path.realpath(__file__))
        self.dbfile = os.path.join(self.path , "report.db")
        self.db_conn = sqlite3.connect(self.dbfile)
        self.theCursor =  self.db_conn.cursor()

        ########### The print below returns a bad value, something like : <__main__.SimpleGrid object at 0x042AF2B0>
        print(self.queryFiltre)
</code>```

You'll notice also that I've added the script to define the path and to connect to the db in both classes, is there a way to do it only once in the first Class?

Thank you,

答:
Your getQueryFiltre() in SimpleGrid has the wrong indentation, and is missing the first argument self. The way you've written it, it is a function within the scope of your setQueryFiltre(), and it isn't called from anywhere.

It should be indented to the same level as setQueryFiltre, and have a first argument self.

By the way, you shouldn't be using getters. It's not pythonic, as explained here: https://stackoverflow.com/a/36943813/11451509

Body:
I have a parent Class that has a setter that returns queryFiltre value and a getter that is supposed to pass the queryFiltre value to my child Class. queryFiltre Should return an SQL query like "SELECT * FROM Report WHERE GA_RPM > 0 and CAMPAIGN LIKE '%TT%'... ".

The print() in the setter returns a SQL query, but the print() of the getter when called in the child Class returns something like " <main.SimpleGrid object at 0x042AF2B0>".

What's wrong with my code? Please bear with me as I'm still learning and oop is still an abstract concept in my head.

I've added comments in the code so you can see what happens where:

class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)

        ########### DATABASE CONNECT
        self.path =os.path.dirname(os.path.realpath(__file__))
        self.dbfile = os.path.join(self.path , "report.db")
        self.db_conn = sqlite3.connect(self.dbfile)
        self.theCursor =  self.db_conn.cursor()
        ########### SETTING FILE CONNECT
        self.configFile = os.path.join(self.path , "config.ini")
        self.config = configparser.ConfigParser()
        self.config.read(self.configFile)

        ########### Calling th Getter and Setter
        self.queryFiltre = self.setQueryFiltre(self)
        self.getQueryFiltre()

    ########### Setter
    def setQueryFiltre(self,queryFiltre):

            if self.config.get('Network', 'taboola') == "true" and self.config.get('Network', 'ob') == "true":
                network = ""
            elif self.config.get('Network', 'taboola') == "true" and self.config.get('Network', 'ob') == "false":
                network = " and CAMPAIGN LIKE '%TB%'"
            elif self.config.get('Network', 'outbrain') == "true" and self.config.get('Network', 'tb') == "false":
                network = " and CAMPAIGN LIKE '%OB%'"
            else:
                network = ""

            queryFiltre = "SELECT * FROM Report WHERE  GA_RPM > 0 " + network + "  and STATUS = '1' ORDER BY CLICKS DESC"

            ########### The print below returns the right value of queryFiltre
            print(queryFiltre)

            return queryFiltre

        ########### Getter
        def getQueryFiltre(queryFiltre):
            queryFiltre = queryFiltre
            return queryFiltre

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, 0, "Native Ads Reports V1.0", size=(1400,800))
        self.grid = SimpleGrid(self, log)

        ########### Calling the Getter of the parent Class
        self.queryFiltre = self.grid.getQueryFiltre()

        ########### DATABASE CONNECT
        self.path =os.path.dirname(os.path.realpath(__file__))
        self.dbfile = os.path.join(self.path , "report.db")
        self.db_conn = sqlite3.connect(self.dbfile)
        self.theCursor =  self.db_conn.cursor()

        ########### The print below returns a bad value, something like : <__main__.SimpleGrid object at 0x042AF2B0>
        print(self.queryFiltre)

You'll notice also that I've added the script to define the path and to connect to the db in both classes, is there a way to do it only once in the first Class?

Thank you,


问:
Use Socket permantently to handle Clientsession or create new one for every request
So i am quite new to Sockets and I have to create a Server-Client-App for school.

I expect a client to request something from the server multiple times during his runtime.

I am uncertain wether I should make a new java.net.Socket for every Request I get (Client opens new socket every time and Java Serversocket accepts)
or use a single socket and keep that during the client's runtime.

答:
That strongly depends on how frequently the socket is used.

E.g. if you know that the client will send a request to the server every 50 milliseconds it would be easier to just keep the socket opened.

But if you know the client will only request information from the socket every 5 minutes it's probably better to close the connection and create a new one when needed. Same if you don't know when the next request will be created.

Creating a new Socket on server-side is not very expensive, so it's probably better to just close the connection if it's not used very frequently.

An exception could be a special socket, that needs authentication or other expensive stuff on creation, but that's probably not the case in a school project.

So in general: It depends on the usage of the socket, but if you're unsure whether it's used very frequently or not better close it and open it again when needed.


问:
When i select , only one column is checked without duplicates
I have a 2 table like this:

first table
+------------+---------------+--------+
| pk         | user_one      |user_two|
+------------+---------------+--------+
second table
+------------+---------------+--------+----------------+----------------+
| pk         | sender        |receiver|fk of firsttable|content        |
+------------+---------------+--------+----------------+----------------+
```

<p>First and second table have one to many(1:N) relations.</p>

<p>There are many records in second table:</p>

```| pk    | sender|receiver|fk of firsttable|content           |
|120    |car224 |car223  |1               |test message1 to 223
|121    |car224 |car223  |1               |test message2 to 223
|122    |car224 |car225  |21              |test message1 to 225
|123    |car224 |car225  |21              |test message2 to 225
|124    |car224 |car225  |21              |test message3 to 225
|125    |car224 |car225  |21              |test message4 to 225

```

<p>I need to find if <code>fk</code> has the same value and I want the row with the largest <code>pk</code>.</p>

<p>I've changed the above column name to make it easier to understand.</p>

<p>Here is the actual <code>sql</code> I've tried so far:</p>

```select *
  from (select rownum rn,
               mr.mrno,
               mr.user_one,
               mr.user_two,
               m.mno,
               m.content
          from tbl_messagerelation mr,
               tbl_message m
          where (mr.user_one = 'car224' or
                 mr.user_two='car224') and
                m.rowid in (select max(rowid)
                              from tbl_message
                              group by m.mno) and
                rownum <= 1*20)
  where rn > (1-1) * 20
```

<p>And this is the result:</p>

```+---------+-------+----------+----------+-------------------------+----------------------+
|  rn     |  mrno | user_one | user_two | mno(pk of second table) |        content       |
+---------+-------+----------+----------+-------------------------+----------------------+
|       1 |     1 | car224   | car223   |                     125 | test message4 to 225 |
|       2 |    21 | car224   | car225   |                     125 | test message4 to 225 |
+---------+-------+----------+----------+-------------------------+----------------------+
```

<p>My desired result is something like this:</p>

```+---------+---------+----------+--------------------+----------------------+
|  fk     |  sender | receiver | pk of second table | content              |
+---------+---------+----------+--------------------+----------------------+
|       1 | car224  | car223   |                121 | test message2 to 223 |
|      21 | car224  | car223   |                125 | test message4 to 225 |
+---------+---------+----------+--------------------+----------------------+
```

答:
Your table description when compared to your query is confusing me. However, what I could understand was that you are probably looking for row_number().

An important advice is to use standard explicit JOIN syntax rather than outdated a,b syntax for joins. Join keys were not clear to me and you may replace it appropriately in your final query.

```<code>select * from
(
select mr.*, m.*, row_number() over ( partition by m.fk order by m.pk desc ) as rn
from tbl_messagerelation mr join  tbl_message m on mr.? = m.?
) where rn =1
</code>```

Or perhaps  you don't need that join at all

```<code>select * from
(
select  m.*, row_number() over ( partition by m.fk order by m.pk desc ) as rn
 from  tbl_message m
) where rn =1
</code>```

Body:
I have a 2 table like this:

first table
+------------+---------------+--------+
| pk         | user_one      |user_two|
+------------+---------------+--------+
second table
+------------+---------------+--------+----------------+----------------+
| pk         | sender        |receiver|fk of firsttable|content        |
+------------+---------------+--------+----------------+----------------+

First and second table have one to many(1:N) relations.

There are many records in second table:

| pk    | sender|receiver|fk of firsttable|content           |
|120    |car224 |car223  |1               |test message1 to 223
|121    |car224 |car223  |1               |test message2 to 223
|122    |car224 |car225  |21              |test message1 to 225
|123    |car224 |car225  |21              |test message2 to 225
|124    |car224 |car225  |21              |test message3 to 225
|125    |car224 |car225  |21              |test message4 to 225

I need to find if fk has the same value and I want the row with the largest pk.

I've changed the above column name to make it easier to understand.

Here is the actual sql I've tried so far:

select *
  from (select rownum rn,
               mr.mrno,
               mr.user_one,
               mr.user_two,
               m.mno,
               m.content
          from tbl_messagerelation mr,
               tbl_message m
          where (mr.user_one = 'car224' or
                 mr.user_two='car224') and
                m.rowid in (select max(rowid)
                              from tbl_message
                              group by m.mno) and
                rownum <= 1*20)
  where rn > (1-1) * 20

And this is the result:

+---------+-------+----------+----------+-------------------------+----------------------+
|  rn     |  mrno | user_one | user_two | mno(pk of second table) |        content       |
+---------+-------+----------+----------+-------------------------+----------------------+
|       1 |     1 | car224   | car223   |                     125 | test message4 to 225 |
|       2 |    21 | car224   | car225   |                     125 | test message4 to 225 |
+---------+-------+----------+----------+-------------------------+----------------------+

My desired result is something like this:

+---------+---------+----------+--------------------+----------------------+
|  fk     |  sender | receiver | pk of second table | content              |
+---------+---------+----------+--------------------+----------------------+
|       1 | car224  | car223   |                121 | test message2 to 223 |
|      21 | car224  | car223   |                125 | test message4 to 225 |
+---------+---------+----------+--------------------+----------------------+

Body:
Your table description when compared to your query is confusing me. However, what I could understand was that you are probably looking for row_number().

An important advice is to use standard explicit JOIN syntax rather than outdated a,b syntax for joins. Join keys were not clear to me and you may replace it appropriately in your final query.

select * from
(
select mr.*, m.*, row_number() over ( partition by m.fk order by m.pk desc ) as rn
from tbl_messagerelation mr join  tbl_message m on mr.? = m.?
) where rn =1

Or perhaps  you don't need that join at all

select * from
(
select  m.*, row_number() over ( partition by m.fk order by m.pk desc ) as rn
 from  tbl_message m
) where rn =1


问:
Best Way to Create Records in a SQL Server Database to Meet Performance Requirements
I'm currently developing a database system to store the result data from a machine. The data is arriving from the machine via an ethernet connection to a C# application which parses the data and creates records for the data in the database. Our calculations suggest we need to create at least 12000 records a second to keep up with the machine. These records are spread accross ten or so tables.

My initial tests are giving us at most 1800 records per second on one table. My C# code is along the lines of:

```<code> SqlCommand command = new SqlCommand ("insert tablename (column names) values (values)", connection);
 command.ExecuteNonQuery ();
</code>```

which I will admit is a naive attempt.

My questions are:

Is this record creation rate feasible and

What's the best method to acheive the require rate?

Database: SQL Server 2008

Language: C# 2.0

答:
If the data is coming in too fast to be loaded in the database "in real time", then:

Upgrade, get better hardware and software. Of course, the new setup may still not be fast enough (and will you be able to test it before shelling out the $$ ?)

Defer. Have C# (or whatever, if C# isn't fast enough) stream the data into a formatted file (comma delimited, XML, whatever) somewhere, and periodically close it off, start a new file, and have SQL load the data found in the "last" file.

SQL 2008 R2 has a "Stream Insight" feature that might be applicable here, though I'd definitely call it an advanced subject.

Mind you now, 12000 rows at 1 byte per second is a bit under 1 GB a day... if you have 100 bytes per row, that's a bit under 100 GB a day, and 30 TB a month.  Are you sure about those numbers?

ContentLicense: CC BY-SA 3.0

Body:
I'm currently developing a database system to store the result data from a machine. The data is arriving from the machine via an ethernet connection to a C# application which parses the data and creates records for the data in the database. Our calculations suggest we need to create at least 12000 records a second to keep up with the machine. These records are spread accross ten or so tables.

My initial tests are giving us at most 1800 records per second on one table. My C# code is along the lines of:

 SqlCommand command = new SqlCommand ("insert tablename (column names) values (values)", connection);
 command.ExecuteNonQuery ();

which I will admit is a naive attempt.

My questions are:

Is this record creation rate feasible and

What's the best method to acheive the require rate?

Database: SQL Server 2008

Language: C# 2.0


问:
Can someone tell me why this query isn't working please?
Can someone tell me why this query isn’t working please?

```<code>$result = $connect->query( “SELECT *
                            FROM DBdata
                            WHERE catc !=‘121’
                            AND description LIKE ‘%$strm%’
                            OR ttl LIKE ‘%$strm%’
                            AND active = 1” );
</code>```

THE PROBLEM - It IS LISTING ‘catc’ that = 121

I want the result it is giving, but don't want the catc items that equal 121

Thanks!

答:
Your OR is likely what's messing things up.

```<code>SELECT * FROM HWpix
    WHERE catc !='121'
    AND
      (description LIKE '%$strm%'
       OR ttl LIKE '%$strm%')
    AND active = 1
</code>```

Body:
Can someone tell me why this query isn’t working please?

$result = $connect->query( “SELECT *
                            FROM DBdata
                            WHERE catc !=‘121’
                            AND description LIKE ‘%$strm%’
                            OR ttl LIKE ‘%$strm%’
                            AND active = 1” );

THE PROBLEM - It IS LISTING ‘catc’ that = 121

I want the result it is giving, but don't want the catc items that equal 121

Thanks!

Body:
Your OR is likely what's messing things up.

SELECT * FROM HWpix
    WHERE catc !='121'
    AND
      (description LIKE '%$strm%'
       OR ttl LIKE '%$strm%')
    AND active = 1


问:
Multiple radio button groups in one form
Is it possible to have multiple radio button groups in a single form? Usually selecting one button deselects the previous, I just need to have one of a group deselected.</p>

```<code><form>
    <fieldset id="group1">
        <input type="radio" value="">
        <input type="radio" value="">
    </fieldset>

    <fieldset id="group2">
        <input type="radio" value="">
        <input type="radio" value="">
        <input type="radio" value="">
    </fieldset>
</form>
</code>```

答:
in input field make name same
like                                         </p>

```<code><input type="radio" name="option" value="option1">
<input type="radio" name="option" value="option2" >
<input type="radio" name="option" value="option3" >
<input type="radio" name="option" value="option3" >
</code>```

Body:
Is it possible to have multiple radio button groups in a single form? Usually selecting one button deselects the previous, I just need to have one of a group deselected.

<form>
    <fieldset id="group1">
        <input type="radio" value="">
        <input type="radio" value="">
    </fieldset>

    <fieldset id="group2">
        <input type="radio" value="">
        <input type="radio" value="">
        <input type="radio" value="">
    </fieldset>
</form>

Body:
in input field make name same
like

<input type="radio" name="option" value="option1">
<input type="radio" name="option" value="option2" >
<input type="radio" name="option" value="option3" >
<input type="radio" name="option" value="option3" >


问:
Xcode can’t find headers from an embedded framework
I have two frameworks installed through Carthage, located in ${PROJECT_DIR}/Carthage/Build/ (the default Carthage path). In my app’s target, I have dragged both frameworks to the Embedded Binaries section as described in the docs. Now no matter what I do, Xcode complains that it can’t find the headers from these two frameworks. What I have tried:

The headers are there, I can click through them in the Xcode tree view and in Finder.

In the frameworks’ Xcode projects, the headers are listed as Public under Build Phases → Headers.

Setting Header Search Paths to ${PROJECT_DIR}/Carthage/Build/** doesn’t help. (WTF?)

Making a clean build and deleting all derived data did not help.

Tried both in Xcode 6 and Xcode 7 beta 5. This is an OS X target, if that makes a difference.

答:
Due to an Xcode defect, it cannot accommodate a search path that has a directory name with a space in it. This causes Xcode to fail to find framework includes at the end of the search path.

Example: #import <C0re/C0re.h>

C0re is a custom framework that has many years of macOS development knowledge built into it (since 1984). I want to use it from a central location for all my projects: ~/Development/Projects/Frameworks Library/

and inside ~/Development/Projects/Frameworks Library/ I have:

In the project within which I want to use the framework I have:

And it fails to find the import/include:

I then:

Removed the framework from the project (just delete the reference not the framework itself)

Removed the space from the folder name in the framework's path (aka Frameworks Library to FrameWorksLibrary)

Added the framework to the project again

Changed the System Frameworks Search Paths under Build Settings to remove the space (for me FrameWorksLibrary)

and with no editing of any source code... The Error Is Gone:

Note: (another related Xcode defect... Xcode variable updates...)
If you are using user-defined variables or Custom Paths under Locations in Preferences, you will need to perform some bogus edit on the entry you made in System Framework Search Paths to trigger Xcode to re-evaluate the system variable(s) you are using in your paths. Otherwise you can change the Xcode system variable all day long and not have change in the ability for Xcode to find the header.
And if your path is really long like mine really are, you may never see that the path is not changing...

And for one more kick in the pants, if you named your Derived Data folders with a space (vs DerivedData) and try to reach into them directly for the framework build... yep, it'll gitcha.


问:
UITextField and UIButton unresponsive after signOut segue swift
In my Xcode project, after signing out and performing a segue, my text fields and buttons are unresponsive and won't show the keyboard, editing mark or allow me to edit. I am not getting an error anywhere, however.

ViewController.swift:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()
    imagePicker = UIImagePickerController()
    imagePicker.allowsEditing = true
    imagePicker.delegate = self
    scrollView.isScrollEnabled = false
    self.reset()
}
</code>```

FeedVC.swift:

```<code>@objc func signOut(_ sender: AnyObject) {
    KeychainWrapper.standard.removeObject(forKey: "uid")
    do {
        try Auth.auth().signOut()
    } catch let signOutError as NSError {
        print ("Error signing out: %@", signOutError)
    }
    performSegue(withIdentifier: "signOut", sender: nil)
}
</code>```

Main.storyboard:

signOut Segue:

答:
By the names you have picked, I’m guessing after signout what you really want to do is an unwind segue, basically returning to the original screen. The way you have it set up I believe, you’re actually creating a brand new view controller when you perform the segue from the tableview to the original view when really you want to go back to the one that has already been made.

What you actually want is an unwind segue, which will actually get you back to the original. This solves the problem mentioned by the other commenter (vicious cycle of segues). https://medium.com/@mimicatcodes/create-unwind-segues-in-swift-3-8793f7d23c6f

Body:
In my Xcode project, after signing out and performing a segue, my text fields and buttons are unresponsive and won't show the keyboard, editing mark or allow me to edit. I am not getting an error anywhere, however.

ViewController.swift:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()
    imagePicker = UIImagePickerController()
    imagePicker.allowsEditing = true
    imagePicker.delegate = self
    scrollView.isScrollEnabled = false
    self.reset()
}

FeedVC.swift:

@objc func signOut(_ sender: AnyObject) {
    KeychainWrapper.standard.removeObject(forKey: "uid")
    do {
        try Auth.auth().signOut()
    } catch let signOutError as NSError {
        print ("Error signing out: %@", signOutError)
    }
    performSegue(withIdentifier: "signOut", sender: nil)
}

Main.storyboard:

signOut Segue:


问:
How to create Custom Ratings bar in Android
Hello all i need to perform Ratings in my application... SO i need to create custom Ratings bar... Can Anyone Help me in this?</p>

答:
I investigated the original source,

and here is my result.

styles.xml (res/values)

```<code><!-- RatingBar -->
<style name="RatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:progressDrawable">@drawable/ratingbar_full</item>
    <item name="android:indeterminateDrawable">@drawable/ratingbar_full</item>
    <item name="android:minHeight">13.4dp</item>
    <item name="android:maxHeight">13.4dp</item>
</style>
</code>```

ratingbar_full.xml (res/drawable)

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/secondaryProgress" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/progress" android:drawable="@drawable/btn_rating_star_on_normal" />
</layer-list>
</code>```

btn_rating_star_off_normal.png (res/drawable-xxhdpi)

btn_rating_star_on_normal.png (res/drawable-xxhdpi)

activity_ratingbar.xml (res/layout)

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatRatingBar
        android:id="@+id/ratingbar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="13.4dp"
        android:isIndicator="false"
        android:numStars="5"
        android:rating="2.6"
        android:secondaryProgressTint="#00000000"
        android:stepSize="0.1" />
</FrameLayout>
</code>```

This is the result.

Note that I added the actual height(13.4dp) of ratingbar in layout_height property, because if it is wrap_content it will draw lines below stars. (in my case only in a preview of Android Studio)

Body:
I investigated the original source,

and here is my result.

styles.xml (res/values)

<!-- RatingBar -->
<style name="RatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:progressDrawable">@drawable/ratingbar_full</item>
    <item name="android:indeterminateDrawable">@drawable/ratingbar_full</item>
    <item name="android:minHeight">13.4dp</item>
    <item name="android:maxHeight">13.4dp</item>
</style>

ratingbar_full.xml (res/drawable)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/secondaryProgress" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/progress" android:drawable="@drawable/btn_rating_star_on_normal" />
</layer-list>

btn_rating_star_off_normal.png (res/drawable-xxhdpi)

btn_rating_star_on_normal.png (res/drawable-xxhdpi)

activity_ratingbar.xml (res/layout)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatRatingBar
        android:id="@+id/ratingbar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="13.4dp"
        android:isIndicator="false"
        android:numStars="5"
        android:rating="2.6"
        android:secondaryProgressTint="#00000000"
        android:stepSize="0.1" />
</FrameLayout>

This is the result.

Note that I added the actual height(13.4dp) of ratingbar in layout_height property, because if it is wrap_content it will draw lines below stars. (in my case only in a preview of Android Studio)


问:
How to change cell background after content edited?
I'm importing some csv columns into a html table. I need to do some validation: if one or more than one cells for a specific column are empty then I don't allow the importing of data to my database and I highlight the empty cell with a background colour. It is a editable table; can someone explain how I can change the background colour when the empty cell has been edited and is not empty anymore?

This is what my javascript looks like so far:

function NoneEmpty(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === "") return false;
  }
  return true;
}

$(document).on('click', '#import_data', function(e) {

  if (NoneEmpty(interno) == false) {

    $('.beta tr').each(function(i) {
      var column2cell = $($(this).children('td')[2]);
      if (column2cell.text() == "") {
        column2cell.css('background-color', 'red');
      }
    });

    return;

  }

});

//This is how I build the html table after uploading the csv file

$('#upload').click(function(e) {

  // Prevent form to be submitted again after page refresh
  e.preventDefault();

  var formData = new FormData();
  formData.append('csv_file', $('#csv_file')[0].files[0]);
  // Append ajax action to formData so I can process the model from the controller
  formData.append('ajax_action', 'kmg_admin_fetch_csv_building_unit');

  $.ajax({

    method: "POST",
    data: formData,
    dataType: 'json',
    contentType: false,
    // cache:false,
    processData: false,

    success: function(data) {

      if (data.notice_code == KM_ERROR_CODE) {

        alert('err');

        $('#csv_file_data').html("
" + data.notice_message + "
");

      } else {

        var html = '
';

        if (data.column) {
          html += '
';
          for (var count = 0; count < data.column.length; count++) {
            html += '' + data.column[count] + '	';
          }
          html += '
';
        }

        if (data.row_data) {
          for (var count = 0; count < data.row_data.length; count++) {
            html += '
';
            html += '' + data.row_data[count].scala + '	';
            html += '' + data.row_data[count].piano + '	';
            html += '' + data.row_data[count].interno + '	';
            html += '' + data.row_data[count].mq + '	';
            html += '' + data.row_data[count].foglio + '	';
            html += '' + data.row_data[count].particella + '	';
            html += '' + data.row_data[count].sub + '
';

          }
        }

        html += '
';
        html += '
<button type="button" id="import_data" class="btn btn-success">Importa unità immobilari</button>
';

        $('#csv_file_data').html(html);
        $('#upload_csv')[0].reset();

      }

    }
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<form id="upload_csv" method="post" enctype="multipart/form-data">
  <div class="row">
    <div class="col-md-5">
      <div class="form-group">
        <div class="fileinput fileinput-new" data-provides="fileinput">
          <div class="input-group input-large">
            <div class="form-control uneditable-input input-fixed input-medium" data-trigger="fileinput">
              <span class="fileinput-filename"> </span>
            </div>
            <span class="input-group-addon btn default btn-file">
                                                                            <span class="fileinput-new"> Seleziona documento </span>
            <span class="fileinput-exists"> Modifica </span>
            <input type="file" name="csv_file" id="csv_file" accept=".csv">
            </span>
             Rimuovi
          </div>
        </div>
      </div>
    </div>

    {#
    <div class="col-md-1"> #}
      <button type="submit" id="upload" name="upload" class="btn blue" value="Upload"><i class="fa fa-cloud-upload"></i> Carica file csv</button> {# </div> #}
  </div>
</form>

<div class="clearfix margin-bottom-10"> </div>
<div id="csv_file_data"></div></code>```

答:
Just to point out the attribute contenteditable="false" is the same as if it where missing whereas contenteditable="true" and contenteditable both make it editable.

IF you wish to manipulate that dynamically $(this).prop("contenteditable",false); can be used.

Now we (once we get that addressed) can then key our functionality upon the actual property and then we do not have to deal with the td[2] and maintenance on that if you add columns etc., test that on my example where I set some of each.

Then you can use the input event.  Then the code is really simple here, DO use classes not .css( here by simply toggling those - I use bootstrap for mine here to show multiple but it could be just yours like my empty-cell example.  Note that if someone puts a space it gets transformed to   - so I added that condition also but used the warning classes.  Test different cells with empty and space to see that in action (make it a space).

I made this code compatible with a dynamically created table by hooking it to the wrapper element $('#csv-file-data') and your action where you empty it - but not the document so it is specific to that if you have other tables for example.

$(function() {
  $('#csv-file-data')
    .on('input', 'tbody td[contenteditable]', function(event) {
      $(this)
        .toggleClass('alert alert-warning', ($(this).html() == " " || $(this).html() == " "))
        .toggleClass('empty-cell alert alert-danger', ($(this).html() == ""));
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td.empty-cell {
  background-color: red;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

    Upload

    <input type="file" class="custom-file-input" id="upload" aria-describedby="inputGroupFileAddon01">
    Choose file

          scala
          piano
          interno
          mq
          foglio
          particella
          sub

          scala stuff
          piano stuff
          interno stuff
          mq stuff
          foglio stuff
          particella stuff
          sub stuff

          scala stuffcan be edited
          piano stuff can edit
          interno stuff
          mq stuff
          foglio stuff
          particella stuff
          sub stuff

          scala stuff
          piano stuff
          interno stuff
          mq stuff
          foglio stuff
          particella stuff
          sub stuff

```

Body:
I'm importing some csv columns into a html table. I need to do some validation: if one or more than one cells for a specific column are empty then I don't allow the importing of data to my database and I highlight the empty cell with a background colour. It is a editable table; can someone explain how I can change the background colour when the empty cell has been edited and is not empty anymore?

This is what my javascript looks like so far:

function NoneEmpty(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === "") return false;
  }
  return true;
}

$(document).on('click', '#import_data', function(e) {

  if (NoneEmpty(interno) == false) {

    $('.beta tr').each(function(i) {
      var column2cell = $($(this).children('td')[2]);
      if (column2cell.text() == "") {
        column2cell.css('background-color', 'red');
      }
    });

    return;

  }

});

//This is how I build the html table after uploading the csv file

$('#upload').click(function(e) {

  // Prevent form to be submitted again after page refresh
  e.preventDefault();

  var formData = new FormData();
  formData.append('csv_file', $('#csv_file')[0].files[0]);
  // Append ajax action to formData so I can process the model from the controller
  formData.append('ajax_action', 'kmg_admin_fetch_csv_building_unit');

  $.ajax({

    method: "POST",
    data: formData,
    dataType: 'json',
    contentType: false,
    // cache:false,
    processData: false,

    success: function(data) {

      if (data.notice_code == KM_ERROR_CODE) {

        alert('err');

        $('#csv_file_data').html("
" + data.notice_message + "
");

      } else {

        var html = '
';

        if (data.column) {
          html += '
';
          for (var count = 0; count < data.column.length; count++) {
            html += '' + data.column[count] + '	';
          }
          html += '
';
        }

        if (data.row_data) {
          for (var count = 0; count < data.row_data.length; count++) {
            html += '
';
            html += '' + data.row_data[count].scala + '	';
            html += '' + data.row_data[count].piano + '	';
            html += '' + data.row_data[count].interno + '	';
            html += '' + data.row_data[count].mq + '	';
            html += '' + data.row_data[count].foglio + '	';
            html += '' + data.row_data[count].particella + '	';
            html += '' + data.row_data[count].sub + '
';

          }
        }

        html += '
';
        html += '
<button type="button" id="import_data" class="btn btn-success">Importa unità immobilari</button>
';

        $('#csv_file_data').html(html);
        $('#upload_csv')[0].reset();

      }

    }
  });

});

<form id="upload_csv" method="post" enctype="multipart/form-data">

                                                                             Seleziona documento
             Modifica
            <input type="file" name="csv_file" id="csv_file" accept=".csv">

             Rimuovi

    {#

 #}
      <button type="submit" id="upload" name="upload" class="btn blue" value="Upload"> Carica file csv</button> {#
 #}

</form>

Body:
Just to point out the attribute contenteditable="false" is the same as if it where missing whereas contenteditable="true" and contenteditable both make it editable.

IF you wish to manipulate that dynamically $(this).prop("contenteditable",false); can be used.

Now we (once we get that addressed) can then key our functionality upon the actual property and then we do not have to deal with the td[2] and maintenance on that if you add columns etc., test that on my example where I set some of each.

Then you can use the input event.  Then the code is really simple here, DO use classes not .css( here by simply toggling those - I use bootstrap for mine here to show multiple but it could be just yours like my empty-cell example.  Note that if someone puts a space it gets transformed to &nbsp; - so I added that condition also but used the warning classes.  Test different cells with empty and space to see that in action (make it a space).

I made this code compatible with a dynamically created table by hooking it to the wrapper element $('#csv-file-data') and your action where you empty it - but not the document so it is specific to that if you have other tables for example.

$(function() {
  $('#csv-file-data')
    .on('input', 'tbody td[contenteditable]', function(event) {
      $(this)
        .toggleClass('alert alert-warning', ($(this).html() == " " || $(this).html() == "&nbsp;"))
        .toggleClass('empty-cell alert alert-danger', ($(this).html() == ""));
    });
});

td.empty-cell {
  background-color: red;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>

<div class="input-group">
  <div class="input-group-prepend">
    <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
  </div>
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="upload" aria-describedby="inputGroupFileAddon01">
    <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
  </div>
</div>
<div id="table-container">
  <div id="csv-file-data">
    <table class="table table-striped table-bordered beta">
      <thead>
        <tr>
          <th>scala</th>
          <th>piano</th>
          <th>interno</th>
          <th>mq</th>
          <th>foglio</th>
          <th>particella</th>
          <th>sub</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="scala" contenteditable="false">scala stuff</td>
          <td class="piano" contenteditable="false">piano stuff</td>
          <td class="interno" contenteditable="true">interno stuff</td>
          <td class="mq" contenteditable="false">mq stuff</td>
          <td class="foglio" contenteditable="false">foglio stuff</td>
          <td class="particella" contenteditable="false">particella stuff</td>
          <td class="sub" contenteditable="false">sub stuff</td>
        </tr>
        <tr>
          <td class="scala">scala stuffcan be edited</td>
          <td class="piano">piano stuff can edit</td>
          <td class="interno" contenteditable="true">interno stuff</td>
          <td class="mq" contenteditable="false">mq stuff</td>
          <td class="foglio" contenteditable="false">foglio stuff</td>
          <td class="particella">particella stuff</td>
          <td class="sub">sub stuff</td>
        </tr>
        <tr>
          <td class="scala" contenteditable="false">scala stuff</td>
          <td class="piano" contenteditable="false">piano stuff</td>
          <td class="interno" contenteditable="true">interno stuff</td>
          <td class="mq">mq stuff</td>
          <td class="foglio">foglio stuff</td>
          <td class="particella">particella stuff</td>
          <td class="sub">sub stuff</td>
        </tr>
      </tbody>
    </table>
  </div>


问:
Simple jQuery page not working
```<code>  …
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <div id ="iAmNew">id="iAmNew"</div>
  <script>
    $(#iAmNew).style("border", "4px dotted blue");
  </script>
  …
</code>```

答:
Try this:</p>

```<code><div id ="iAmNew">id="iAmNew"</div>

<script>
$("#iAmNew").css("border", "4px dotted blue");</script>
</code>```

Title: Simple jQuery page not working

Body:
  …

id="iAmNew"

  …

Body:
Try this:

<div id ="iAmNew">id="iAmNew"</div>

<script>
$("#iAmNew").css("border", "4px dotted blue");</script>


问:
How to create and populate two dimentional array inside ES6 class constructor
I want to initialize and populate a two-dimensional array, but my solution doesn't seem to work. It only returns a function, not a value.

class Board{
    constructor(width,height,cols,rows)
    {
        this.width=width;
        this.height=height;
        this.cols=cols;
        this.rows=rows;
        this.array= function(){
            let array=[];
            for(let i=0;i<this.cols;i++)
            {
                array[i]=[];
                for(let j=0;j<this.rows;j++){
                    array[i][j]=0;
                }
            }
            return array;
        }
    }
```

答:
```<code>this.array= function(){
    let array=[];
    for(let i=0;i<this.cols;i++)
    {
        array[i]=[];
        for(let j=0;j<this.rows;j++){
            array[i][j]=0;
        }
    }
    return array;
}
</code>```

This just creates a function named this.array.

If you want this.array to hold the return value, call the function there itself.

```<code>this.array= (function(){
    let array=[];
    for(let i=0;i<this.cols;i++)
    {
        array[i]=[];
        for(let j=0;j<this.rows;j++){
            array[i][j]=0;
        }
    }
    return array;
})();
</code>```

Body:
this.array= function(){
    let array=[];
    for(let i=0;i<this.cols;i++)
    {
        array[i]=[];
        for(let j=0;j<this.rows;j++){
            array[i][j]=0;
        }
    }
    return array;
}

This just creates a function named this.array.

If you want this.array to hold the return value, call the function there itself.

this.array= (function(){
    let array=[];
    for(let i=0;i<this.cols;i++)
    {
        array[i]=[];
        for(let j=0;j<this.rows;j++){
            array[i][j]=0;
        }
    }
    return array;
})();


问:
Keycloak admin client
I trying to use the keycloak client admin to create a user in my keycloak

```<code><dependency>
  <groupId>org.keycloak</groupId>
  <artifactId>keycloak-admin-client</artifactId>
  <version>6.0.1</version>
</dependency>
</code>```

and with this code:

```<code>Keycloak keycloak = KeycloakBuilder.builder() //
                .serverUrl(serverUrl) //
                .realm(realm) //
                .grantType(OAuth2Constants.PASSWORD) //
                .clientId(clientId) //
                .clientSecret(clientSecret) //
                .username("idm-admin") //
                .password("admin") //
                .build();

        UserRepresentation user = new UserRepresentation();
        user.setEnabled(true);
        user.setUsername("tester1");
        user.setFirstName("First");
        user.setLastName("Last");
        user.setEmail("tom+tester1@tdlabs.local");
        user.setAttributes(Collections.singletonMap("origin", Arrays.asList("demo")));

        // Get realm
        RealmResource realmResource = keycloak.realm(realm);
        UsersResource userRessource = realmResource.users();

        // Create user (requires manage-users role)
        Response response = userRessource.create(user);
        System.out.println("Repsonse: " + response.getStatusInfo());
        System.out.println(response.getLocation());
        String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");

        System.out.printf("User created with userId: %s%n", userId);

        // Get realm role "tester" (requires view-realm role)
        RoleRepresentation testerRealmRole = realmResource.roles()//
                .get("tester").toRepresentation();

        // Assign realm role tester to user
        userRessource.get(userId).roles().realmLevel() //
                .add(Arrays.asList(testerRealmRole));

        // Get client
        ClientRepresentation app1Client = realmResource.clients() //
                .findByClientId("app-javaee-petclinic").get(0);

        // Get client level role (requires view-clients role)
        RoleRepresentation userClientRole = realmResource.clients().get(app1Client.getId()) //
                .roles().get("user").toRepresentation();

        // Assign client level role to user
        userRessource.get(userId).roles() //
                .clientLevel(app1Client.getId()).add(Arrays.asList(userClientRole));

        // Define password credential
        CredentialRepresentation passwordCred = new CredentialRepresentation();
        passwordCred.setTemporary(false);
        passwordCred.setType(CredentialRepresentation.PASSWORD);
        passwordCred.setValue("test");

        // Set password credential
        userRessource.get(userId).resetPassword(passwordCred);
</code>```

But in my line  Response response = userRessource.create(user); the IDE show the error: Cannot access javax.ws.rs.core.Response;  I`m using spring-boot 2.0.5.RELEASE and java 1.8

答:
If the problem is only related to

Cannot access javax.ws.rs.core.Response

you have to add the following dependency in maven pom.xml if you are using Maven.

```<code><dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.1.1</version>
</dependency>
</code>```

If you are not using maven, download the jar file and set in the classpath.

Title: Keycloak admin client

Body:
I trying to use the keycloak client admin to create a user in my keycloak

<dependency>
  <groupId>org.keycloak</groupId>
  <artifactId>keycloak-admin-client</artifactId>
  <version>6.0.1</version>
</dependency>

and with this code:

Keycloak keycloak = KeycloakBuilder.builder() //
                .serverUrl(serverUrl) //
                .realm(realm) //
                .grantType(OAuth2Constants.PASSWORD) //
                .clientId(clientId) //
                .clientSecret(clientSecret) //
                .username("idm-admin") //
                .password("admin") //
                .build();

        UserRepresentation user = new UserRepresentation();
        user.setEnabled(true);
        user.setUsername("tester1");
        user.setFirstName("First");
        user.setLastName("Last");
        user.setEmail("tom+tester1@tdlabs.local");
        user.setAttributes(Collections.singletonMap("origin", Arrays.asList("demo")));

        // Get realm
        RealmResource realmResource = keycloak.realm(realm);
        UsersResource userRessource = realmResource.users();

        // Create user (requires manage-users role)
        Response response = userRessource.create(user);
        System.out.println("Repsonse: " + response.getStatusInfo());
        System.out.println(response.getLocation());
        String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");

        System.out.printf("User created with userId: %s%n", userId);

        // Get realm role "tester" (requires view-realm role)
        RoleRepresentation testerRealmRole = realmResource.roles()//
                .get("tester").toRepresentation();

        // Assign realm role tester to user
        userRessource.get(userId).roles().realmLevel() //
                .add(Arrays.asList(testerRealmRole));

        // Get client
        ClientRepresentation app1Client = realmResource.clients() //
                .findByClientId("app-javaee-petclinic").get(0);

        // Get client level role (requires view-clients role)
        RoleRepresentation userClientRole = realmResource.clients().get(app1Client.getId()) //
                .roles().get("user").toRepresentation();

        // Assign client level role to user
        userRessource.get(userId).roles() //
                .clientLevel(app1Client.getId()).add(Arrays.asList(userClientRole));

        // Define password credential
        CredentialRepresentation passwordCred = new CredentialRepresentation();
        passwordCred.setTemporary(false);
        passwordCred.setType(CredentialRepresentation.PASSWORD);
        passwordCred.setValue("test");

        // Set password credential
        userRessource.get(userId).resetPassword(passwordCred);

But in my line  Response response = userRessource.create(user); the IDE show the error: Cannot access javax.ws.rs.core.Response;  I`m using spring-boot 2.0.5.RELEASE and java 1.8

Body:
If the problem is only related to

Cannot access javax.ws.rs.core.Response

you have to add the following dependency in maven pom.xml if you are using Maven.

<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.1.1</version>
</dependency>

If you are not using maven, download the jar file and set in the classpath.


问:
Need to remove duplicate columns from a dataframe in pyspark
I have a dataframe with 432 columns and has 24 duplicate columns.

df_tickets-->This has 432 columns

duplicatecols--> This has the cols from df_tickets which are duplicate.

I want to remove the cols in df_tickets which are duplicate. So df_tickets should only have 432-24=408 columns.

I have tried this with the below code but its throwing error.

```<code>df_tickets.select([c for c in df_tickets.columns if c not in duplicatecols]).show()
</code>```

The error is

```<code>An error occurred while calling o1657.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
HashAggregate(keys=[ms_bvoip_order_extension_id#953, ms_order_id#954...........
</code>```

Can someone help me on this?

答:
You might have to rename some of the duplicate columns in order to filter the duplicated. otherwise columns in duplicatecols will all be de-selected while you might want to keep one column for each. Below is one way which might help:

```<code># an example dataframe
cols = list('abcaded')
df_ticket = spark.createDataFrame([tuple(i for i in range(len(cols)))], cols)
>>> df_ticket.show()
#+---+---+---+---+---+---+---+
#|  a|  b|  c|  a|  d|  e|  d|
#+---+---+---+---+---+---+---+
#|  0|  1|  2|  3|  4|  5|  6|
#+---+---+---+---+---+---+---+

# unless you just want to filter a subset of all duplicate columns
# this list is probably not useful
duplicatecols = list('ad')

# create cols_new so that seen columns will have a suffix '_dup'
cols_new = []
seen = set()
for c in df_ticket.columns:
    cols_new.append('{}_dup'.format(c) if c in seen else c)
    seen.add(c)

>>> cols_new
#['a', 'b', 'c', 'a_dup', 'd', 'e', 'd_dup']
</code>```

Then filter the result based on the new column names

```<code>>>> df_ticket.toDF(*cols_new).select(*[c for c in cols_new if not c.endswith('_dup')]).show()
#+---+---+---+---+---+
#|  a|  b|  c|  d|  e|
#+---+---+---+---+---+
#|  0|  1|  2|  4|  5|
#+---+---+---+---+---+
</code>```

This will keep the first of columns with the same column names. it should be an easy fix if you want to keep the last. Ideally, you should adjust column names before creating such dataframe having duplicated column names.

Body:
I have a dataframe with 432 columns and has 24 duplicate columns.

df_tickets-->This has 432 columns

duplicatecols--> This has the cols from df_tickets which are duplicate.

I want to remove the cols in df_tickets which are duplicate. So df_tickets should only have 432-24=408 columns.

I have tried this with the below code but its throwing error.

df_tickets.select([c for c in df_tickets.columns if c not in duplicatecols]).show()

The error is

An error occurred while calling o1657.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
HashAggregate(keys=[ms_bvoip_order_extension_id#953, ms_order_id#954...........

Can someone help me on this?

Body:
You might have to rename some of the duplicate columns in order to filter the duplicated. otherwise columns in duplicatecols will all be de-selected while you might want to keep one column for each. Below is one way which might help:

# an example dataframe
cols = list('abcaded')
df_ticket = spark.createDataFrame([tuple(i for i in range(len(cols)))], cols)
>>> df_ticket.show()
#+---+---+---+---+---+---+---+
#|  a|  b|  c|  a|  d|  e|  d|
#+---+---+---+---+---+---+---+
#|  0|  1|  2|  3|  4|  5|  6|
#+---+---+---+---+---+---+---+

# unless you just want to filter a subset of all duplicate columns
# this list is probably not useful
duplicatecols = list('ad')

# create cols_new so that seen columns will have a suffix '_dup'
cols_new = []
seen = set()
for c in df_ticket.columns:
    cols_new.append('{}_dup'.format(c) if c in seen else c)
    seen.add(c)

>>> cols_new
#['a', 'b', 'c', 'a_dup', 'd', 'e', 'd_dup']

Then filter the result based on the new column names

>>> df_ticket.toDF(*cols_new).select(*[c for c in cols_new if not c.endswith('_dup')]).show()
#+---+---+---+---+---+
#|  a|  b|  c|  d|  e|
#+---+---+---+---+---+
#|  0|  1|  2|  4|  5|
#+---+---+---+---+---+

This will keep the first of columns with the same column names. it should be an easy fix if you want to keep the last. Ideally, you should adjust column names before creating such dataframe having duplicated column names.


问:
Type mismatch: cannot convert from element type java.awt.print.Book to Book
```<code>@Service
public class LMSService {

    @Autowired
    private BookInterface a;

    private Collection<Books1> findBooks(){
    List<Books1> books=new ArrayList<Books1>();
    for(Books1 booke : a.findAll())
    {
        books.add(booke);
    }
    return books;
}
</code>```

```<code>@Repository
public interface BookInterface extends CrudRepository<Books1,Long>{

}
</code>```

a.findAll() method gives the error

答:
You need to add the generic arguments

CrudRepository<Books1, Integer>
```

Body:
@Service
public class LMSService {

    @Autowired
    private BookInterface a;

    private Collection<Books1> findBooks(){
    List<Books1> books=new ArrayList<Books1>();
    for(Books1 booke : a.findAll())
    {
        books.add(booke);
    }
    return books;
}

@Repository
public interface BookInterface extends CrudRepository<Books1,Long>{

}

a.findAll() method gives the error


答:
Related to this question:

Maximum number of socket in java

If you're worried about exceeding the maximum number of sockets that can be opened (I imagine this is highly unlikely in your case) you can create a work-around where you use TCP to initially establish the connection, send the client a UID (Unique Identifier, a 64-bit unsigned long long type should be sufficient) and then close the TCP connection. Fill and maintain a structure (or Class object in your case) detailing the connection details (IP address, Unique Identifier code) and then wait on arriving packets sent via UDP (User Datagram Protocol, an alternative to TCP). If you decide to use UDP, be aware that you'll need to implement a means of reordering packets in order to reconstruct a byte-stream (serialisation) and a mechanism for resending data packets if somehow they do not arrive (packet loss recovery).

Sounds worse than it is. I'll repeat though, don't bother yourself with these intricacies if you're not worried about exceeding any limits.

Title: Use Socket permantently to handle Clientsession or create new one for every request

Body:
So i am quite new to Sockets and I have to create a Server-Client-App for school.

I expect a client to request something from the server multiple times during his runtime.

I am uncertain wether I should make a new java.net.Socket for every Request I get (Client opens new socket every time and Java Serversocket accepts)
or use a single socket and keep that during the client's runtime.


问:
select all but the last record from grouped record in a table
I am trying to select all but the last row of grouped data from a table.

```<code>+----+--------+--------+                    +----+--------+--------+
| id | userID | amount |                    | id | userID | amount |
+----+--------+--------+                    +----+--------+--------+
| 1  | 20     | 400    |                    | 1  | 20     | 400    |
| 2  | 20     | 200    |                    | 2  | 20     | 200    |
| 3  | 21     | 100    |         =>         | 3  | 21     | 100    |
| 4  | 11     | 500    |                    | 4  | 11     | 500    |
| 5  | 11     | 250    |                    | 6  | 21     | 50     |
| 6  | 21     | 50     |
| 7  | 20     | 100    |
| 8  | 21     | 200    |
+----+--------+--------+
</code>```

I have tried to use the query

```<code>SELECT *
  FROM table
 WHERE userID != (SELECT MAX(userID) FROM table)
 GROUP
    BY userID
</code>```

but it only fetches one unique row of data even though there are more left

答:
You have not aggreagtion function so you don't need  group by </p>

```<code>SELECT *
FROM table
WHERE userID != (
  SELECT MAX(userID) FROM table
)
</code>```

<p>This can happen with mysql version <5.7  for mysql version > 5.7 (by default setting)  this use of group by raise an error </p>

Body:
I am trying to select all but the last row of grouped data from a table.

+----+--------+--------+                    +----+--------+--------+
| id | userID | amount |                    | id | userID | amount |
+----+--------+--------+                    +----+--------+--------+
| 1  | 20     | 400    |                    | 1  | 20     | 400    |
| 2  | 20     | 200    |                    | 2  | 20     | 200    |
| 3  | 21     | 100    |         =>         | 3  | 21     | 100    |
| 4  | 11     | 500    |                    | 4  | 11     | 500    |
| 5  | 11     | 250    |                    | 6  | 21     | 50     |
| 6  | 21     | 50     |
| 7  | 20     | 100    |
| 8  | 21     | 200    |
+----+--------+--------+

I have tried to use the query

SELECT *
  FROM table
 WHERE userID != (SELECT MAX(userID) FROM table)
 GROUP
    BY userID

but it only fetches one unique row of data even though there are more left

Body:
You have not aggreagtion function so you don't need  group by

SELECT *
FROM table
WHERE userID != (
  SELECT MAX(userID) FROM table
)

This can happen with mysql version <5.7  for mysql version > 5.7 (by default setting)  this use of group by raise an error


问:
How to wait for the promise when using get in Firestore
I am just trying a simple get command with Firestore, using this code from Google it doesn't work because it's not waiting for the promise?

Earlier I had put only a snippet of code, this is the entirety of index.js -- I'm using Firestore with Dialogflow to build a Google Assistant app and trying to call a function from the welcome intent that gets a field from Firestore, then writes that field to a string (named question1), and then this string should be spoken by the assistant as part of the ssml response.  I've been on this for at least 30 hours already, can't seem to comprehend promises in regards to intents, firestore, etc. I've tried about 10 different solutions, this one works, only it says "undefined" in other variations I have tried it would say undefined several times but after 2-3 passes the get command would be complete and then the variable would be read out.  I'm just trying to figure out how to get the get command and variable set before moving onto the SSML response.  Can anyone point me in the right direction?

```<code>      'use strict';

const functions = require('firebase-functions'); //don't forget this one

// Import Admin SDK
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
const collectionRef = db.collection('text');

const Firestore = require('@google-cloud/firestore');

var doc;

var question1;

const url = require('url');
const {
dialogflow,
Image,
Permission,
NewSurface,
} = require('actions-on-google');
const {ssml} = require('./util');

const config = functions.config();

const WELCOME_INTENT = 'Default Welcome Intent';

const app = dialogflow({debug: true});

async function dbaccess(rando) {

console.log("dbaseaccess started")

var currentquestion2 = 'question-' + rando.toString();

var cityRef
try { return cityRef = db.collection('text').doc(currentquestion2).get();
console.log("get command completed")
//do stuff

question1 = cityRef.data().n111

} catch(e) {

//error!
}
console.log("one line above return something");

return rando;

}

app.fallback((conv) => {
// intent contains the name of the intent
// you defined in the Intents area of Dialogflow
const intent = conv.intent;

switch (intent) {
 case WELCOME_INTENT:

var rando = Math.floor(Math.random() * 3) + 1;
dbaccess(rando);

const ssml =
'<speak>' +
question1 +
'</speak>';
conv.ask(ssml);

break;

exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
</code>```

答:
maybe a little of work around could help you, I'm not sure yet how you are trying to implement it.

```<code> function databasetest () {
  var cityRef = db.collection('cities').doc('SF');
  return cityRef.get()
  }

// so you can implement it like

databasetest().then(doc => {
 if (!doc.exists) {
   console.log('No such document!');
 } else {
   console.log('Document data:', doc.data());
 }
})
.catch(err => {
  console.log('Error getting document', err);
});
</code>```

More context would help to understand your use case better :)

Body:
I am just trying a simple get command with Firestore, using this code from Google it doesn't work because it's not waiting for the promise?

Earlier I had put only a snippet of code, this is the entirety of index.js -- I'm using Firestore with Dialogflow to build a Google Assistant app and trying to call a function from the welcome intent that gets a field from Firestore, then writes that field to a string (named question1), and then this string should be spoken by the assistant as part of the ssml response.  I've been on this for at least 30 hours already, can't seem to comprehend promises in regards to intents, firestore, etc. I've tried about 10 different solutions, this one works, only it says "undefined" in other variations I have tried it would say undefined several times but after 2-3 passes the get command would be complete and then the variable would be read out.  I'm just trying to figure out how to get the get command and variable set before moving onto the SSML response.  Can anyone point me in the right direction?

      'use strict';

const functions = require('firebase-functions'); //don't forget this one

// Import Admin SDK
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
const collectionRef = db.collection('text');

const Firestore = require('@google-cloud/firestore');

var doc;

var question1;

const url = require('url');
const {
dialogflow,
Image,
Permission,
NewSurface,
} = require('actions-on-google');
const {ssml} = require('./util');

const config = functions.config();

const WELCOME_INTENT = 'Default Welcome Intent';

const app = dialogflow({debug: true});

async function dbaccess(rando) {

console.log("dbaseaccess started")

var currentquestion2 = 'question-' + rando.toString();

var cityRef
try { return cityRef = db.collection('text').doc(currentquestion2).get();
console.log("get command completed")
//do stuff

question1 = cityRef.data().n111

} catch(e) {

//error!
}
console.log("one line above return something");

return rando;

}

app.fallback((conv) => {
// intent contains the name of the intent
// you defined in the Intents area of Dialogflow
const intent = conv.intent;

switch (intent) {
 case WELCOME_INTENT:

var rando = Math.floor(Math.random() * 3) + 1;
dbaccess(rando);

const ssml =
'<speak>' +
question1 +
'</speak>';
conv.ask(ssml);

break;

exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);

Body:
maybe a little of work around could help you, I'm not sure yet how you are trying to implement it.

 function databasetest () {
  var cityRef = db.collection('cities').doc('SF');
  return cityRef.get()
  }

// so you can implement it like

databasetest().then(doc => {
 if (!doc.exists) {
   console.log('No such document!');
 } else {
   console.log('Document data:', doc.data());
 }
})
.catch(err => {
  console.log('Error getting document', err);
});

More context would help to understand your use case better :)


问:
sample code from chatterbot website works fine when run on spyder, but directly running the .py file doesnt
i installed chatterbot the other day and was trying it out with the code provided in the website, here's the link: https://chatterbot.readthedocs.io/en/stable/examples.html

it worked fine on spyder but when i try to run the .py file directly it doesnt.

i am using python 3.7 with anaconda.

the initial error message i got was:

```<code>from _sqlite3 import *
------------------------------------------------------------------------
ImportError: DLL load failed: The specified module could not be found.
------------------------------------------------------------------------
</code>```

i then tried downloading the sqlite dll files from https://www.sqlite.org/download.html and put them in the anaconda DLL folder. running the file again i got the same error for a different module:

```<code>from . import _mklinit
------------------------------------------------------------------------
ImportError: DLL load failed: The specified module could not be found.
------------------------------------------------------------------------
</code>```

the code from the chatterbot website.

```<code>from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

# Create a new chat bot named Charlie
chatbot = ChatBot('Charlie')

trainer = ListTrainer(chatbot)

trainer.train([
    "Hi, can I help you?",
    "Sure, I'd like to book a flight to Iceland.",
    "Your flight has been booked."
])

# Get a response to the input text 'I would like to book a flight.'
response = chatbot.get_response('I would like to book a flight.')

print(response)
</code>```

the .py file should run normally but instead it fails to import chatterbot and shuts down immediatly.

答: Have you activated the conda environment before running the .py file? Anaconda provides sqlite if it is declared as a dependency of an installed package. But if you haven't activated the environment, the search paths are not set correctly.</p>

Body:
i installed chatterbot the other day and was trying it out with the code provided in the website, here's the link: https://chatterbot.readthedocs.io/en/stable/examples.html

it worked fine on spyder but when i try to run the .py file directly it doesnt.

i am using python 3.7 with anaconda.

the initial error message i got was:

from _sqlite3 import *
------------------------------------------------------------------------
ImportError: DLL load failed: The specified module could not be found.
------------------------------------------------------------------------

i then tried downloading the sqlite dll files from https://www.sqlite.org/download.html and put them in the anaconda DLL folder. running the file again i got the same error for a different module:

from . import _mklinit
------------------------------------------------------------------------
ImportError: DLL load failed: The specified module could not be found.
------------------------------------------------------------------------

the code from the chatterbot website.

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

# Create a new chat bot named Charlie
chatbot = ChatBot('Charlie')

trainer = ListTrainer(chatbot)

trainer.train([
    "Hi, can I help you?",
    "Sure, I'd like to book a flight to Iceland.",
    "Your flight has been booked."
])

# Get a response to the input text 'I would like to book a flight.'
response = chatbot.get_response('I would like to book a flight.')

print(response)

the .py file should run normally but instead it fails to import chatterbot and shuts down immediatly.


问:
How can I uniquely identify an IMAP message after copying it?
I want to move an IMAP message from INBOX to INBOX/Archive using python's imapclient library, which I'm doing basically like this:

```<code>def archive_message(imap, message_id):
    imap.copy([message_id], getOptions().imap_archive_folder)
    imap.delete_messages([message_id])
</code>```

However, this loses my reference to the message. What I want to do is to store an identifier for the message that will allow me to look up the message later, using something like this:

```<code>def retrieve_message(imap, MYSTICAL_STORED_ID):
    imap.select_folder(getOptions().imap_archive_folder)
    return imap.fetch([MYSTICAL_STORED_ID], parts=["RFC822"])
</code>```

What ID should I / can I use for this, and how would I do the lookup part of this?

答: The value in the Message-Id header is supposed to be unique per email message.

Body:
I want to move an IMAP message from INBOX to INBOX/Archive using python's imapclient library, which I'm doing basically like this:

def archive_message(imap, message_id):
    imap.copy([message_id], getOptions().imap_archive_folder)
    imap.delete_messages([message_id])

However, this loses my reference to the message. What I want to do is to store an identifier for the message that will allow me to look up the message later, using something like this:

def retrieve_message(imap, MYSTICAL_STORED_ID):
    imap.select_folder(getOptions().imap_archive_folder)
    return imap.fetch([MYSTICAL_STORED_ID], parts=["RFC822"])

What ID should I / can I use for this, and how would I do the lookup part of this?


问:
How can I query by sort key in AWS DynamoDB?
I have a database of users, and I'd like to return all users with the last name X. I currently have "last" as the sort key for my table. I'm running the following code, but getting a "Query condition missed key schema element" error.</p>

```<code>var params = { TableName: 'Patients',
    KeyConditionExpression: '#id = :idNum',
    ExpressionAttributeNames: {
       '#id': 'last'
    },
    ExpressionAttributeValues: {
      ':idNum': 'Test'
    }
};

docClient.query(params, function(err, data) {
    if (err) {
        console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
    } else {
        console.log("Query succeeded.");
        res.json(data);
    }
});
</code>```

答:
This is not the way DynamoDB/NoSQL should be used. You either create a GSI as thomasmichaelwallace suggested or have the users lastname as partition key too. You can add "ln_" before all of your last name partitionkeys to separte them from your other partition keys. If you had firstname as partitions before your primary key should look like that now:

```<code>partition | sort
fn_hans | ln_zimmer
fn_steve | ln_jobs
ln_zimmer | fn_hans
ln_jobs | fn_steve
</code>```

Now you can query all partition which start with ln_. And yes you are supposed to have douplicate data in noSql. NoSQL Design has some articles about how to design a dynamoDB table.

Body:
I have a database of users, and I'd like to return all users with the last name X. I currently have "last" as the sort key for my table. I'm running the following code, but getting a "Query condition missed key schema element" error.

var params = { TableName: 'Patients',
    KeyConditionExpression: '#id = :idNum',
    ExpressionAttributeNames: {
       '#id': 'last'
    },
    ExpressionAttributeValues: {
      ':idNum': 'Test'
    }
};

docClient.query(params, function(err, data) {
    if (err) {
        console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
    } else {
        console.log("Query succeeded.");
        res.json(data);
    }
});

Body:
This is not the way DynamoDB/NoSQL should be used. You either create a GSI as thomasmichaelwallace suggested or have the users lastname as partition key too. You can add "ln_" before all of your last name partitionkeys to separte them from your other partition keys. If you had firstname as partitions before your primary key should look like that now:

partition | sort
fn_hans | ln_zimmer
fn_steve | ln_jobs
ln_zimmer | fn_hans
ln_jobs | fn_steve

Now you can query all partition which start with ln_. And yes you are supposed to have douplicate data in noSql. NoSQL Design has some articles about how to design a dynamoDB table.


问:
Toggle Back And Forth Between Styles onClick() - Switch Case
On this page:

http://javascript.drawyourpets.com/

I'm trying to toggle back and forth between styles every time a user clicks the button.

I'm using a switch case as per the code from this solution:

function changeColor() {
  let theToggle = document.getElementById("change-color");
  theToggle.toggleStatus = "on";
  switch (theToggle.toggleStatus) {
    case "on":
      theToggle.toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}</code>```

  <button id="change-color" onclick="changeColor()">Change Color</button>

```

This changes the background color the first time, but it only works once - it should be changing on every click.

I'm not very familiar with switch-cases, maybe something's wrong with it?

答:
There is no toggleStatus in your html element. One approach would be jQuery's toggleClass(); or if you want to do it in pure js, you can add a data attribute named status to control your switch case.

This is one of the possible ways to do in pure javascript.

function changeColor() {
  let theToggle = document.getElementById("change-color");
  let toggleStatus = theToggle.dataset.status;
  switch (toggleStatus) {
    case "on":
      theToggle.dataset.status = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.dataset.status = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}</code>```

  <button id="change-color" data-status="on" onclick="changeColor()">Change Color</button>

```

Body:
On this page:

http://javascript.drawyourpets.com/

I'm trying to toggle back and forth between styles every time a user clicks the button.

I'm using a switch case as per the code from this solution:

function changeColor() {
  let theToggle = document.getElementById("change-color");
  theToggle.toggleStatus = "on";
  switch (theToggle.toggleStatus) {
    case "on":
      theToggle.toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}

#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}

  <button id="change-color" onclick="changeColor()">Change Color</button>

This changes the background color the first time, but it only works once - it should be changing on every click.

I'm not very familiar with switch-cases, maybe something's wrong with it?

Body:
There is no toggleStatus in your html element. One approach would be jQuery's toggleClass(); or if you want to do it in pure js, you can add a data attribute named status to control your switch case.

This is one of the possible ways to do in pure javascript.

function changeColor() {
  let theToggle = document.getElementById("change-color");
  let toggleStatus = theToggle.dataset.status;
  switch (toggleStatus) {
    case "on":
      theToggle.dataset.status = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.dataset.status = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}

#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}

<div class="column">
  <button id="change-color" data-status="on" onclick="changeColor()">Change Color</button>
</div>


问:
SystemML:Cannot import the submodule mllearn (and therefore Keras2DML function)
I am using IBM Watson Studio (Default spark python environment) and trying to convert a Keras model to systemml DML and train it on Spark.

```<code>!pip install systemml
import systemml
</code>```

this executes just fine. But this -

```<code>from systemml import mllearn
</code>```

throws
SyntaxError: import * only allowed at module level

```<code>dir(systemml)
</code>```

doesn't show mllearn.

I tried to install it from http://www.romeokienzler.com/systemml-1.0.0-SNAPSHOT-python.tar.gz and https://sparktc.ibmcloud.com/repo/latest/systemml-1.0.0-SNAPSHOT-python.tar.gz
and a git clone but was unsuccessful. What am I doing wrong?

答:
final this is perfectly working if you are working on IBM cloud notebook

1)

```<code>! pip install --upgrade https://github.com/niketanpansare/future_of_data/raw/master/systemml-1.3.0-SNAPSHOT-python.tar.gz
</code>```

2)

```<code>!ln -s -f /home/spark/shared/user-libs/python3/systemml/systemml-java/systemml-1.3.0-SNAPSHOT-extra.jar ~/user-libs/spark2/systemml-1.3.0-SNAPSHOT-extra.jar

!ln -s -f /home/spark/shared/user-libs/python3/systemml/systemml-java/systemml-1.3.0-SNAPSHOT.jar ~/user-libs/spark2/systemml-1.3.0-SNAPSHOT.jar
</code>```

~

~

Body:
I am using IBM Watson Studio (Default spark python environment) and trying to convert a Keras model to systemml DML and train it on Spark.

!pip install systemml
import systemml

this executes just fine. But this -

from systemml import mllearn

throws
SyntaxError: import * only allowed at module level

dir(systemml)

doesn't show mllearn.

I tried to install it from http://www.romeokienzler.com/systemml-1.0.0-SNAPSHOT-python.tar.gz and https://sparktc.ibmcloud.com/repo/latest/systemml-1.0.0-SNAPSHOT-python.tar.gz
and a git clone but was unsuccessful. What am I doing wrong?

Body:
final this is perfectly working if you are working on IBM cloud notebook

1)

! pip install --upgrade https://github.com/niketanpansare/future_of_data/raw/master/systemml-1.3.0-SNAPSHOT-python.tar.gz

2)

!ln -s -f /home/spark/shared/user-libs/python3/systemml/systemml-java/systemml-1.3.0-SNAPSHOT-extra.jar ~/user-libs/spark2/systemml-1.3.0-SNAPSHOT-extra.jar

!ln -s -f /home/spark/shared/user-libs/python3/systemml/systemml-java/systemml-1.3.0-SNAPSHOT.jar ~/user-libs/spark2/systemml-1.3.0-SNAPSHOT.jar

~

~