问:
SQLiteOpenHelper constructor problem
I Created SQLite Database in SQLiteBrowser. I want to refer it in android app so I put DB file in assets folder n used the following code to copy DB to App memory. M using eclipse for android app development.

But SQLiteOpenHelper constructor is giving error.
The constructor DB_Import(DB_test1) is undefined

```<code>package com.example.DB_test1;

public class DB_test1 extends Activity{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DB_Import my_Import;
        //SQLiteDatabase myDb = null;
        my_Import=new DB_Import(this);
        try {
            my_Import.createDatabase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
</code>```

Following is another class file.

```<code>package com.example.DB_test1;

public class DB_Import extends SQLiteOpenHelper{

    private final Context myContext;
     String DB_PATH = "data/data/com.example.DB_test/databases/";
     String DB_NAME = "Dict_temp";
    private SQLiteDatabase myDatabase;

    public DB_Import(Context context) {
            super(context, "data/data/com.example.DB_test/databases/", null, 1);
            this.myContext = context;
        }
    public void createDatabase()throws IOException{
            // TODO Auto-generated method stub
            boolean dbExist = checkDatabase(); ////////////////Check if database Exist
            if (dbExist) {
                //openDatabase();
            }else {
            this.getReadableDatabase();

            try {
            copyDatabase(); ///////////////Copies the database from assets to android
            } catch (IOException e) {
            // TODO Auto-generated catch block
            throw new Error("Error copying database");
            }
            }
        }
</code>```

答:
Try this code:</p>

```<code>public class DataBaseHelper extends SQLiteOpenHelper{
private Context mycontext;

private String DB_PATH = "/data/data/gr.peos/databases/";
//private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
private static String DB_NAME = "BLib.sqlite";//the extension may be .sqlite or .db
public SQLiteDatabase myDataBase;
/*private String DB_PATH = "/data/data/"
                        + mycontext.getApplicationContext().getPackageName()
                        + "/databases/";*/

public DataBaseHelper(Context context) throws IOException  {
super(context,DB_NAME,null,1);
this.mycontext=context;
boolean dbexist = checkdatabase();
if(dbexist)
{
    //System.out.println("Database exists");
    opendatabase();
}
else
{
    System.out.println("Database doesn't exist");
createdatabase();
}

}

public void createdatabase() throws IOException{
boolean dbexist = checkdatabase();
if(dbexist)
{
    //System.out.println(" Database exists.");
}
else{
    this.getReadableDatabase();
try{
        copydatabase();
    }
    catch(IOException e){
        throw new Error("Error copying database");
    }
}
}
private boolean checkdatabase() {
//SQLiteDatabase checkdb = null;
boolean checkdb = false;
try{
    String myPath = DB_PATH + DB_NAME;
    File dbfile = new File(myPath);
    //checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
    checkdb = dbfile.exists();
}
catch(SQLiteException e){
    System.out.println("Database doesn't exist");
}

return checkdb;
}
private void copydatabase() throws IOException {

//Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;

//Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream("/data/data/gr.peos/databases/BLib.sqlite");

// transfer byte to inputfile to outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myinput.read(buffer))>0)
{
    myoutput.write(buffer,0,length);
}

//Close the streams
myoutput.flush();
myoutput.close();
myinput.close();

}

public void opendatabase() throws SQLException
{
//Open the database
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);

}

public synchronized void close(){
if(myDataBase != null){
    myDataBase.close();
}
super.close();
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: SQLiteOpenHelper constructor problem

Body:
I Created SQLite Database in SQLiteBrowser. I want to refer it in android app so I put DB file in assets folder n used the following code to copy DB to App memory. M using eclipse for android app development.

But SQLiteOpenHelper constructor is giving error.
The constructor DB_Import(DB_test1) is undefined

package com.example.DB_test1;

public class DB_test1 extends Activity{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DB_Import my_Import;
        //SQLiteDatabase myDb = null;
        my_Import=new DB_Import(this);
        try {
            my_Import.createDatabase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Following is another class file.

package com.example.DB_test1;

public class DB_Import extends SQLiteOpenHelper{

    private final Context myContext;
     String DB_PATH = "data/data/com.example.DB_test/databases/";
     String DB_NAME = "Dict_temp";
    private SQLiteDatabase myDatabase;

    public DB_Import(Context context) {
            super(context, "data/data/com.example.DB_test/databases/", null, 1);
            this.myContext = context;
        }
    public void createDatabase()throws IOException{
            // TODO Auto-generated method stub
            boolean dbExist = checkDatabase(); ////////////////Check if database Exist
            if (dbExist) {
                //openDatabase();
            }else {
            this.getReadableDatabase();

            try {
            copyDatabase(); ///////////////Copies the database from assets to android
            } catch (IOException e) {
            // TODO Auto-generated catch block
            throw new Error("Error copying database");
            }
            }
        }

Body:
Try this code:

public class DataBaseHelper extends SQLiteOpenHelper{
private Context mycontext;

private String DB_PATH = "/data/data/gr.peos/databases/";
//private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
private static String DB_NAME = "BLib.sqlite";//the extension may be .sqlite or .db
public SQLiteDatabase myDataBase;
/*private String DB_PATH = "/data/data/"
                        + mycontext.getApplicationContext().getPackageName()
                        + "/databases/";*/

public DataBaseHelper(Context context) throws IOException  {
super(context,DB_NAME,null,1);
this.mycontext=context;
boolean dbexist = checkdatabase();
if(dbexist)
{
    //System.out.println("Database exists");
    opendatabase();
}
else
{
    System.out.println("Database doesn't exist");
createdatabase();
}

}

public void createdatabase() throws IOException{
boolean dbexist = checkdatabase();
if(dbexist)
{
    //System.out.println(" Database exists.");
}
else{
    this.getReadableDatabase();
try{
        copydatabase();
    }
    catch(IOException e){
        throw new Error("Error copying database");
    }
}
}
private boolean checkdatabase() {
//SQLiteDatabase checkdb = null;
boolean checkdb = false;
try{
    String myPath = DB_PATH + DB_NAME;
    File dbfile = new File(myPath);
    //checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
    checkdb = dbfile.exists();
}
catch(SQLiteException e){
    System.out.println("Database doesn't exist");
}

return checkdb;
}
private void copydatabase() throws IOException {

//Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;

//Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream("/data/data/gr.peos/databases/BLib.sqlite");

// transfer byte to inputfile to outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myinput.read(buffer))>0)
{
    myoutput.write(buffer,0,length);
}

//Close the streams
myoutput.flush();
myoutput.close();
myinput.close();

}

public void opendatabase() throws SQLException
{
//Open the database
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);

}

public synchronized void close(){
if(myDataBase != null){
    myDataBase.close();
}
super.close();
}


来源: stackexchange

问:
React access state after render with functional components
I'm a bit of a newbie with React functional components, I have a child and parent components with some state that gets updated with useEffect, which state apparently resets back to its initial values after render.

Parent has a list of users it passes to its child:

Parent:

```<code>const Parent = () => {
   const [users, setUsers] = useState([])
   const getUsers = () => {
   setUsers(["pedro", "juan"])
  }
    useEffect(() => {
        getUsers()
    }, []);

   return <div>
    <Child users={users} />
}
</code>```

Child:

```<code>const Child = () => {
   const [users, setUsers] = useState([])
  useEffect(() => {
    setUsers(props.users)
  }, [[...props.users]]);
}
</code>```

If I for any reason try to access state (users) from either my child or parent components I get my initial value, which is an empty array, not my updated value from getUsers(), generally with a Parent Class component I'd have no trouble accessing that info, but it seems like functional components behave diffently? or is it caused by the useEffect? generally I'd use a class component for the parent but some libraries I use rely on Hooks, so I'm kind of forced to use functional components.

答:
There are a couple of mistakes the way you are trying to access data and passing that data.

You should adapt to the concept of lifting up state, which means that if you have users being passed to your Child component, make sure that all the logic regarding adding or removing or updating the users stays inside the Parent function and the Child component is responsible only for displaying the list of users.

Here is a code sandbox inspired by the code you have shared above. I hope this answers your question, do let me know if otherwise.

Also sharing the code below.

```<code>import React, { useState } from "react";

export default function Parent() {
  const [users, setUsers] = useState([]);
  let [userNumber, setUserNumber] = useState(1); // only for distinctive users,
    //can be ignored for regular implementation

  const setRandomUsers = () => {
    let newUser = {};
    newUser.name = `user ${userNumber}`;
    setUsers([...users, newUser]);
    setUserNumber(++userNumber);
  };

  return (
    <div className="App">
      <button onClick={setRandomUsers}>Add New User</button>
      <Child users={users} />
   </div>
  );
}

const Child = props => {
  return (
    props.users &&
    props.users.map((user, index) => <div key={index}>{user.name}</div>)
  );
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm a bit of a newbie with React functional components, I have a child and parent components with some state that gets updated with useEffect, which state apparently resets back to its initial values after render.

Parent has a list of users it passes to its child:

Parent:

const Parent = () => {
   const [users, setUsers] = useState([])
   const getUsers = () => {
   setUsers(["pedro", "juan"])
  }
    useEffect(() => {
        getUsers()
    }, []);

   return

    <Child users={users} />
}

Child:

const Child = () => {
   const [users, setUsers] = useState([])
  useEffect(() => {
    setUsers(props.users)
  }, [[...props.users]]);
}

If I for any reason try to access state (users) from either my child or parent components I get my initial value, which is an empty array, not my updated value from getUsers(), generally with a Parent Class component I'd have no trouble accessing that info, but it seems like functional components behave diffently? or is it caused by the useEffect? generally I'd use a class component for the parent but some libraries I use rely on Hooks, so I'm kind of forced to use functional components.

Body:
There are a couple of mistakes the way you are trying to access data and passing that data.

You should adapt to the concept of lifting up state, which means that if you have users being passed to your Child component, make sure that all the logic regarding adding or removing or updating the users stays inside the Parent function and the Child component is responsible only for displaying the list of users.

Here is a code sandbox inspired by the code you have shared above. I hope this answers your question, do let me know if otherwise.

Also sharing the code below.

import React, { useState } from "react";

export default function Parent() {
  const [users, setUsers] = useState([]);
  let [userNumber, setUserNumber] = useState(1); // only for distinctive users,
    //can be ignored for regular implementation

  const setRandomUsers = () => {
    let newUser = {};
    newUser.name = `user ${userNumber}`;
    setUsers([...users, newUser]);
    setUserNumber(++userNumber);
  };

  return (
    <div className="App">
      <button onClick={setRandomUsers}>Add New User</button>
      <Child users={users} />
   </div>
  );
}

const Child = props => {
  return (
    props.users &&
    props.users.map((user, index) => <div key={index}>{user.name}</div>)
  );
};


问:
Creating Binary Tree
Most of the questions I've searched for regarding binary trees shows the implementation of binary search trees, but not binary trees. The terms of a complete binary tree are:

Either an empty tree or it has 1 node with 2 children, where each
child is another Binary Tree.

All levels are full (except for possibly the last level)

All leaves on the bottom-most level are
as far left as possible.

I've come up with a concept but it doesn't seem to running through the recursion properly -- Does anyone know what I'm doing wrong?

```<code>class Node():
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

    def add(self, key):
        if self.key:
            if self.left is None:
                self.left = Node(key)
            else:
                self.left.add(key)

                if self.right is None:
                    self.right = Node(key)
                else:
                    self.right.add(key)
        else:
            self.key = key
        return (self.key)
</code>```

答:
The problem in your code is that you are adding the same value multiple times. You add the node, and then still recurse deeper, where you do the same.

The deeper problem is that you don't really know where to insert the node before you have reached the bottom level of the tree, and have detected where that level is incomplete. Finding the correct insertion point may need a traversal through the whole tree... which is defeating the speed gain you would expect to get from using binary trees in the first place.

I provide here three solutions, starting with the most efficient:

1. Using a list as tree implementation

For complete trees there is a special consideration to make: if you number the nodes by level, starting with 0 for the root, and within each level from left to right, you notice that the number of a node's parent is (k-1)/2 when its own number is k. In the other direction: if a node with number k has children, then its left child has number k*2+1, and the right child has a number that is one greater.

Because the tree is complete, there will never be gaps in this numbering, and so you could store the nodes in a list, and use the indexes of that list for the node numbering. Adding a node to the tree now simply means you append it to that list. Instead of a Node object, you just have the tree list, and the index in that list is your node reference.

Here is an implementation:

```<code>class CompleteTree(list):
    def add(self, key):
        self.append(key)
        return len(self) - 1

    def left(self, i):
        return i * 2 + 1 if i * 2 + 1 < len(self) else -1

    def right(self, i):
        return i * 2 + 2 if i * 2 + 2 < len(self) else -1

    @staticmethod
    def parent(i):
        return (i - 1) // 2

    def swapwithparent(self, i):
        if i > 0:
            p = self.parent(i)
            self[p], self[i] = self[i], self[p]

    def inorder(self, i=0):
        left = self.left(i)
        right = self.right(i)
        if left >= 0:
            yield from self.inorder(left)
        yield i
        if right >= 0:
            yield from self.inorder(right)

    @staticmethod
    def depth(i):
        return (i + 1).bit_length() - 1
</code>```

Here is a demo that creates your example tree, and then prints the keys visited in an in-order traversal, indented by their depth in the tree:

```<code>tree = CompleteTree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
for node in tree.inorder():
    print("  " * tree.depth(node), tree[node])
</code>```

Of course, this means you have to reference nodes a bit different from when you would use a real Node class, but the efficiency gain pays off.

2. Using an extra property

If you know how many nodes there are in a (sub)tree, then from the bit representation of that number, you can know where exactly the next node should be added.

For instance, in your example tree you have 5 nodes. Imagine you want to add a 6 to that tree. The root node would tell you that you currently have 5 and so you need to update it to 6. In binary that is 110. Ignoring the left-most 1-bit, the rest of the bits tell you whether to go left or right. In this case, you should go right (1) and then finally left (0), creating the node in that direction. You can do this iteratively or recursively.

Here is an implementation with recursion:

```<code>class Node():
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.count = 1

    def add(self, key):
        self.count += 1
        if self.left is None:
            self.left = Node(key)
        elif self.right is None:
            self.right = Node(key)
        # extract from the count the second-most significant bit:
        elif self.count & (1 << (self.count.bit_length() - 2)):
            self.right.add(key)
        else:
            self.left.add(key)

    def inorder(self):
        if self.left:
            yield from self.left.inorder()
        yield self
        if self.right:
            yield from self.right.inorder()

tree = Node(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
for node in tree.inorder():
    print(node.key)
</code>```

3. Without extra property

If no property can be added to Node objects, then a more extensive search is needed to find the right insertion point:

```<code>class Node():
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

    def newparent(self):
        # Finds the node that should serve as parent for a new node
        # It returns a tuple:
        #   if parent found: [-1, parent for new node]
        #   if not found: [height, left-most leaf]
        # In the latter case, the subtree is perfect, and its left-most
        # leaf is the node to be used, unless self is a right child
        # and its sibling has the insertion point.
        if self.right:
            right = self.right.newparent()
            if right[0] == -1: # found inbalance
                return right
            left = self.left.newparent()
            if left[0] == -1: # found inbalance
                return left
            if left[0] != right[0]:
                return [-1, right[1]] # found inbalance
            # temporary result in perfect subtree
            return [left[0]+1, left[1]]
        elif self.left:
            return [-1, self] # found inbalance
        # temporary result for leaf
        return [0, self]

    def add(self, key):
        _, parent = self.newparent()
        if not parent.left:
            parent.left = Node(key)
        else:
            parent.right = Node(key)

    def __repr__(self):
        s = ""
        if self.left:
            s += str(self.left).replace("\n", "\n  ")
        s += "\n" + str(self.key)
        if self.right:
            s += str(self.right).replace("\n", "\n  ")
        return s

tree = Node(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
print(tree)
</code>```

This searches recursively the tree from right to left, to find the candidate parent of the node to be added.

For large trees, this can be improved a bit, by doing a binary-search among paths from root to leaf, based on the length of those paths. But it will still not be as efficient as the first two solutions.

Title: Creating Binary Tree

Body:
Most of the questions I've searched for regarding binary trees shows the implementation of binary search trees, but not binary trees. The terms of a complete binary tree are:

Either an empty tree or it has 1 node with 2 children, where each
child is another Binary Tree.

All levels are full (except for possibly the last level)

All leaves on the bottom-most level are
as far left as possible.

I've come up with a concept but it doesn't seem to running through the recursion properly -- Does anyone know what I'm doing wrong?

class Node():
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

    def add(self, key):
        if self.key:
            if self.left is None:
                self.left = Node(key)
            else:
                self.left.add(key)

                if self.right is None:
                    self.right = Node(key)
                else:
                    self.right.add(key)
        else:
            self.key = key
        return (self.key)

Body:
The problem in your code is that you are adding the same value multiple times. You add the node, and then still recurse deeper, where you do the same.

The deeper problem is that you don't really know where to insert the node before you have reached the bottom level of the tree, and have detected where that level is incomplete. Finding the correct insertion point may need a traversal through the whole tree... which is defeating the speed gain you would expect to get from using binary trees in the first place.

I provide here three solutions, starting with the most efficient:

1. Using a list as tree implementation

For complete trees there is a special consideration to make: if you number the nodes by level, starting with 0 for the root, and within each level from left to right, you notice that the number of a node's parent is (k-1)/2 when its own number is k. In the other direction: if a node with number k has children, then its left child has number k*2+1, and the right child has a number that is one greater.

Because the tree is complete, there will never be gaps in this numbering, and so you could store the nodes in a list, and use the indexes of that list for the node numbering. Adding a node to the tree now simply means you append it to that list. Instead of a Node object, you just have the tree list, and the index in that list is your node reference.

Here is an implementation:

class CompleteTree(list):
    def add(self, key):
        self.append(key)
        return len(self) - 1

    def left(self, i):
        return i * 2 + 1 if i * 2 + 1 < len(self) else -1

    def right(self, i):
        return i * 2 + 2 if i * 2 + 2 < len(self) else -1

    @staticmethod
    def parent(i):
        return (i - 1) // 2

    def swapwithparent(self, i):
        if i > 0:
            p = self.parent(i)
            self[p], self[i] = self[i], self[p]

    def inorder(self, i=0):
        left = self.left(i)
        right = self.right(i)
        if left >= 0:
            yield from self.inorder(left)
        yield i
        if right >= 0:
            yield from self.inorder(right)

    @staticmethod
    def depth(i):
        return (i + 1).bit_length() - 1

Here is a demo that creates your example tree, and then prints the keys visited in an in-order traversal, indented by their depth in the tree:

tree = CompleteTree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
for node in tree.inorder():
    print("  " * tree.depth(node), tree[node])

Of course, this means you have to reference nodes a bit different from when you would use a real Node class, but the efficiency gain pays off.

2. Using an extra property

If you know how many nodes there are in a (sub)tree, then from the bit representation of that number, you can know where exactly the next node should be added.

For instance, in your example tree you have 5 nodes. Imagine you want to add a 6 to that tree. The root node would tell you that you currently have 5 and so you need to update it to 6. In binary that is 110. Ignoring the left-most 1-bit, the rest of the bits tell you whether to go left or right. In this case, you should go right (1) and then finally left (0), creating the node in that direction. You can do this iteratively or recursively.

Here is an implementation with recursion:

class Node():
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.count = 1

    def add(self, key):
        self.count += 1
        if self.left is None:
            self.left = Node(key)
        elif self.right is None:
            self.right = Node(key)
        # extract from the count the second-most significant bit:
        elif self.count & (1 << (self.count.bit_length() - 2)):
            self.right.add(key)
        else:
            self.left.add(key)

    def inorder(self):
        if self.left:
            yield from self.left.inorder()
        yield self
        if self.right:
            yield from self.right.inorder()

tree = Node(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
for node in tree.inorder():
    print(node.key)

3. Without extra property

If no property can be added to Node objects, then a more extensive search is needed to find the right insertion point:

class Node():
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

    def newparent(self):
        # Finds the node that should serve as parent for a new node
        # It returns a tuple:
        #   if parent found: [-1, parent for new node]
        #   if not found: [height, left-most leaf]
        # In the latter case, the subtree is perfect, and its left-most
        # leaf is the node to be used, unless self is a right child
        # and its sibling has the insertion point.
        if self.right:
            right = self.right.newparent()
            if right[0] == -1: # found inbalance
                return right
            left = self.left.newparent()
            if left[0] == -1: # found inbalance
                return left
            if left[0] != right[0]:
                return [-1, right[1]] # found inbalance
            # temporary result in perfect subtree
            return [left[0]+1, left[1]]
        elif self.left:
            return [-1, self] # found inbalance
        # temporary result for leaf
        return [0, self]

    def add(self, key):
        _, parent = self.newparent()
        if not parent.left:
            parent.left = Node(key)
        else:
            parent.right = Node(key)

    def __repr__(self):
        s = ""
        if self.left:
            s += str(self.left).replace("\n", "\n  ")
        s += "\n" + str(self.key)
        if self.right:
            s += str(self.right).replace("\n", "\n  ")
        return s

tree = Node(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
print(tree)

This searches recursively the tree from right to left, to find the candidate parent of the node to be added.

For large trees, this can be improved a bit, by doing a binary-search among paths from root to leaf, based on the length of those paths. But it will still not be as efficient as the first two solutions.


答:
You really need to augment your tree in some way. Since this is not a binary search tree, the only real information you have about each node is whether or not it has a left and right child. Unfortunately, this isn't helpful in navigating a complete binary tree. Imagine a complete binary tree with 10 levels. Until the 9th level, every single node has both a left child and a right child, so you have no way of knowing which path to take down to the leaves. So the question is, what information do you add to each node? I would add the count of nodes in that tree.

Maintaining the count is easy, since every time you descend down a subtree you know to add one to the count at that node. What you want to recognize is the leftmost imperfect subtree. Every perfect binary tree has n = 2^k - 1, where k is the number of levels and n is the number of nodes. There are quick and easy ways to check if a number is 1 less than a power of two (see the first answer to this question), and in fact in a complete binary tree every node has at most one child that isn't the root of a perfect binary tree. Follow a simple rule to add nodes:

If the left child is None, set root.left = Node(key) and return

Else if the right child is None, set root.right = Node(key) and return

If one of the children of the current node is the root of an imperfect subtree, make that node the current node (descend down that subtree)

Else if the sizes are unequal, make the node with the smaller subtree the current node.

Else, make the left child the current node.

By augmenting each node with the size of the subtree rooted there, you have all the information you need at every node to build a recursive solution.

Title: Creating Binary Tree


问:
SyntaxError: Unexpected identifier with bcrypt module
js , I created a file named app.js .
I coded a login function with bcrypt module database is MySQL . I hardly find which code causes this error . I had a error below , If you find any solution , please teach me .

```<code>if (await bcrypt.compare(req.body.password, foundUser.password)) {
          ^^^^^^

SyntaxError: Unexpected identifier
    at Object.compileFunction (vm.js:344:18)
    at wrapSafe (internal/modules/cjs/loader.js:1106:15)
    at Module._compile (internal/modules/cjs/loader.js:1140:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1196:10)
    at Module.load (internal/modules/cjs/loader.js:1040:32)
    at Function.Module._load (internal/modules/cjs/loader.js:929:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
</code>```

I checked paraenthese and brackets , but it seems no wrong
Here is my whole app.js file

```<code>//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
const mysql = require("mysql");
const bcrypt = require("bcrypt");

app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);

app.get("/login", (req, res) => {
  res.render("login");
});

app.post("/login", async (req, res) => {
  connection.query(
    "SELECT * FROM user WHERE email=?",
    [req.body.useremail],
    (error, foundUser) => {
      if (foundUser.useremail == null) {
        res.status(400).send("Cannot find user");
      }
      try {
        if (await bcrypt.compare(req.body.password, foundUser.password)) {
          res.render("secrets");
        } else {
          res.send("email or password is wrong");
        }
      } catch {
        res.status(500).send();
      }
    },
  );
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});
</code>```

答: Have you tried to update or/and reinstall your version of bcrypt ?</p>

Body:
js , I created a file named app.js .
I coded a login function with bcrypt module database is MySQL . I hardly find which code causes this error . I had a error below , If you find any solution , please teach me .

if (await bcrypt.compare(req.body.password, foundUser.password)) {
          ^^^^^^

SyntaxError: Unexpected identifier
    at Object.compileFunction (vm.js:344:18)
    at wrapSafe (internal/modules/cjs/loader.js:1106:15)
    at Module._compile (internal/modules/cjs/loader.js:1140:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1196:10)
    at Module.load (internal/modules/cjs/loader.js:1040:32)
    at Function.Module._load (internal/modules/cjs/loader.js:929:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...

I checked paraenthese and brackets , but it seems no wrong
Here is my whole app.js file

//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
const mysql = require("mysql");
const bcrypt = require("bcrypt");

app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);

app.get("/login", (req, res) => {
  res.render("login");
});

app.post("/login", async (req, res) => {
  connection.query(
    "SELECT * FROM user WHERE email=?",
    [req.body.useremail],
    (error, foundUser) => {
      if (foundUser.useremail == null) {
        res.status(400).send("Cannot find user");
      }
      try {
        if (await bcrypt.compare(req.body.password, foundUser.password)) {
          res.render("secrets");
        } else {
          res.send("email or password is wrong");
        }
      } catch {
        res.status(500).send();
      }
    },
  );
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});


问:
How to change Mapbox store locator list to the dropdown and trigger href link
need some advice or help with Mapbox original sample JS code,
how to make from this peace of code dropdown instead of listings?

The idea is: change Mapbox store locator listings to the dropdown.
Any help would be nice, thanks!

I change some parts of code, but inside the dropdown is  link I need to trigger this href link for map marker action, and here I need some help ..

I have this:
(JS)

```<code>/**
   * Add a listing for each store to the sidebar.
  **/
  function buildLocationList(data) {
    data.features.forEach(function(store, i){
      /**
       * Create a shortcut for `store.properties`,
       * which will be used several times below.
      **/
      var prop = store.properties;

      /* Add a new listing section to the sidebar. */
      var listings = document.getElementById('listings');
      var listing = listings.appendChild(document.createElement('option'));
      /* Assign a unique `id` to the listing. */
      listing.id = "listing-" + prop.id;
      /* Assign the `item` class to each listing for styling. */
      listing.className = 'item';

      /* Add the link to the individual listing created above. */
      var link = listing.appendChild(document.createElement('a'));
      link.href = '#';
      link.className = 'title';
      link.id = "link-" + prop.id;
      link.innerHTML = prop.text;

      /* Add details to the individual listing. */
      var details = listing.appendChild(document.createElement('span'));
      details.innerHTML = prop.text;
      details.innerHTML = prop.address;

      /**
       * Listen to the element and when it is clicked, do four things:
       * 1. Update the `currentFeature` to the store associated with the clicked link
       * 2. Fly to the point
       * 3. Close all other popups and display popup for clicked store
       * 4. Highlight listing in sidebar (and remove highlight for all other listings)
      **/
      link.addEventListener('click', function(e){
        for (var i=0; i < data.features.length; i++) {
          if (this.id === "link-" + data.features[i].properties.id) {
            var clickedListing = data.features[i];
            flyToStore(clickedListing);
            createPopUp(clickedListing);
          }
        }
        var activeItem = document.getElementsByClassName('active');
        if (activeItem[0]) {
          activeItem[0].classList.remove('active');
        }
        this.parentNode.classList.add('active');
      });
    });
  }
</code>```

here is:
(html)

```<code><div class='sidebar'>
  <select id='listings' class='listings'></select>
</div>
</code>```

this is html after js do the magic:

```<code><div class="sidebar">
  <select id="listings" class="listings">
<option id="listing-0" class="item"><a href="#" class="title" id="link-0">store1</a><span>Address here</span></option>

........ here is more options .......
</div>
</code>```

need trigger store1 when dropdown selected?!

答:
You can't have a link inside a select option. What you can do is write the link as data attribute to the options. As the example doesn't work as Stack Snippet, here's a Fiddle.

$("select").on("change", function() {
  window.open($(this).find("option:selected").attr("data-link"), '_blank');
});
```

<pre class="lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sidebar">
  <select id="listings" class="listings">
    <option value="0">Select store</option>
    <option id="listing-0" class="item" data-link="https://www.google.com">store1 Address here</option>
    <option id="listing-1" class="item" data-link="https://www.stackoverflow.com">store2 Address here</option>
  </select>
</div>
</code>```

Body:
need some advice or help with Mapbox original sample JS code,
how to make from this peace of code dropdown instead of listings?

The idea is: change Mapbox store locator listings to the dropdown.
Any help would be nice, thanks!

I change some parts of code, but inside the dropdown is  link I need to trigger this href link for map marker action, and here I need some help ..

I have this:
(JS)

/**
   * Add a listing for each store to the sidebar.
  **/
  function buildLocationList(data) {
    data.features.forEach(function(store, i){
      /**
       * Create a shortcut for `store.properties`,
       * which will be used several times below.
      **/
      var prop = store.properties;

      /* Add a new listing section to the sidebar. */
      var listings = document.getElementById('listings');
      var listing = listings.appendChild(document.createElement('option'));
      /* Assign a unique `id` to the listing. */
      listing.id = "listing-" + prop.id;
      /* Assign the `item` class to each listing for styling. */
      listing.className = 'item';

      /* Add the link to the individual listing created above. */
      var link = listing.appendChild(document.createElement('a'));
      link.href = '#';
      link.className = 'title';
      link.id = "link-" + prop.id;
      link.innerHTML = prop.text;

      /* Add details to the individual listing. */
      var details = listing.appendChild(document.createElement('span'));
      details.innerHTML = prop.text;
      details.innerHTML = prop.address;

      /**
       * Listen to the element and when it is clicked, do four things:
       * 1. Update the `currentFeature` to the store associated with the clicked link
       * 2. Fly to the point
       * 3. Close all other popups and display popup for clicked store
       * 4. Highlight listing in sidebar (and remove highlight for all other listings)
      **/
      link.addEventListener('click', function(e){
        for (var i=0; i < data.features.length; i++) {
          if (this.id === "link-" + data.features[i].properties.id) {
            var clickedListing = data.features[i];
            flyToStore(clickedListing);
            createPopUp(clickedListing);
          }
        }
        var activeItem = document.getElementsByClassName('active');
        if (activeItem[0]) {
          activeItem[0].classList.remove('active');
        }
        this.parentNode.classList.add('active');
      });
    });
  }

here is:
(html)

  <select id='listings' class='listings'></select>

this is html after js do the magic:

  <select id="listings" class="listings">
<option id="listing-0" class="item">store1Address here</option>

........ here is more options .......

need trigger store1 when dropdown selected?!

Body:
You can't have a link inside a select option. What you can do is write the link as data attribute to the options. As the example doesn't work as Stack Snippet, here's a Fiddle.

$("select").on("change", function() {
  window.open($(this).find("option:selected").attr("data-link"), '_blank');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sidebar">
  <select id="listings" class="listings">
    <option value="0">Select store</option>
    <option id="listing-0" class="item" data-link="https://www.google.com">store1 Address here</option>
    <option id="listing-1" class="item" data-link="https://www.stackoverflow.com">store2 Address here</option>
  </select>
</div>


问:
Issue with newsapi.org API and JQuery
I am getting the following error message:

Failed to load resource: the server responded with a status of 426 (Upgrade Required)"
  error on using JQuery to GET results from https://newsapi.org/v2/top-headlines?country=in&apiKey=..... using proxy-https://cors-anywhere.herokuapp.com/ on a ngrok hosted https site  and the localhost too.

But the same process works if I use http instead of https i.e. https://cors-anywhere.herokuapp.com/https://newsapi.org/... and use the http ngrok site.

This is the response I get if I use http-

{status: "error", code: "corsNotAllowed",…}
  code: "corsNotAllowed"
  message: "Requests via the browser are not allowed on the Developer plan, except from localhost."
  status: "error"}

Is there a workaround for this? Will this error go it I host it properly using my domain and by an ssl ?

答:
You are trying to access an API which is not accepting requests from a website (except from localhost). If the browser comes across a request which is cross-origin, it tries to make a pre-flight request (an initial request to ask the server, it is okay to fetch from this remote address, which is different than the current domain). If the pre-flight request is not responded with a successful message, the Ajax request fails. This behavior is called CORS and it must be supported by the API.

Your API does not seem to allow i.e. it actually forbids CORS requests explicitly. This is usually done, if the API wants to force the developer to make the request on the server-side. The benefit of this is, that the access key is not sent along with the JavaScript code to the visitor of the website but rather it stays on the server.

Try to make the request on your server and then send the data to your front-end from your own server. This also allows to use your own authentication. You could also use a web service like CORS everywhere, but keep in mind that this service has access to all data you are sending and receiving (and it is able to modify the data both-ways).

Title: Issue with newsapi.org API and JQuery


问:
How to return the PrintArea from Excel in Python
I'm trying to create a Python script (I'm using Python 3.7.3 with UTF-8 encoding on Windows 10 64-bit with Microsoft Office 365) that exports user selected worksheets to PDF, after the user has selected the Excel-files.

The Excel-files contain a lot of different settings for page setup and each worksheet in each Excel-file has a different page setup.

The task is therefore that I need to read all current variables regarding page setup to be able to assign them to the related variables for export.

The problem is when I'm trying to get Excel to return the current print area of the worksheet, which I can't figure out.
As far as I understand I need to be able to read the current print area, to be able to set it for the export.

The Excel-files are a mixture of ".xlxs" and ".xlsm".

I've tried using all kind of different methods from the Excel VBA documentation, but nothing has worked so far e.g. by adding ".Range" and ".Address" etc.

I've also tried the ".UsedRange", but there is no significant difference in the cells that I can search for and I can't format them in a specific way so I can't use this.

I've also tried using the "IgnorePrintAreas = False" variable in the "ExportAsFixedFormat"-function, but that didn't work either.

```<code>#This is some of the script.
#I've left out irrelevant parts (dialogboxes etc.) just to make it shorter

#Import pywin32 and open Excel and selected workbook.
import win32com.client as win32

excel = win32.gencache.EnsureDispatch("Excel.Application")
excel.Visible = False

wb = excel.Workbooks.Open(wb_path)

#Select the 1st worksheet in the workbook
#This is just used for testing
wb.Sheets([1]).Select()

#This is the line I can't get to work
ps_prar = wb.ActiveSheet.PageSetup.PrintArea

#This is just used to test if I get the print area
print(ps_prar)

#This is exporting the selected worksheet to PDF
wb.Sheets([1]).Select()
wb.ActiveSheet.ExportAsFixedFormat(0, pdf_path, Quality = 0, IncludeDocProperties = True, IgnorePrintAreas = False, OpenAfterPublish = True)

#This closes the workbook and the Excel-file (although Excel sometimes still exists in Task Manager
wb.Close()
wb = None
excel.Quit()
excel = None
</code>```

If I leave the code as above and try and open a test Excel-file (.xlxs) with a small PrintArea (A1:H8) the print function just gives me a blank line.
If I add something to .PrintArea (as mentioned above) I get 1 of 2 errors:

"TypeError: 'str' object is not callable".

or

"ps_prar = wb.ActiveSheet.PageSetup.PrintArea.Range
  AttributeError: 'str' object has no attribute 'Range'"

I'm hoping someone can help me in this matter - thanks, in advance.

答:
try

```<code>wb = excel.Workbooks.OpenXML(wb_path)
</code>```

insead of

```<code>wb = excel.Workbooks.Open(wb_path)
</code>```

My problem was with a german version of ms-office. It works now. Check here https://social.msdn.microsoft.com/Forums/de-DE/3dce9f06-2262-4e22-a8ff-5c0d83166e73/excel-api-interne-namen?forum=officede

Body:
I'm trying to create a Python script (I'm using Python 3.7.3 with UTF-8 encoding on Windows 10 64-bit with Microsoft Office 365) that exports user selected worksheets to PDF, after the user has selected the Excel-files.

The Excel-files contain a lot of different settings for page setup and each worksheet in each Excel-file has a different page setup.

The task is therefore that I need to read all current variables regarding page setup to be able to assign them to the related variables for export.

The problem is when I'm trying to get Excel to return the current print area of the worksheet, which I can't figure out.
As far as I understand I need to be able to read the current print area, to be able to set it for the export.

The Excel-files are a mixture of ".xlxs" and ".xlsm".

I've tried using all kind of different methods from the Excel VBA documentation, but nothing has worked so far e.g. by adding ".Range" and ".Address" etc.

I've also tried the ".UsedRange", but there is no significant difference in the cells that I can search for and I can't format them in a specific way so I can't use this.

I've also tried using the "IgnorePrintAreas = False" variable in the "ExportAsFixedFormat"-function, but that didn't work either.

#This is some of the script.
#I've left out irrelevant parts (dialogboxes etc.) just to make it shorter

#Import pywin32 and open Excel and selected workbook.
import win32com.client as win32

excel = win32.gencache.EnsureDispatch("Excel.Application")
excel.Visible = False

wb = excel.Workbooks.Open(wb_path)

#Select the 1st worksheet in the workbook
#This is just used for testing
wb.Sheets([1]).Select()

#This is the line I can't get to work
ps_prar = wb.ActiveSheet.PageSetup.PrintArea

#This is just used to test if I get the print area
print(ps_prar)

#This is exporting the selected worksheet to PDF
wb.Sheets([1]).Select()
wb.ActiveSheet.ExportAsFixedFormat(0, pdf_path, Quality = 0, IncludeDocProperties = True, IgnorePrintAreas = False, OpenAfterPublish = True)

#This closes the workbook and the Excel-file (although Excel sometimes still exists in Task Manager
wb.Close()
wb = None
excel.Quit()
excel = None

If I leave the code as above and try and open a test Excel-file (.xlxs) with a small PrintArea (A1:H8) the print function just gives me a blank line.
If I add something to .PrintArea (as mentioned above) I get 1 of 2 errors:

"TypeError: 'str' object is not callable".

or

"ps_prar = wb.ActiveSheet.PageSetup.PrintArea.Range
  AttributeError: 'str' object has no attribute 'Range'"

I'm hoping someone can help me in this matter - thanks, in advance.

Body:
try

wb = excel.Workbooks.OpenXML(wb_path)

insead of

wb = excel.Workbooks.Open(wb_path)

My problem was with a german version of ms-office. It works now. Check here https://social.msdn.microsoft.com/Forums/de-DE/3dce9f06-2262-4e22-a8ff-5c0d83166e73/excel-api-interne-namen?forum=officede


问:
Point in rectangle
What is the fastest way to find if a point is in a rectangle given in this form:

I have two points which are the centers of opposite sides of the rectangle, and a number which is the height of those sides. I hope this is clear.

The rectangle is (probably) not aligned with the axis. I am wondering if there may be a faster algorithm given this data then calculating the four corners, rotating, etc.

An idea I though of but am not sure how to implement (having trouble with the math) was to find the distance from the point to the line traced between the two centers, and if it is  less then half the length of the side of the rectangle and also on the line then it is in the rectangle. I don't know how to explain this better.

Maybe the picture will help explain:

A, B, C are given, as well as the length of side A/B. Basically I thought that if CD is less then half of side A and D is on AB, the point is in the rectangle. But how do I do this?

Another thought: Instead of finding D to see if it is on AB, check if angles ABC and BAC are acute, but I still don't know how to do this.

答:
The idea with the acute triangle ABC does not work. E.g. it the point C is directly besides the line AB the angle at C will become almost 180°. On the other hand the angle at B might be very small if the rectangle's height is fairly small but C does then lie outside the rectangle.

Nevertheless your other approach is one basic way to implements this.

The point D is somewhere on the line through A and B, thus

```<code>D = A + t * (B-A)
</code>```

(captial letters stand for vectors in space, small letters for numbers). At the same time the connection from D to C is perpendicular to the connection A to B and thus

```<code>(C-D) . (B-A) == 0
</code>```

i.e. the dot product of the two difference vectors is zero. Putting both together yields

```<code>(C-A-t*(B-A)) . (B-A) = (C-A) . (B-A) - t * (B-A) . (B-A) == 0
</code>```

or when solved for t:

```<code>t = (C-A).(B-A) / (B-A).(B-A)
</code>```

(or in other words the relative length of the projection of the vector AC onto the line AB).

The point D is within the rectangle if 0 <= t <= 1, and thus this is your first condition.

Afterwards you can calulate the distance of C to D (just insert t into the very first eqn to get D) and compare this to h/2, i.e. the last condition then is

```<code>(C-D).(C-D) <= (h/2)^2
</code>```

ContentLicense: CC BY-SA 3.0

Title: Point in rectangle

Body:
The idea with the acute triangle ABC does not work. E.g. it the point C is directly besides the line AB the angle at C will become almost 180°. On the other hand the angle at B might be very small if the rectangle's height is fairly small but C does then lie outside the rectangle.

Nevertheless your other approach is one basic way to implements this.

The point D is somewhere on the line through A and B, thus

D = A + t * (B-A)

(captial letters stand for vectors in space, small letters for numbers). At the same time the connection from D to C is perpendicular to the connection A to B and thus

(C-D) . (B-A) == 0

i.e. the dot product of the two difference vectors is zero. Putting both together yields

(C-A-t*(B-A)) . (B-A) = (C-A) . (B-A) - t * (B-A) . (B-A) == 0

or when solved for t:

t = (C-A).(B-A) / (B-A).(B-A)

(or in other words the relative length of the projection of the vector AC onto the line AB).

The point D is within the rectangle if 0 <= t <= 1, and thus this is your first condition.

Afterwards you can calulate the distance of C to D (just insert t into the very first eqn to get D) and compare this to h/2, i.e. the last condition then is

(C-D).(C-D) <= (h/2)^2


问:
Declare multiple worksheets as variables
I am trying to declare some variables for the worksheets in this way

```<code>Dim e
For Each e In Array("Data", "CL", "SE", "GE", "E1", "E2", "E3", "E4", "E5", "STP", "STF", "RH", "CR", "MC", "AW")
    Set wsData = ThisWorkbook.Worksheets(e)
Next e
</code>```

Is it possible to declare all the worksheets using the 1d array ..? If not, is there a workaround to smart approach to do that ..?
example wsData to refer to the worksheet "Data"
and wsCL to refer to the worksheet "CL" and so on.

答:
You can loop through the built in Worksheets collection like so...

```<code>For each e in ThisWorkbook.Worksheets
    'Now e represents a workbook object with each iteration
    Debug.Print e.Name
Next e
</code>```

You could also use Sheets rather than Worksheets.

If desired you could use a For...Next loop too, like so...

```<code>For e = 1 to ThisWorkbook.Worksheets.Count
    Debug.Print ThisWorkbook.Worksheets(e).Name
Next e
</code>```

Body:
I am trying to declare some variables for the worksheets in this way

Dim e
For Each e In Array("Data", "CL", "SE", "GE", "E1", "E2", "E3", "E4", "E5", "STP", "STF", "RH", "CR", "MC", "AW")
    Set wsData = ThisWorkbook.Worksheets(e)
Next e

Is it possible to declare all the worksheets using the 1d array ..? If not, is there a workaround to smart approach to do that ..?
example wsData to refer to the worksheet "Data"
and wsCL to refer to the worksheet "CL" and so on.

Body:
You can loop through the built in Worksheets collection like so...

For each e in ThisWorkbook.Worksheets
    'Now e represents a workbook object with each iteration
    Debug.Print e.Name
Next e

You could also use Sheets rather than Worksheets.

If desired you could use a For...Next loop too, like so...

For e = 1 to ThisWorkbook.Worksheets.Count
    Debug.Print ThisWorkbook.Worksheets(e).Name
Next e


问:
Flask - One flash message will not go away, due to functools.wraps?
I am building a simple flask webapp as part of Harvard's CS50 Web Programming Course to learn web development.  I've successfully got user registration / log in / logout implemented, along with various message flashing to give the user feedback.

For some reason, the "Login Successful" flash message just won't go away after its displayed.  I've read the documentation, and some useful posts like this and this.  It seems like any route with the @login_required decorator can't get rid of the flashed message.

Fully working code is here: GoodBookBadBook

Here is the application.py file:

```<code>import os
from flask import Flask, session, request, render_template, url_for, redirect, flash
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from werkzeug.security import generate_password_hash, check_password_hash
import functools

app = Flask(__name__)

DATABASE_URL = "postgres://xqmbmqkcvpavvs:17f6f6f690bb777e4d484e3ee441e3b4d8c88591d239a9beb49aca4599863b97@ec2-52-70-15-120.compute-1.amazonaws.com:5432/dfg72kp1ckutig"
app.config["DATABASE_URL"] = DATABASE_URL

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Set up database
engine = create_engine(DATABASE_URL)
db = scoped_session(sessionmaker(bind=engine))

def login_required(route_func):
    @functools.wraps(route_func)  # returns wrapper as route_func (?).
    def wrapper(*args, **kwargs):
        print(f"wrapper flashes: {session.get('_flashes', [])}", flush=True)
        if "logged_in" in session:
            return route_func(*args, **kwargs)
        else:
            flash("You must log in to use GoodBookBadBook.", category="error")
            return redirect(url_for('login'))
    return wrapper

@app.route("/")
def index():
    print(f"index flashes: {session.get('_flashes', [])}", flush=True)
    return render_template("index.html", logged_in=session.get("logged_in", False))

@app.route("/main")
@login_required
def main():
    print(f"main flashes: {session.get('_flashes', [])}", flush=True)
    return render_template("main.html", logged_in=session.get("logged_in", False))

@app.route("/books")
@login_required  # calls wrapper() with arguments to books().
def books():
    print(f"books flashes: {session.get('_flashes', [])}", flush=True)
    books = db.execute("SELECT * from Books").fetchall()
    return render_template("books.html", books=books, logged_in=session.get("logged_in", False))

@app.route("/books/<int:book_id>")
@login_required  # calls wrapper() with arguments to books().
def book(book_id):
    print(f"book flashes: {session.get('_flashes', [])}", flush=True)
    book = db.execute("SELECT * from Books WHERE id = :book_id", {"book_id": book_id}).fetchone()
    print(f"book() /books/book_id {book}", flush=True)
    return render_template("book.html", book=book, logged_in=session.get("logged_in", False))

@app.route("/authors")
@login_required  # calls wrapper() with arguments to authors().
def authors():
    print(f"authors flashes: {session.get('_flashes', [])}", flush=True)
    books = db.execute("SELECT * from Books").fetchall()
    return render_template("authors.html", books=books, logged_in=session.get("logged_in", False))

@app.route("/signup", methods=["GET", "POST"])
def signup():
    username = request.form.get("username")
    pwd = request.form.get("pwd")
    repeat_pwd = request.form.get("repeat_pwd")
    print(f"signup flashes: {session.get('_flashes', [])}", flush=True)
    if request.method == "POST":
        if validate_registration(username, pwd, repeat_pwd):
            hash = generate_password_hash(pwd)
            db.execute("INSERT INTO Users(Username, Hash) VALUES (:username, :hash)",
                       {"username": username, "hash": hash})
            db.commit()
            flash("Registration successful.", category="success")
            return redirect(url_for('login'))
    return render_template("signup.html")

def validate_registration(username, pwd, repeat_pwd):
    existing_user = db.execute("SELECT * from Users WHERE Username = :username",
                               {"username": username}).fetchone()
    print(f"validate_registration flashes: {session.get('_flashes', [])}", flush=True)
    if existing_user:
        flash("Username unavailable.", category="error")
        return False
    if len(username) < 3:
        flash("Username must be at least 3 characters", category="error")
        return False
    if pwd != repeat_pwd:
        flash("Passwords do not match.", category="error")
        return False
    if len(pwd) < 3:
        flash("Password must be at least 3 characters.", category="error")
        return False
    return True

@app.route("/login", methods=["GET", "POST"])
def login():
    username = request.form.get("username")
    pwd = request.form.get("pwd")
    print(f"login flashes: {session.get('_flashes', [])}", flush=True)
    if request.method == "POST":
        existing_user = db.execute("SELECT * from Users WHERE Username = :username",
                                   {"username": username}).fetchone()
        if not existing_user:
            flash("No user found. Please sign up first.", category="error")
            return redirect(url_for('signup'))
        if not check_password_hash(existing_user.hash, pwd):
            flash("Incorrect password.", category="error")
            return
        else:
            session["logged_in"] = True
            flash("Login successful. Thank you for using GoodBookBadBook.", category="success")
            return redirect(url_for('main'))
    return render_template("login.html")

@app.route("/logout")
def logout():
    print(f"logout flashes: {session.get('_flashes', [])}", flush=True)
    session.pop("logged_in", None)
    flash("You have successfully been logged out. Come back soon!", category="success")
    return render_template("logout.html", logged_in=session.get("logged_in", False))
</code>```

Been stuck on this all day, any help is appreciated.

EDIT:  I updated the git repo to remove all references to a timeout script.  I am not going to use a timeout script in the final code.

EDIT 2: Here's a 30 second video of the problem.

答:
just delete the  block script from  signup.html and main.html and it will work

```<code>{% block scripts %}
{#  <script type="text/javascript">window.setTimeout("document.getElementById('success-msg').style.display='none';", 2000); </script>#}
{% endblock %}
</code>```

in Layout.html  in head tag add for sucess-msg and error-msg

```<code><head>
<script   type="text/javascript">window.setTimeout("document.getElementById('success-msg').style.display='none';", 2000); </script>
</head>
</code>```

Being layout.html as your base Html page, you need to add all the common use script in that base file, which can be used in other files. ERROR is occurring because of this (render_template function, jinja internal caching, don't worry about that now)

Body:
I am building a simple flask webapp as part of Harvard's CS50 Web Programming Course to learn web development.  I've successfully got user registration / log in / logout implemented, along with various message flashing to give the user feedback.

For some reason, the "Login Successful" flash message just won't go away after its displayed.  I've read the documentation, and some useful posts like this and this.  It seems like any route with the @login_required decorator can't get rid of the flashed message.

Fully working code is here: GoodBookBadBook

Here is the application.py file:

import os
from flask import Flask, session, request, render_template, url_for, redirect, flash
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from werkzeug.security import generate_password_hash, check_password_hash
import functools

app = Flask(__name__)

DATABASE_URL = "postgres://xqmbmqkcvpavvs:17f6f6f690bb777e4d484e3ee441e3b4d8c88591d239a9beb49aca4599863b97@ec2-52-70-15-120.compute-1.amazonaws.com:5432/dfg72kp1ckutig"
app.config["DATABASE_URL"] = DATABASE_URL

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Set up database
engine = create_engine(DATABASE_URL)
db = scoped_session(sessionmaker(bind=engine))

def login_required(route_func):
    @functools.wraps(route_func)  # returns wrapper as route_func (?).
    def wrapper(*args, **kwargs):
        print(f"wrapper flashes: {session.get('_flashes', [])}", flush=True)
        if "logged_in" in session:
            return route_func(*args, **kwargs)
        else:
            flash("You must log in to use GoodBookBadBook.", category="error")
            return redirect(url_for('login'))
    return wrapper

@app.route("/")
def index():
    print(f"index flashes: {session.get('_flashes', [])}", flush=True)
    return render_template("index.html", logged_in=session.get("logged_in", False))

@app.route("/main")
@login_required
def main():
    print(f"main flashes: {session.get('_flashes', [])}", flush=True)
    return render_template("main.html", logged_in=session.get("logged_in", False))

@app.route("/books")
@login_required  # calls wrapper() with arguments to books().
def books():
    print(f"books flashes: {session.get('_flashes', [])}", flush=True)
    books = db.execute("SELECT * from Books").fetchall()
    return render_template("books.html", books=books, logged_in=session.get("logged_in", False))

@app.route("/books/<int:book_id>")
@login_required  # calls wrapper() with arguments to books().
def book(book_id):
    print(f"book flashes: {session.get('_flashes', [])}", flush=True)
    book = db.execute("SELECT * from Books WHERE id = :book_id", {"book_id": book_id}).fetchone()
    print(f"book() /books/book_id {book}", flush=True)
    return render_template("book.html", book=book, logged_in=session.get("logged_in", False))

@app.route("/authors")
@login_required  # calls wrapper() with arguments to authors().
def authors():
    print(f"authors flashes: {session.get('_flashes', [])}", flush=True)
    books = db.execute("SELECT * from Books").fetchall()
    return render_template("authors.html", books=books, logged_in=session.get("logged_in", False))

@app.route("/signup", methods=["GET", "POST"])
def signup():
    username = request.form.get("username")
    pwd = request.form.get("pwd")
    repeat_pwd = request.form.get("repeat_pwd")
    print(f"signup flashes: {session.get('_flashes', [])}", flush=True)
    if request.method == "POST":
        if validate_registration(username, pwd, repeat_pwd):
            hash = generate_password_hash(pwd)
            db.execute("INSERT INTO Users(Username, Hash) VALUES (:username, :hash)",
                       {"username": username, "hash": hash})
            db.commit()
            flash("Registration successful.", category="success")
            return redirect(url_for('login'))
    return render_template("signup.html")

def validate_registration(username, pwd, repeat_pwd):
    existing_user = db.execute("SELECT * from Users WHERE Username = :username",
                               {"username": username}).fetchone()
    print(f"validate_registration flashes: {session.get('_flashes', [])}", flush=True)
    if existing_user:
        flash("Username unavailable.", category="error")
        return False
    if len(username) < 3:
        flash("Username must be at least 3 characters", category="error")
        return False
    if pwd != repeat_pwd:
        flash("Passwords do not match.", category="error")
        return False
    if len(pwd) < 3:
        flash("Password must be at least 3 characters.", category="error")
        return False
    return True

@app.route("/login", methods=["GET", "POST"])
def login():
    username = request.form.get("username")
    pwd = request.form.get("pwd")
    print(f"login flashes: {session.get('_flashes', [])}", flush=True)
    if request.method == "POST":
        existing_user = db.execute("SELECT * from Users WHERE Username = :username",
                                   {"username": username}).fetchone()
        if not existing_user:
            flash("No user found. Please sign up first.", category="error")
            return redirect(url_for('signup'))
        if not check_password_hash(existing_user.hash, pwd):
            flash("Incorrect password.", category="error")
            return
        else:
            session["logged_in"] = True
            flash("Login successful. Thank you for using GoodBookBadBook.", category="success")
            return redirect(url_for('main'))
    return render_template("login.html")

@app.route("/logout")
def logout():
    print(f"logout flashes: {session.get('_flashes', [])}", flush=True)
    session.pop("logged_in", None)
    flash("You have successfully been logged out. Come back soon!", category="success")
    return render_template("logout.html", logged_in=session.get("logged_in", False))

Been stuck on this all day, any help is appreciated.

EDIT:  I updated the git repo to remove all references to a timeout script.  I am not going to use a timeout script in the final code.

EDIT 2: Here's a 30 second video of the problem.

Body:
just delete the  block script from  signup.html and main.html and it will work

{% block scripts %}
{#  <script type="text/javascript">window.setTimeout("document.getElementById('success-msg').style.display='none';", 2000); </script>#}
{% endblock %}

in Layout.html  in head tag add for sucess-msg and error-msg

<head>
<script   type="text/javascript">window.setTimeout("document.getElementById('success-msg').style.display='none';", 2000); </script>
</head>

Being layout.html as your base Html page, you need to add all the common use script in that base file, which can be used in other files. ERROR is occurring because of this (render_template function, jinja internal caching, don't worry about that now)


问:
Xamarin Forms ( iOS build) "Can't resolve the reference 'System.Configuration.ConfigurationException'
I have hit a blocking error after upgrading to Visual Studio 2019 16.6.0 and subsequently upgraded Xamarin.IOS package to 13.4.

Here is the exact error message:
Can't resolve the reference 'System.Configuration.ConfigurationException', referenced from the method 'System.Void System.Configuration.ConfigurationErrorsException::.ctor(System.String,System.Exception,System.String,System.Int32)' in 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.   HSETicketingMobile.iOS

The app used to build successfully before the upgrade. Is there anything I can do or is it a newly introduced upgrade issue and I have to wait for the fix from Microsoft?

I tried to google the error but I couldn't find any solution.

My visual studio is on Windows and I'm connecting to XCode over the LAN.
Thank you

Here is my build log:
https://drive.google.com/open?id=1ZwwIZVwWZdge0uleZyPDySfhHczHuXOI

答:
Finally, I found the source of the problem.

I was including System.ComponentModel.DataAnnotations in one of my modules and it was in turn calling System.Configuration.ConfigurationException under the hood.

I added a build condition to exclude the use of the DataAnnotations for my Xamarin.iOS and that solved the problem.

The strange thing is that my code hasn't changed and just upgrading to VS 2019 16.6.0 caused the problem to happen.

I got a hint from this discussion thread here

I hope this helps someone else.


问:
Load textures from images stored in StreamingDataPath
I'm trying very hard to understand how should i store and load some images in my Unity app for Android platform.

From what i understood, i should store them in the Application.streamingAssetsPath.
However i don't know how to access them.

Note: My images are in sub-folders within the streaming assets folder.

答:
Here a some pages that I think might help you:

The docs:
https://docs.unity3d.com/Manual/StreamingAssets.html

Others:
https://answers.unity.com/questions/210909/android-streamingassets-file-access.html

https://forum.unity.com/threads/solved-loading-image-from-streamingassets.717869/

Personally, I do not develop on android so I can’t help you more unfortunately but I am hopping this can help a bit.


问:
How to check if user is already logged in via Spotify in Android Studio?
I'm developing a music app that has 'login with spotify' feature. I followed this guide to achieve authorize users.

But i don't want to authorize users everytime they opened the app. That would be terrible user exprience. When we use twitter's SDK or Firebase Auth, there are some singletons to get current auth information. By getting that object we can know if user is already logged in or not when the app starts. Is there an equivalent class or mechanism to do so with Spotify's sdk?

答:
You can use Room database to save user data local. When user opens app check if user exists in database.

I guess you have some Splash/Loading/Welcome screen with your app logo when you start your app. You can save some information from user local and do auth there with that data (something like token or id).

Here is url for Room database:
https://developer.android.com/training/data-storage/room


问:
How to Convert Arabic Characters to Unicode Using PHP
I want to to know how can I convert a word into unicode exactly like:
http://www.arabunic.free.fr/

can anyone know how to do that using PHP considering that Arabic text may contains ligatures?

thanks

Edit

I'm not sure what is that "unicode" but I need to have the Arabic Character in it's equivalent machine number considering that arabic characters have different  contextual forms depending on their position - see here:

http://en.wikipedia.org/wiki/Arabic_alphabet#Table_of_basic_letters

the same character in different position:

ب | ـب |    ـبـ | بـ

I think it must be a way to convert each Arabic character into it's equivalent number, but how?

Edit

I still believe there's a way to convert each character to it's form depending on positions

any idea is appreciated..

答:
I'm totally agree with FloatBird about the use of the arabic.php which you will find it as he said at ar-php, The thing is they have changed the class name after version 4 from Arabic to I18N_Arabic so in order for the code to work using arabic.php ver 4.0 you need to change the code to

```<code><?php
include('Arabic.php');
$Arabic = new I18N_Arabic('ArGlyphs');

$text = 'بسم الله الرحمن الرحيم';
$text = $Arabic->utf8Glyphs($text);
echo $text;
?>
</code>```

Also notice that you need to put the php code file inside the I18N folder.

Anyway it is working fantastically, Thanks again FloatBird

Body:
I'm totally agree with FloatBird about the use of the arabic.php which you will find it as he said at ar-php, The thing is they have changed the class name after version 4 from Arabic to I18N_Arabic so in order for the code to work using arabic.php ver 4.0 you need to change the code to

<?php
include('Arabic.php');
$Arabic = new I18N_Arabic('ArGlyphs');

$text = 'بسم الله الرحمن الرحيم';
$text = $Arabic->utf8Glyphs($text);
echo $text;
?>

Also notice that you need to put the php code file inside the I18N folder.

Anyway it is working fantastically, Thanks again FloatBird


问:
Can't replace "[" and "]" characters in a string in Javascript
I'm trying to replace "[" and "]" characters in the string using javascript.

when I'm doing

```<code>newString = oldString.replace("[]", "");
</code>```

then it works fine - but the problem is I have a lot of this characters in my string and I need to replace all of the occurrences.

But when I'm doing:

```<code>newString = oldString.replace(/[]/g, "");
</code>```

or

```<code>newString = oldString.replace(/([])/g, "");
</code>```

nothing is happens. I've also tried with HTML numbers like

```<code>newString = oldString.replace(/[]/g, "");
</code>```

but it doesn't work neither. Any ideas how to make it?

答:
had a similair situation. i just used backslash like so.</p>

```<code>-replace '\[','' -replace ']',''
</code>```

Body:
I'm trying to replace "[" and "]" characters in the string using javascript.

when I'm doing

newString = oldString.replace("[]", "");

then it works fine - but the problem is I have a lot of this characters in my string and I need to replace all of the occurrences.

But when I'm doing:

newString = oldString.replace(/[]/g, "");

or

newString = oldString.replace(/([])/g, "");

nothing is happens. I've also tried with HTML numbers like

newString = oldString.replace(/[]/g, "");

but it doesn't work neither. Any ideas how to make it?

Body:
had a similair situation. i just used backslash like so.

-replace '\[','' -replace ']',''


问:
How can I ignore cascade when calling persist/merge
How can I ignore cascade saving/updating when calling persist(..)/ merge(..) without removing cascade annotation?

答:
You can't. Two workarounds come to my mind:

empty the collections before persisting

use HQL to insert/update

Neither is a good option though.


问:
How to display an Hebrew mapbox?
How to present an Hebrew mapbox? (https://www.mapbox.com/)

I'm using mapbox-gl-js.

答:
Mapbox does not include support for worldwide Hebrew labels, per this Github issue.

However, if you select "Local" as the language in Mapbox Studio, then it will show the labels in Hebrew in Israel only.

Title: How to display an Hebrew mapbox?


问:
Returning an array from a function to main in c++
How can I return this array to the main function for further use in my program?</p>

```<code>int* enterMarks(int marks) {

int arr[marks];
cout << "Please enter " << marks << "marks (0<=Mark<=100):" << endl;

for (int i = 0; i < marks; i++) {
    cout << i+1 << ">";
    cin >> arr[i];
}
cout << "Thank you..." << endl;

return *arr;
</code>```

答:
For starters variable length arrays like this

```<code>int* enterMarks(int marks) {

int arr[marks];
//...
</code>```

is not a standard C++ feature. In C++ the size of an array shall be a compile-time constant.

Secondly a pointer to a local array with automatic storage duration returned from the function will have invalid value because the local array will not be alive after exiting the function.

You need to have a dynamically allocated array.

Either you can use the smart pointer std::unique_ptr  that will point to a dynamically allocated array as shown in the demonstrative program below.

```<code>#include <iostream>
#include <memory>

std::unique_ptr<unsigned int[]> enterMarks( size_t marks )
{
    const unsigned HIGH_MARK = 100;

    auto arr = std::make_unique<unsigned int[]>( marks );

    std::cout << "Please enter " << marks
              << " marks (0<=Mark<=" << HIGH_MARK << "):" << std::endl;

    for ( size_t i = 0; i < marks; i++ )
    {
        std::cout << i+1 << "> ";
        std::cin >> arr[i];
    }

    std::cout << "Thank you..." << std::endl;

    return arr;
}

int main()
{
    size_t n = 10;

    auto arr = enterMarks( n );

    for ( size_t i = 0; i < n; i++ )
    {
        std::cout << arr[i] << ' ';
    }
    std::cout << '\n';

    return 0;
}
</code>```

The program output might look like

```<code>Please enter 10 marks (0<=Mark<=100):
1> 10
2> 20
3> 30
4> 40
5> 50
6> 60
7> 70
8> 80
9> 90
10> 100
Thank you...
10 20 30 40 50 60 70 80 90 100
</code>```

Or you can use the standard class template std::vector as shown below.

```<code>#include <iostream>
#include <vector>

std::vector<unsigned int> enterMarks( size_t marks )
{
    const unsigned HIGH_MARK = 100;

    std::vector<unsigned int> arr( marks );

    std::cout << "Please enter " << marks
              << " marks (0<=Mark<=" << HIGH_MARK << "):" << std::endl;

    for ( size_t i = 0; i < marks; i++ )
    {
        std::cout << i+1 << "> ";
        std::cin >> arr[i];
    }

    std::cout << "Thank you..." << std::endl;

    return arr;
}

int main()
{
    size_t n = 10;

    auto arr = enterMarks( n );

    for ( size_t i = 0; i < n; i++ )
    {
        std::cout << arr[i] << ' ';
    }
    std::cout << '\n';

    return 0;
}
</code>```

The program output might look the same way as shown above.

Pay attention that there is no great sense to maje the array of the signed integer type int. It is better to use unsigned integer type unsigned int.

Body:
How can I return this array to the main function for further use in my program?

int* enterMarks(int marks) {

int arr[marks];
cout << "Please enter " << marks << "marks (0<=Mark<=100):" << endl;

for (int i = 0; i < marks; i++) {
    cout << i+1 << ">";
    cin >> arr[i];
}
cout << "Thank you..." << endl;

return *arr;

Body:
For starters variable length arrays like this

int* enterMarks(int marks) {

int arr[marks];
//...

is not a standard C++ feature. In C++ the size of an array shall be a compile-time constant.

Secondly a pointer to a local array with automatic storage duration returned from the function will have invalid value because the local array will not be alive after exiting the function.

You need to have a dynamically allocated array.

Either you can use the smart pointer std::unique_ptr  that will point to a dynamically allocated array as shown in the demonstrative program below.

#include <iostream>
#include <memory>

std::unique_ptr<unsigned int[]> enterMarks( size_t marks )
{
    const unsigned HIGH_MARK = 100;

    auto arr = std::make_unique<unsigned int[]>( marks );

    std::cout << "Please enter " << marks
              << " marks (0<=Mark<=" << HIGH_MARK << "):" << std::endl;

    for ( size_t i = 0; i < marks; i++ )
    {
        std::cout << i+1 << "> ";
        std::cin >> arr[i];
    }

    std::cout << "Thank you..." << std::endl;

    return arr;
}

int main()
{
    size_t n = 10;

    auto arr = enterMarks( n );

    for ( size_t i = 0; i < n; i++ )
    {
        std::cout << arr[i] << ' ';
    }
    std::cout << '\n';

    return 0;
}

The program output might look like

Please enter 10 marks (0<=Mark<=100):
1> 10
2> 20
3> 30
4> 40
5> 50
6> 60
7> 70
8> 80
9> 90
10> 100
Thank you...
10 20 30 40 50 60 70 80 90 100

Or you can use the standard class template std::vector as shown below.

#include <iostream>
#include <vector>

std::vector<unsigned int> enterMarks( size_t marks )
{
    const unsigned HIGH_MARK = 100;

    std::vector<unsigned int> arr( marks );

    std::cout << "Please enter " << marks
              << " marks (0<=Mark<=" << HIGH_MARK << "):" << std::endl;

    for ( size_t i = 0; i < marks; i++ )
    {
        std::cout << i+1 << "> ";
        std::cin >> arr[i];
    }

    std::cout << "Thank you..." << std::endl;

    return arr;
}

int main()
{
    size_t n = 10;

    auto arr = enterMarks( n );

    for ( size_t i = 0; i < n; i++ )
    {
        std::cout << arr[i] << ' ';
    }
    std::cout << '\n';

    return 0;
}

The program output might look the same way as shown above.

Pay attention that there is no great sense to maje the array of the signed integer type int. It is better to use unsigned integer type unsigned int.


问:
How can I compare two time strings in the format HH:MM:SS?
I have two time strings in HH:MM:SS format. For example, str1 contains 10:20:45,  str2 contains 5:10:10.

How can I compare the above values?

答:
```<code>Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')
> true
</code>```

The 1st January is an arbitrary date, doesn't mean anything.

Body:
Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')
> true

The 1st January is an arbitrary date, doesn't mean anything.


问:
Javascript Print Multiple Webpages iFrame Content (Print All Button)
Using JavaScript, how do I create a print all button?

The 'Print All' button whenever clicked would iterate through an iFrame's different src's and print the content.

As a note, the iFrame is currently setup on a main webpage.  There are navigation buttons to change the content src of the iFrame.  This main webpage is set up to resemble navigating through slide content with navigation buttons.  The navigation buttons are really navigating to different webpages.

So, I'm guessing that the content would need to be appended to a document or arrayed so that the content could then be printed all at once with the 'Print All' button.

I was successful at printing a 'Current Slide' (or iFrame content) with the following code:

```<code>function PrintCurrentSlide()
{
    var el = document.getElementById('ifMain');
    el.contentWindow.focus();
    el.contentWindow.print();
    return;
}
</code>```

Now, I'm searching for an answer to navigate through the iFrame src's to print content with just one click.

答:
I came up with a way around it.
With this you get only one print dialogue box.

The aim is to get the contents of all the iframes  into the parent window by manipulating the DOM using javascript.
Here is the code:

```<code><script>

 pages =[] // initiate an empty list here

function printPage() {

var frames = document.getElementsByTagName('iframe');
// get all the iframes and loop over them
// then push their innerHTML into the list
for (var i = 0; i < frames.length; i++){
   pages.push(frames[i].contentWindow.document.body.innerHTML);
;
}
if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated iframes innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
window.print();
}
else {
// do nothing
}

}
</code>```

with this solution you even avoid the problem of the iframe being cut off if it exceeds one page.

Remember that in your parent page HTML you will have the code below to call the printPage function.

```<code><input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />
</code>```

Body:
Using JavaScript, how do I create a print all button?

The 'Print All' button whenever clicked would iterate through an iFrame's different src's and print the content.

As a note, the iFrame is currently setup on a main webpage.  There are navigation buttons to change the content src of the iFrame.  This main webpage is set up to resemble navigating through slide content with navigation buttons.  The navigation buttons are really navigating to different webpages.

So, I'm guessing that the content would need to be appended to a document or arrayed so that the content could then be printed all at once with the 'Print All' button.

I was successful at printing a 'Current Slide' (or iFrame content) with the following code:

function PrintCurrentSlide()
{
    var el = document.getElementById('ifMain');
    el.contentWindow.focus();
    el.contentWindow.print();
    return;
}

Now, I'm searching for an answer to navigate through the iFrame src's to print content with just one click.

Body:
I came up with a way around it.
With this you get only one print dialogue box.

The aim is to get the contents of all the iframes  into the parent window by manipulating the DOM using javascript.
Here is the code:

<script>

 pages =[] // initiate an empty list here

function printPage() {

var frames = document.getElementsByTagName('iframe');
// get all the iframes and loop over them
// then push their innerHTML into the list
for (var i = 0; i < frames.length; i++){
   pages.push(frames[i].contentWindow.document.body.innerHTML);
;
}
if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated iframes innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
window.print();
}
else {
// do nothing
}

}

with this solution you even avoid the problem of the iframe being cut off if it exceeds one page.

Remember that in your parent page HTML you will have the code below to call the printPage function.

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />


问:
R find intervals in data.table
i want to add a new column with intervals or breakpoints by group. As an an example:

This is my data.table:

```<code>x <- data.table(a = c(1:8,1:8), b = c(rep("A",8),rep("B",8)))
</code>```

I have already the breakpoint or rowindices:

```<code>pos <- data.table(b =  c("A","A","B","B"), bp = c(3,5,2,4))
</code>```

Here i can find the interval for group "A" with:

```<code>findInterval(1:nrow(x[b=="A"]), pos[b=="A"]$bp)
</code>```

How can i do this for each group. In this case "A" and "B"?

答:
Another option using rolling join in data.table:

```<code>pos[, ri := rowid(b)]
x[, intvl := fcoalesce(pos[x, on=.(b, bp=a), roll=Inf, ri], 0L)]
</code>```

output:

```<code>    a b intvl
 1: 1 A     0
 2: 2 A     0
 3: 3 A     1
 4: 4 A     1
 5: 5 A     2
 6: 6 A     2
 7: 7 A     2
 8: 8 A     2
 9: 1 B     0
10: 2 B     1
11: 3 B     1
12: 4 B     2
13: 5 B     2
14: 6 B     2
15: 7 B     2
16: 8 B     2
</code>```

Title: R find intervals in data.table

Body:
i want to add a new column with intervals or breakpoints by group. As an an example:

This is my data.table:

x <- data.table(a = c(1:8,1:8), b = c(rep("A",8),rep("B",8)))

I have already the breakpoint or rowindices:

pos <- data.table(b =  c("A","A","B","B"), bp = c(3,5,2,4))

Here i can find the interval for group "A" with:

findInterval(1:nrow(x[b=="A"]), pos[b=="A"]$bp)

How can i do this for each group. In this case "A" and "B"?

Body:
Another option using rolling join in data.table:

pos[, ri := rowid(b)]
x[, intvl := fcoalesce(pos[x, on=.(b, bp=a), roll=Inf, ri], 0L)]

output:

    a b intvl
 1: 1 A     0
 2: 2 A     0
 3: 3 A     1
 4: 4 A     1
 5: 5 A     2
 6: 6 A     2
 7: 7 A     2
 8: 8 A     2
 9: 1 B     0
10: 2 B     1
11: 3 B     1
12: 4 B     2
13: 5 B     2
14: 6 B     2
15: 7 B     2
16: 8 B     2


问:
ctags doesn't understand -e option (no exuberant tags option)
When I type ctags -e it returns an error saying it doesn't know that command line option. I thought it should know about exuberant tags because etags works on cli.

Also, I recieve the following error: ctags: unrecognized option --langdef=arc and I have the following in my ~/.ctags file:

```<code>--langdef=arc
--langmap=arc:.arc
--regex-arc=/^\(def ([a-zA-Z1-9_*\/<>-]+)/\1/
--regex-arc=/^\(= ([a-zA-Z1-9_*\/<>-]+)/\1/
--regex-scheme=/^\(xdef ([a-zA-Z1-9_*\/<>-]+)/\1/
</code>```

答:
I had the same issue, but my error occurred because I had installed emacs with flatpak which came bundled with its own version of ctags, distinct from the one I installed with my linux package manager.

In such case the solution is to either specify the ctags path in the emacs config or use the normal non flatpak version.

Body:
When I type ctags -e it returns an error saying it doesn't know that command line option. I thought it should know about exuberant tags because etags works on cli.

Also, I recieve the following error: ctags: unrecognized option --langdef=arc and I have the following in my ~/.ctags file:

--langdef=arc
--langmap=arc:.arc
--regex-arc=/^\(def ([a-zA-Z1-9_*\/<>-]+)/\1/
--regex-arc=/^\(= ([a-zA-Z1-9_*\/<>-]+)/\1/
--regex-scheme=/^\(xdef ([a-zA-Z1-9_*\/<>-]+)/\1/


问:
How to access vuex store from fetch or asyncData hook in NuxtJS?
I want to access vuex store specifically getters from fetch hook.

Here is my getters I'm loading using mapGetters inside order page

```<code>computed: {
    ...mapGetters("auth", ["authUser"])
  },
</code>```

Here is apollo call from fetch hook and I'm trying to provide authUser.id as a variable which is provided by authUser getter from vuex store.

```<code>async fetch() {
    console.log("fetch order is called");
    const orderInput = {
      userId: this.authUser.id,
      orderStatus: "PENDING"
    };

    const response = await this.$apollo.query({
      query: getOrdersByUserIdQuery,
      variables: { orderInput }
    });

    this.orders = response.data.getOrderByUserId.orders;
    console.log("getOrderResponse", response);
  },
</code>```

But, it fails to load the authUser from the store in initial page load.

I am curious to know If my steps are correct or not. If this is not correct what are the other alternatives that can I follow?

答:
use this.$store for (Nuxt >= 2.12).
you should already have a store :)</p>

Body:
I want to access vuex store specifically getters from fetch hook.

Here is my getters I'm loading using mapGetters inside order page

computed: {
    ...mapGetters("auth", ["authUser"])
  },

Here is apollo call from fetch hook and I'm trying to provide authUser.id as a variable which is provided by authUser getter from vuex store.

async fetch() {
    console.log("fetch order is called");
    const orderInput = {
      userId: this.authUser.id,
      orderStatus: "PENDING"
    };

    const response = await this.$apollo.query({
      query: getOrdersByUserIdQuery,
      variables: { orderInput }
    });

    this.orders = response.data.getOrderByUserId.orders;
    console.log("getOrderResponse", response);
  },

But, it fails to load the authUser from the store in initial page load.

I am curious to know If my steps are correct or not. If this is not correct what are the other alternatives that can I follow?


问:
WebSphere Portal 6.1 default theme deleted
I deleted the chosen default theme in WebSphere Portal 6.1 using the administration pages. Now the portal is themeless. More importantly, the theme selection page in the administration section can no longer be displayed.

How can I set the default theme "externally" (i.e. manually, without the administration pages)?

答:
Chrisr is right. Here is how to use xmlaccess in little more detail:

To generate a full export of your Portal's configuration, do the following:

Copy the file <Portal_home>/doc/xml-samples/Export.xml to <Portal_home>/bin.

Open a terminal or command window. Change directory (cd) to <Portal_home>/bin.

From the directory <Portal_home>/bin, run the following xmlaccess command all on one line:

xmlaccess -user <Portal_admin_user> -password <Portal_admin_password> -url :<port>/wps/config" rel="nofollow">http://<myhost>:<port>/wps/config -in Export.xml -out result.xml

(from: IBM How to generate a complete XMLAccess export of a Portal configuration)

You might encounter an error EJPXB0016E Connection refused. It is because either:

localhost cannot be resolved or

-url option was not supplied

If localhost cannot be resolved, open the following file:

```<code>../wp_profile/ConfigEngine/properties/wkplc_comp.properties
</code>```

and change XmlAccessHost=localhost to XmlAccessHost=hostname.compyname.com.

(from: IBM Configuration task fails during XMLAccess with 'EJPXB0016E Connection refused' error). I simply forgot the -url parameter and didn't have to change that value.

If everything goes well, you should have the result.xml file. Use xmlaccess again with the result.xml to configure the server with default theme deleted:

xmlaccess -user <Portal_admin_user> -password <Portal_admin_password> -url :<port>/wps/config" rel="nofollow">http://<myhost>:<port>/wps/config -in result.xml

Body:
Chrisr is right. Here is how to use xmlaccess in little more detail:

To generate a full export of your Portal's configuration, do the following:

Copy the file <Portal_home>/doc/xml-samples/Export.xml to <Portal_home>/bin.

Open a terminal or command window. Change directory (cd) to <Portal_home>/bin.

From the directory <Portal_home>/bin, run the following xmlaccess command all on one line:

xmlaccess -user <Portal_admin_user> -password <Portal_admin_password> -url http://<myhost>:<port>/wps/config -in Export.xml -out result.xml

(from: IBM How to generate a complete XMLAccess export of a Portal configuration)

You might encounter an error EJPXB0016E Connection refused. It is because either:

localhost cannot be resolved or

-url option was not supplied

If localhost cannot be resolved, open the following file:

../wp_profile/ConfigEngine/properties/wkplc_comp.properties

and change XmlAccessHost=localhost to XmlAccessHost=hostname.compyname.com.

(from: IBM Configuration task fails during XMLAccess with 'EJPXB0016E Connection refused' error). I simply forgot the -url parameter and didn't have to change that value.

If everything goes well, you should have the result.xml file. Use xmlaccess again with the result.xml to configure the server with default theme deleted:

xmlaccess -user <Portal_admin_user> -password <Portal_admin_password> -url http://<myhost>:<port>/wps/config -in result.xml


问:
How Can I Import From Outside a File?
im trying to import from a file called "data.json", however I am getting this error: Module not found: Can't resolve './src/data/data.json' in ...src/components/Table'
Anyone know how to help?

My code:

import {data} from "./src/data/data.json";

答:
if Table is folder and you are importing in a  file inside it then try this:

```<code>import * as data from "../../data/data.json";
</code>```

if Table is a js file then try this:

```<code>import * as data from "../../data/data.json";
</code>```

Title: How Can I Import From Outside a File?

Body:
if Table is folder and you are importing in a  file inside it then try this:

import * as data from "../../data/data.json";

if Table is a js file then try this:

import * as data from "../../data/data.json";