问:
Trying to put that i made in my Tkinter GUI directly into a file
```<code>from tkinter import *

root = Tk()'
root.geometry('500x500')
root.title("Auto Assign Widget")

cw=StringVar()
pp=StringVar()
mt=StringVar()
bdt=StringVar()

def printt():   #Print command
    cw1=cw.get()
    pp1=pp.get()
    mt1=mt.get()
    bdt1=bdt.get()
    print("M48")
    print(f"Cu, {cw1}")
    print(f"PP, {pp1}")
    print(f"Mat, {mt1}")
    print(f"Thk, {bdt1}")
    print("%")

def exitt():  #Defining the exit fucntion for the exit button command
    exit()

label_0=Label(root, text="Schmoll Auto Assign Widget", relief='solid')
label_0.place(x=200, y=150)

list1=['Qoz', 'Toz', 'Hoz', '1oz']
droplist=OptionMenu(root, cw, *list1)
cw.set("Copper Weight")
droplist.config(width=15)
droplist.place(x=80, y=240)

list2=['1x106', '1x1027', '1x1080', '1x1067']
droplist=OptionMenu(root, pp, *list2)
pp.set("Pre-Preg Style")
droplist.config(width=15)
droplist.place(x=80, y=280)

list3=['370HR', 'MEG6', 'R6202', 'FR408']
droplist=OptionMenu(root, mt, *list3)
mt.set("Material Type")
droplist.config(width=15)
droplist.place(x=80, y=320)

label_1=Label(root, text='Board Thickness')
label_1.place(x=80, y=360)
entry_1= Entry(root, textvar=bdt)
entry_1.place(x=240, y=360)

but_export = Button(root, text = 'Export', command=printt).place(x=150, y=450)
but_quit = Button(root, text='Quit', command=exitt).place(x=280, y=450)

root.mainloop()
</code>```

And now I would like to try and create another button that sets up a tool path to a directory so i can choose what file i would like to write the information to. Any ideas where i should start looking? I figure that i can do this in Tkinter pretty easy

with open('out.txt', 'w') as f:

print('Filename:', filename, file=f)

^ Thats kinda what i had in my but id like to assign it to a button command where maybe i would open the file and then do my GUI stuff, then have it write itself in. Thanks for all the help!

答:
Add this lines to your code :

1-import filedialog:

```<code>from tkinter import filedialog
</code>```

2-in function printt add :

```<code>text="M48\n"+(f"Cu, {cw1}\n")+(f"PP, {pp1}\n")+(f"Mat, {mt1}\n")+(f"Thk, {bdt1}")+"%"
return text
</code>```

3- Define new function for saving:

```<code>def file_save():
    text = printt()
    f = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))

    if f is None:
        return
    with open(f, 'r') as original: data = original.read()
    with open(f, 'w') as modified: modified.write(text+"\n" + data)
</code>```

4- create button for Save:

```<code>but_SaveAs = Button(root, text = 'Save as', command=file_save).place(x=50, y=450)
</code>```

Body:
from tkinter import *

root = Tk()'
root.geometry('500x500')
root.title("Auto Assign Widget")

cw=StringVar()
pp=StringVar()
mt=StringVar()
bdt=StringVar()

def printt():   #Print command
    cw1=cw.get()
    pp1=pp.get()
    mt1=mt.get()
    bdt1=bdt.get()
    print("M48")
    print(f"Cu, {cw1}")
    print(f"PP, {pp1}")
    print(f"Mat, {mt1}")
    print(f"Thk, {bdt1}")
    print("%")

def exitt():  #Defining the exit fucntion for the exit button command
    exit()

label_0=Label(root, text="Schmoll Auto Assign Widget", relief='solid')
label_0.place(x=200, y=150)

list1=['Qoz', 'Toz', 'Hoz', '1oz']
droplist=OptionMenu(root, cw, *list1)
cw.set("Copper Weight")
droplist.config(width=15)
droplist.place(x=80, y=240)

list2=['1x106', '1x1027', '1x1080', '1x1067']
droplist=OptionMenu(root, pp, *list2)
pp.set("Pre-Preg Style")
droplist.config(width=15)
droplist.place(x=80, y=280)

list3=['370HR', 'MEG6', 'R6202', 'FR408']
droplist=OptionMenu(root, mt, *list3)
mt.set("Material Type")
droplist.config(width=15)
droplist.place(x=80, y=320)

label_1=Label(root, text='Board Thickness')
label_1.place(x=80, y=360)
entry_1= Entry(root, textvar=bdt)
entry_1.place(x=240, y=360)

but_export = Button(root, text = 'Export', command=printt).place(x=150, y=450)
but_quit = Button(root, text='Quit', command=exitt).place(x=280, y=450)

root.mainloop()

And now I would like to try and create another button that sets up a tool path to a directory so i can choose what file i would like to write the information to. Any ideas where i should start looking? I figure that i can do this in Tkinter pretty easy

with open('out.txt', 'w') as f:

print('Filename:', filename, file=f)

^ Thats kinda what i had in my but id like to assign it to a button command where maybe i would open the file and then do my GUI stuff, then have it write itself in. Thanks for all the help!

Body:
Add this lines to your code :

1-import filedialog:

from tkinter import filedialog

2-in function printt add :

text="M48\n"+(f"Cu, {cw1}\n")+(f"PP, {pp1}\n")+(f"Mat, {mt1}\n")+(f"Thk, {bdt1}")+"%"
return text

3- Define new function for saving:

def file_save():
    text = printt()
    f = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))

    if f is None:
        return
    with open(f, 'r') as original: data = original.read()
    with open(f, 'w') as modified: modified.write(text+"\n" + data)

4- create button for Save:

but_SaveAs = Button(root, text = 'Save as', command=file_save).place(x=50, y=450)


来源: stackexchange

问:
Python flask_sqlalchemy: AttributeError: 'Table' object has no attribute 'added_by'
Here is my model class, which has definition of all database objects.
(I've imported db object from another package which is an instance of sqlAlchemy())

```<code>from datetime import datetime
from TasMar import  db, login_manager
from flask import  current_app
from flask_login import UserMixin

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class User(db.Model, UserMixin):
    __tablename__ = 'tm_user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20),unique=True, nullable=False)
    email = db.Column(db.String(120),unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password=  db.Column(db.String(120), nullable=False)

    #foreign keys accessing this table's primary keys
    added = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.added_by')
    assigned = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.assigned_to')

    def __repr__(self):
            return "User('{}','{}','{}')".format(self.username,self.email,self.image_file)

class Tasks(db.Model):
    __tablename__ = 'tm_task'
    task_id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('tm_task.task_id'),nullable=True)
    descr = db.Column(db.String(500), nullable=False)
    added_on = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    added_by = db.Column(db.Integer, db.ForeignKey('tm_user.id'),nullable=False)
    assigned_to = db.Column(db.Integer, db.ForeignKey('tm_user.id'),nullable=False)
    last_updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    remark = db.Column(db.Text)

    parent = db.relationship('Tasks', remote_side=[task_id]) #self referential
    status = db.Column(db.Integer, db.ForeignKey('tm_status.id'),nullable=False)
    type = db.Column(db.Integer, db.ForeignKey('tm_type.id'),nullable=False)
    urgency = db.Column(db.Integer, db.ForeignKey('tm_urgency.id'),nullable=False)

    def __repr__(self):
            return "Tasks('{}','{}','{}','{}')".format(self.descr,self.added_on,self.added_by,self.assigned_to)

class tm_status(db.Model):
    __tablename__ = 'tm_status'
    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.String(20),unique=True,nullable=False)
    status_f = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.status')

    def __repr__(self):
            return "tm_status('{}')".format(self.status)

class tm_type(db.Model):
    __tablename__ = 'tm_type'
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(20),unique=True,nullable=False)
    type_f = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.type')

    def __repr__(self):
            return "tm_type('{}')".format(self.type)

class tm_urgency(db.Model):
    __tablename__ = 'tm_urgency'
    id = db.Column(db.Integer, primary_key=True)
    urgency = db.Column(db.String(20),unique=True,nullable=False)
    urgency_f = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.urgency')

    def __repr__(self):
            return "tm_urgency('{}')".format(self.urgency)
</code>```

I use another class to create these objects and query data as following

```<code>from TasMar import db,create_app
from TasMar.models import User,Tasks,tm_status, tm_urgency,tm_type
app=create_app()
app.app_context().push()
#db.create_all()   #<<works perfectly but not below !
user = User.query.filter_by(email='dummy@email.com').first()
print(user)
</code>```

create_all() works fine and it creates all the schema objects with correct relationship, however querying the data gives error. (ie running above code gives error as below)
AttributeError: 'Table' object has no attribute 'added_by'
Why am I getting this error?

```<code>Traceback (most recent call last):
  File "F:\My Documents\Official\work\EclipseWorkspace\TaMar\setup_db.py", line 7, in <module>
    user = User.query.filter_by(email='dummy@email.com').first()
  File "F:\Installations\Anaconda\lib\site-packages\flask_sqlalchemy\__init__.py", line 517, in __get__
    mapper = orm.class_mapper(type)
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\base.py", line 421, in class_mapper
    mapper = _inspect_mapped_class(class_, configure=configure)
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\base.py", line 400, in _inspect_mapped_class
    mapper._configure_all()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\mapper.py", line 1268, in _configure_all
    configure_mappers()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\mapper.py", line 3013, in configure_mappers
    mapper._post_configure_properties()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\mapper.py", line 1811, in _post_configure_properties
    prop.init()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\interfaces.py", line 184, in init
    self.do_init()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\relationships.py", line 1655, in do_init
    self._process_dependent_arguments()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\relationships.py", line 1680, in _process_dependent_arguments
    setattr(self, attr, attr_value())
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\ext\declarative\clsregistry.py", line 281, in __call__
    x = eval(self.arg, globals(), self._dict)
  File "<string>", line 1, in <module>
AttributeError: 'Table' object has no attribute 'added_by'
</code>```

答:
I managed to solve this. Apparently I was mixing up class names and table names, here is the working updated code, look at the updated foreign key data for 'added_by' column.</p>

```<code>from datetime import datetime
from TasMar import  db, login_manager
from flask import  current_app
from flask_login import UserMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class User(db.Model, UserMixin):
    __tablename__ = 'tm_user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20),unique=True, nullable=False)
    email = db.Column(db.String(120),unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password=  db.Column(db.String(120), nullable=False)

    #foreign keys accessing this table's primary keys
    added_by = db.relationship('Tasks',backref='addedby', lazy=True, foreign_keys='Tasks.added_by')
    assigned_to = db.relationship('Tasks',backref='user', lazy=True, foreign_keys='Tasks.assigned_to')

    def __repr__(self):
            return "User('{}','{}','{}')".format(self.username,self.email,self.image_file)

class Tasks(db.Model):
    __tablename__ = 'tm_task'
    task_id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('tm_task.task_id'),nullable=True)
    descr = db.Column(db.String(500), nullable=False)
    added_on = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    assigned_to = db.Column(db.Integer, db.ForeignKey('tm_user.id'),nullable=False)
    added_by = db.Column(db.Integer, db.ForeignKey('tm_user.id'),nullable=False)
    target_date = db.Column(db.DateTime,nullable=True,default=None)
    last_updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    remark = db.Column(db.Text)
    #foreign keys accessing this table's primary keys
    parent = db.relationship('Tasks', remote_side=[task_id]) #self referential
    status = db.Column(db.Integer, db.ForeignKey('tm_status.id'),nullable=False)
    type = db.Column(db.Integer, db.ForeignKey('tm_type.id'),nullable=False)
    urgency = db.Column(db.Integer, db.ForeignKey('tm_urgency.id'),nullable=False)

    def __repr__(self):
            return "Tasks('{}','{}','{}','{}')".format(self.descr,self.added_on,self.added_by,self.assigned_to)

class tm_status(db.Model):
    __tablename__ = 'tm_status'
    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.String(20),unique=True,nullable=False)
    status_f = db.relationship('Tasks',backref='status_f', lazy=True, foreign_keys='Tasks.status')

    def __repr__(self):
            return "tm_status('{}')".format(self.status)

class tm_type(db.Model):
    __tablename__ = 'tm_type'
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(20),unique=True,nullable=False)
    type_f = db.relationship('Tasks',backref='type_f', lazy=True, foreign_keys='Tasks.type')

    def __repr__(self):
            return "tm_type('{}')".format(self.type)

class tm_urgency(db.Model):
    __tablename__ = 'tm_urgency'
    id = db.Column(db.Integer, primary_key=True)
    urgency = db.Column(db.String(20),unique=True,nullable=False)
    urgency_f = db.relationship('Tasks', backref='urgency_f', lazy=True, foreign_keys='Tasks.urgency')

    def __repr__(self):
            return "tm_urgency('{}')".format(self.urgency)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is my model class, which has definition of all database objects.
(I've imported db object from another package which is an instance of sqlAlchemy())

from datetime import datetime
from TasMar import  db, login_manager
from flask import  current_app
from flask_login import UserMixin

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class User(db.Model, UserMixin):
    __tablename__ = 'tm_user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20),unique=True, nullable=False)
    email = db.Column(db.String(120),unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password=  db.Column(db.String(120), nullable=False)

    #foreign keys accessing this table's primary keys
    added = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.added_by')
    assigned = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.assigned_to')

    def __repr__(self):
            return "User('{}','{}','{}')".format(self.username,self.email,self.image_file)

class Tasks(db.Model):
    __tablename__ = 'tm_task'
    task_id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('tm_task.task_id'),nullable=True)
    descr = db.Column(db.String(500), nullable=False)
    added_on = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    added_by = db.Column(db.Integer, db.ForeignKey('tm_user.id'),nullable=False)
    assigned_to = db.Column(db.Integer, db.ForeignKey('tm_user.id'),nullable=False)
    last_updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    remark = db.Column(db.Text)

    parent = db.relationship('Tasks', remote_side=[task_id]) #self referential
    status = db.Column(db.Integer, db.ForeignKey('tm_status.id'),nullable=False)
    type = db.Column(db.Integer, db.ForeignKey('tm_type.id'),nullable=False)
    urgency = db.Column(db.Integer, db.ForeignKey('tm_urgency.id'),nullable=False)

    def __repr__(self):
            return "Tasks('{}','{}','{}','{}')".format(self.descr,self.added_on,self.added_by,self.assigned_to)

class tm_status(db.Model):
    __tablename__ = 'tm_status'
    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.String(20),unique=True,nullable=False)
    status_f = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.status')

    def __repr__(self):
            return "tm_status('{}')".format(self.status)

class tm_type(db.Model):
    __tablename__ = 'tm_type'
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(20),unique=True,nullable=False)
    type_f = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.type')

    def __repr__(self):
            return "tm_type('{}')".format(self.type)

class tm_urgency(db.Model):
    __tablename__ = 'tm_urgency'
    id = db.Column(db.Integer, primary_key=True)
    urgency = db.Column(db.String(20),unique=True,nullable=False)
    urgency_f = db.relationship('Tasks', lazy=True, foreign_keys='tm_task.urgency')

    def __repr__(self):
            return "tm_urgency('{}')".format(self.urgency)

I use another class to create these objects and query data as following

from TasMar import db,create_app
from TasMar.models import User,Tasks,tm_status, tm_urgency,tm_type
app=create_app()
app.app_context().push()
#db.create_all()   #<<works perfectly but not below !
user = User.query.filter_by(email='dummy@email.com').first()
print(user)

create_all() works fine and it creates all the schema objects with correct relationship, however querying the data gives error. (ie running above code gives error as below)
AttributeError: 'Table' object has no attribute 'added_by'
Why am I getting this error?

Traceback (most recent call last):
  File "F:\My Documents\Official\work\EclipseWorkspace\TaMar\setup_db.py", line 7, in <module>
    user = User.query.filter_by(email='dummy@email.com').first()
  File "F:\Installations\Anaconda\lib\site-packages\flask_sqlalchemy\__init__.py", line 517, in __get__
    mapper = orm.class_mapper(type)
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\base.py", line 421, in class_mapper
    mapper = _inspect_mapped_class(class_, configure=configure)
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\base.py", line 400, in _inspect_mapped_class
    mapper._configure_all()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\mapper.py", line 1268, in _configure_all
    configure_mappers()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\mapper.py", line 3013, in configure_mappers
    mapper._post_configure_properties()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\mapper.py", line 1811, in _post_configure_properties
    prop.init()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\interfaces.py", line 184, in init
    self.do_init()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\relationships.py", line 1655, in do_init
    self._process_dependent_arguments()
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\orm\relationships.py", line 1680, in _process_dependent_arguments
    setattr(self, attr, attr_value())
  File "F:\Installations\Anaconda\lib\site-packages\sqlalchemy\ext\declarative\clsregistry.py", line 281, in __call__
    x = eval(self.arg, globals(), self._dict)
  File "<string>", line 1, in <module>
AttributeError: 'Table' object has no attribute 'added_by'

Body:
I managed to solve this. Apparently I was mixing up class names and table names, here is the working updated code, look at the updated foreign key data for 'added_by' column.

from datetime import datetime
from TasMar import  db, login_manager
from flask import  current_app
from flask_login import UserMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class User(db.Model, UserMixin):
    __tablename__ = 'tm_user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20),unique=True, nullable=False)
    email = db.Column(db.String(120),unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password=  db.Column(db.String(120), nullable=False)

    #foreign keys accessing this table's primary keys
    added_by = db.relationship('Tasks',backref='addedby', lazy=True, foreign_keys='Tasks.added_by')
    assigned_to = db.relationship('Tasks',backref='user', lazy=True, foreign_keys='Tasks.assigned_to')

    def __repr__(self):
            return "User('{}','{}','{}')".format(self.username,self.email,self.image_file)

class Tasks(db.Model):
    __tablename__ = 'tm_task'
    task_id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('tm_task.task_id'),nullable=True)
    descr = db.Column(db.String(500), nullable=False)
    added_on = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    assigned_to = db.Column(db.Integer, db.ForeignKey('tm_user.id'),nullable=False)
    added_by = db.Column(db.Integer, db.ForeignKey('tm_user.id'),nullable=False)
    target_date = db.Column(db.DateTime,nullable=True,default=None)
    last_updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    remark = db.Column(db.Text)
    #foreign keys accessing this table's primary keys
    parent = db.relationship('Tasks', remote_side=[task_id]) #self referential
    status = db.Column(db.Integer, db.ForeignKey('tm_status.id'),nullable=False)
    type = db.Column(db.Integer, db.ForeignKey('tm_type.id'),nullable=False)
    urgency = db.Column(db.Integer, db.ForeignKey('tm_urgency.id'),nullable=False)

    def __repr__(self):
            return "Tasks('{}','{}','{}','{}')".format(self.descr,self.added_on,self.added_by,self.assigned_to)

class tm_status(db.Model):
    __tablename__ = 'tm_status'
    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.String(20),unique=True,nullable=False)
    status_f = db.relationship('Tasks',backref='status_f', lazy=True, foreign_keys='Tasks.status')

    def __repr__(self):
            return "tm_status('{}')".format(self.status)

class tm_type(db.Model):
    __tablename__ = 'tm_type'
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(20),unique=True,nullable=False)
    type_f = db.relationship('Tasks',backref='type_f', lazy=True, foreign_keys='Tasks.type')

    def __repr__(self):
            return "tm_type('{}')".format(self.type)

class tm_urgency(db.Model):
    __tablename__ = 'tm_urgency'
    id = db.Column(db.Integer, primary_key=True)
    urgency = db.Column(db.String(20),unique=True,nullable=False)
    urgency_f = db.relationship('Tasks', backref='urgency_f', lazy=True, foreign_keys='Tasks.urgency')

    def __repr__(self):
            return "tm_urgency('{}')".format(self.urgency)


问:
slide toogle element, which was clicked
I have this simple html code:

```<code><ul>
   <li>
      <button onclick="test()">Button</button>
   </li>
   <li>
      <button onclick="test()">Button</button>
   </li>
   <li>
      <button onclick="test()">Button</button>
   </li>
</ul>
</code>```

and my javascript function:

```<code>function test() {
    // do something
}
</code>```

Now, if I clicked on a button I would like to remove the whole
 element of the button, which was clicked. Can you show me how? :/

With "remove" I mean

```<code>$(selector).toggle( "slide" );
</code>```

答:
It's generally not a good idea to use inline event handlers.

Instead, you can easily attach an event handler to all buttons in jQuery like:

$('ul button').click(function(){
  $(this).closest('li').toggle( "slide" );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
   <li><button>Button 1</button></li>
   <li><button>Button 2</button></li>
   <li><button>Button 3</button></li>
</ul></code>```

In case, you still want to use inline event handlers then you can simply pass this inside the handler like:

```<code><button onclick="test(this)">Button</button>
</code>```

and update your javascript function like:

```<code>function test(obj) {
    $(obj).closest('li').toggle("slide");
}
</code>```

Demo:

function test(obj) {
  $(obj).closest('li').toggle("slide");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li><button onclick="test(this)">Button 1</button></li>
  <li><button onclick="test(this)">Button 2</button></li>
  <li><button onclick="test(this)">Button 3</button></li>
</ul></code>```

Title: slide toogle element, which was clicked

Body:
I have this simple html code:

      <button onclick="test()">Button</button>

      <button onclick="test()">Button</button>

      <button onclick="test()">Button</button>

and my javascript function:

function test() {
    // do something
}

Now, if I clicked on a button I would like to remove the whole
 element of the button, which was clicked. Can you show me how? :/

With "remove" I mean

$(selector).toggle( "slide" );

Body:
It's generally not a good idea to use inline event handlers.

Instead, you can easily attach an event handler to all buttons in jQuery like:

$('ul button').click(function(){
  $(this).closest('li').toggle( "slide" );
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
   <li><button>Button 1</button></li>
   <li><button>Button 2</button></li>
   <li><button>Button 3</button></li>
</ul>

In case, you still want to use inline event handlers then you can simply pass this inside the handler like:

<button onclick="test(this)">Button</button>

and update your javascript function like:

function test(obj) {
    $(obj).closest('li').toggle("slide");
}

Demo:

function test(obj) {
  $(obj).closest('li').toggle("slide");
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li><button onclick="test(this)">Button 1</button></li>
  <li><button onclick="test(this)">Button 2</button></li>
  <li><button onclick="test(this)">Button 3</button></li>
</ul>


问:
How to use JDK profiling tools? Do I need to look at profiling tools (JConsole or VisualVM) until it shows some troubles?
I'm a newbie in profiling (but not in Java in general though), I interested Java or Kotlin profiling best practices.

I read multiple articles, watch some videos. I got profiling could be done either manually ( e.g. timestampEnd-timestampStart) or by using standart profiling tools (i'm writing here only that which included into JDK)

At the articles described how to use the tools, but never the best practice from end to end.

So my question is: yes, the tools are showing at real time what is happening. But do a programmer need to sit and watch to it for days to catch the moment when the program starts to mess up?
AFAIK the process should be opposite: the program is working well as long as it can but the moment of getting trouble should be caught and logged automatically, then alerted to programmers and analysed by them, isn't it? So how the real time profiling tools provides it? What is the best practice?

(My question looks general, may be after it's answered I'll learn more about profiling using the answer and be more specific)

答: This is pretty much what JFR was built to help solve. Having structured way to record various events and metrics from the JVM/JDK/Java Application in a repository that can be retrieved as self-describing binary files. So your production JVM can be run with a low-overhead configuration for JFR that contains detailed information about what happened in the application while you have some light-weight metrics with some monitors continually checking them and alerting you if something has happened. Then you'd just download the JFR profile and investigate what happened.</p>


问:
sort numbers numerically and strings alphabetically in an array perl
It's a very easy problem but can't get my way around it. I have an array

```<code>@arr = qw(txt text anothertext 38.09 100.87 0.876)
</code>```

How can I sort the numbers in the array numerically and the strings alphabetically. So the output would look like, either:

```<code>@sorted_as = (anothertext text txt 100.87 38.09 0.876)
</code>```

or,

```<code>@sorted_des = (txt text anothertext 100.87 38.09 0.876)
</code>```

Sorry if I duplicate any question but could not find a suitable answer.

答:
Divide into 2 lists, sort each individually, then combine back into 1 list.

```<code>use warnings;
use strict;

my @arr = qw(txt text anothertext 38.09 100.87 0.876);

my @word =         sort {$a cmp $b} grep {  /^[a-z]/i } @arr;
my @num  = reverse sort {$a <=> $b} grep { !/^[a-z]/i } @arr;
my @sorted_as = (@word, @num);
print "@sorted_as\n";
</code>```

Outputs:

```<code>anothertext text txt 100.87 38.09 0.876
</code>```

To get des also, add these lines:

```<code>@word = reverse @word;
my @sorted_des = (@word, @num);
print "@sorted_des\n";
</code>```

Body:
It's a very easy problem but can't get my way around it. I have an array

@arr = qw(txt text anothertext 38.09 100.87 0.876)

How can I sort the numbers in the array numerically and the strings alphabetically. So the output would look like, either:

@sorted_as = (anothertext text txt 100.87 38.09 0.876)

or,

@sorted_des = (txt text anothertext 100.87 38.09 0.876)

Sorry if I duplicate any question but could not find a suitable answer.

Body:
Divide into 2 lists, sort each individually, then combine back into 1 list.

use warnings;
use strict;

my @arr = qw(txt text anothertext 38.09 100.87 0.876);

my @word =         sort {$a cmp $b} grep {  /^[a-z]/i } @arr;
my @num  = reverse sort {$a <=> $b} grep { !/^[a-z]/i } @arr;
my @sorted_as = (@word, @num);
print "@sorted_as\n";

Outputs:

anothertext text txt 100.87 38.09 0.876

To get des also, add these lines:

@word = reverse @word;
my @sorted_des = (@word, @num);
print "@sorted_des\n";


问:
How to create a triangle in CSS3 using border-radius
I am using border-radius property to acheive rounded corners. But I am not sure how to get rounded corners of this shape. I tried giving same dimensions from either sides but they just dont give me the exact shape. Am I missing some CSS3 property here.

Just wondering if clip css property is the answer.

UPDATE:

http://jsfiddle.net/YWnzc/136/

答:
I used this for add triagle to link:</p>

```<code>.review-box_left-link:after{
    content: '';
    position: absolute;
    width: 19px;
    height: 19px;
    background: #2195DB;
    border-radius: 2px;
    transform: rotate(-45deg);
    background: linear-gradient(to right bottom, white 0%,white 50%,#2195DB 50%,#2195DB 50%,#2195DB 100%);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I used this for add triagle to link:

.review-box_left-link:after{
    content: '';
    position: absolute;
    width: 19px;
    height: 19px;
    background: #2195DB;
    border-radius: 2px;
    transform: rotate(-45deg);
    background: linear-gradient(to right bottom, white 0%,white 50%,#2195DB 50%,#2195DB 50%,#2195DB 100%);
}


问:
Laravel Left join not returing all records with where clause
I am not getting all records in left join.
my core query is like SELECT cities.*, states.name as state FROM cities LEFT JOIN states ON cities.states_id = states.id its working well

my laravel query is like this

```<code>      $all_city = DB::table('cities')
            ->leftjoin('states', 'cities.states_id', '=', 'states.id')
            ->where([['states.name', 'LIKE', '%'.$state.'%'], ['cities.name', 'like', '%'.$name.'%']])
            ->select('cities.*', 'states.name as state')
            ->orderBy($sort_field, $sort_type)
            ->paginate($pagination);
            return response()->json($all_city);
</code>```

Laravel returning only those records which are unique in both. And if i remove where clause from this then its working well.
Can someone suggest whats going wrong.

Thanks in advance!!

答:
You can simply do like this:</p>

```<code>$all_city = DB::table('cities')
                ->leftJoin('states', 'cities.states_id', '=', 'states.id')
                ->where('states.name', 'like', '%'.$state.'%')
                ->where('cities.name', 'like', '%'.$name.'%')
                ->select('cities.*', 'states.name as state')
                ->orderBy($sort_field, $sort_type)
                ->paginate($pagination);
       return response()->json($all_city);
</code>```

Body:
I am not getting all records in left join.
my core query is like SELECT cities.*, states.name as state FROM cities LEFT JOIN states ON cities.states_id = states.id its working well

my laravel query is like this

      $all_city = DB::table('cities')
            ->leftjoin('states', 'cities.states_id', '=', 'states.id')
            ->where([['states.name', 'LIKE', '%'.$state.'%'], ['cities.name', 'like', '%'.$name.'%']])
            ->select('cities.*', 'states.name as state')
            ->orderBy($sort_field, $sort_type)
            ->paginate($pagination);
            return response()->json($all_city);

Laravel returning only those records which are unique in both. And if i remove where clause from this then its working well.
Can someone suggest whats going wrong.

Thanks in advance!!

Body:
You can simply do like this:

$all_city = DB::table('cities')
                ->leftJoin('states', 'cities.states_id', '=', 'states.id')
                ->where('states.name', 'like', '%'.$state.'%')
                ->where('cities.name', 'like', '%'.$name.'%')
                ->select('cities.*', 'states.name as state')
                ->orderBy($sort_field, $sort_type)
                ->paginate($pagination);
       return response()->json($all_city);


问:
Kotlin coroutines - delay, how does it work?
I am quite used to using RX to handle concurrency, but, in my current job, we have a mix of AsyncTask, Executors + Handlers, Threads and some LiveData thrown in. Now we are thinking about moving towards using Kotlin Coroutines (and in fact have started using it in certain places in the codebase).

Therefore, I need to start wrapping my head around Coroutines, ideally drawing from my existing knowledge of concurrency tools to speed the process up.

I have tried following the Google codelab for them and whilst it's giving me a bit of understanding it's also raising lots of unanswered questions so I've tried getting my hands dirty by writing some code, debugging and looking at log outputs.

As I understand it, a coroutine is composed of 2 main building blocks; suspend functions which are where you do your work and coroutine contexts which is where you execute suspend functions such that you can have a handle on what dispatchers the coroutines will run on.

Here I have some code below, that behaves as I would expect. I have set up a coroutine context using Dispatchers.Main. So, as expected, when I launch the coroutine getResources it ends up blocking the UI thread for 5 seconds due to the Thread.sleep(5000):

```<code>private const val TAG = "Coroutines"

class MainActivity : AppCompatActivity(), CoroutineScope {
    override val coroutineContext: CoroutineContext = Job() + Dispatchers.Main

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        log("onCreate", "launching coroutine")
        launch {
            val resource = getResource()
            log("onCreate", "resource fetched: $resource")
            findViewById<TextView>(R.id.textView).text = resource.toString()
        }
        log("onCreate", "coroutine launched")
    }

    private suspend fun getResource() : Int {
        log("getResource", "about to sleep for 5000ms")
        Thread.sleep(5000)
        log("getResource", "finished fetching resource")
        return 1
    }

    private fun log(methodName: String, toLog: String) {
        Log.d(TAG,"$methodName: $toLog: ${Thread.currentThread().name}")
    }
}
</code>```

When I run this code, I see the following logs:

```<code>2020-05-28 11:42:44.364 9819-9819/? D/Coroutines: onCreate: launching coroutine: main
2020-05-28 11:42:44.376 9819-9819/? D/Coroutines: onCreate: coroutine launched: main
2020-05-28 11:42:44.469 9819-9819/? D/Coroutines: getResource: about to sleep for 5000ms: main
2020-05-28 11:42:49.471 9819-9819/com.example.coroutines D/Coroutines: getResource: finished fetching resource: main
2020-05-28 11:42:49.472 9819-9819/com.example.coroutines D/Coroutines: onCreate: resource fetched: 1: main
</code>```

As you can see, all the logs originated from the main thread, and there is a 5 second gap between the log before and after the Thread.sleep(5000). During that 5 second gap, the UI thread is blocked, I can confirm this by just looking at the emulator; it doens't render any UI because onCreate is blocked.

Now, if I update the getResources function to use the suspend fun delay(5000) instead of using Thread.sleep(5000) like so:

```<code>private suspend fun getResource() : Int {
    log("getResource", "about to sleep for 5000ms")
    delay(5000)
    log("getResource", "finished fetching resource")
    return 1
}
</code>```

Then what I end up seeing confuses me. I understand delay isn't the same as Thread.sleep, but because I am running it within the coroutine context which is backed by Dispatchers.Main, I expected to see the same result as using Thread.sleep.

Instead, what I see is the UI thread is not blocked while the 5 second delay is happening, and the logs look like:

```<code>2020-05-28 11:54:19.099 10038-10038/com.example.coroutines D/Coroutines: onCreate: launching coroutine: main
2020-05-28 11:54:19.111 10038-10038/com.example.coroutines D/Coroutines: onCreate: coroutine launched: main
2020-05-28 11:54:19.152 10038-10038/com.example.coroutines D/Coroutines: getResource: about to sleep for 5000ms: main
2020-05-28 11:54:24.167 10038-10038/com.example.coroutines D/Coroutines: getResource: finished fetching resource: main
2020-05-28 11:54:24.168 10038-10038/com.example.coroutines D/Coroutines: onCreate: resource fetched: 1: main
</code>```

I can see the UI thread is not blocked in this case as the UI renders whilst the delay is taking place and then the text view is updated after 5 seconds.

So, my question is, how does delay, in this case, not block the UI thread (even though the logs in my suspend function still indicate that the function is running on the main thread...)

答:
The best way to connect your existing intuition with the world of coroutines is to make this mental mapping: whereas in the classical world, the OS schedules threads to CPU cores (preemptively suspending them as needed), a dispatcher schedules coroutines to threads. Coroutines can't be preemptively suspended, this is where the cooperative nature of coroutine concurrency comes in.

With that in mind:

because I am running it within the coroutine context which is backed by Dispatchers.Main, I expected to see the same result as using Thread.sleep.

delay(delayTime) simply suspends the coroutine and schedules its resumption delayTime later. Therefore you should expect to see a very different result than with Thread.sleep, which never suspends a coroutine and keeps occupying its thread, a situation comparable to one where Thread.sleep() wouldn't allow the CPU core to run other stuff, but would busy-wait.

Body:
I am quite used to using RX to handle concurrency, but, in my current job, we have a mix of AsyncTask, Executors + Handlers, Threads and some LiveData thrown in. Now we are thinking about moving towards using Kotlin Coroutines (and in fact have started using it in certain places in the codebase).

Therefore, I need to start wrapping my head around Coroutines, ideally drawing from my existing knowledge of concurrency tools to speed the process up.

I have tried following the Google codelab for them and whilst it's giving me a bit of understanding it's also raising lots of unanswered questions so I've tried getting my hands dirty by writing some code, debugging and looking at log outputs.

As I understand it, a coroutine is composed of 2 main building blocks; suspend functions which are where you do your work and coroutine contexts which is where you execute suspend functions such that you can have a handle on what dispatchers the coroutines will run on.

Here I have some code below, that behaves as I would expect. I have set up a coroutine context using Dispatchers.Main. So, as expected, when I launch the coroutine getResources it ends up blocking the UI thread for 5 seconds due to the Thread.sleep(5000):

private const val TAG = "Coroutines"

class MainActivity : AppCompatActivity(), CoroutineScope {
    override val coroutineContext: CoroutineContext = Job() + Dispatchers.Main

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        log("onCreate", "launching coroutine")
        launch {
            val resource = getResource()
            log("onCreate", "resource fetched: $resource")
            findViewById<TextView>(R.id.textView).text = resource.toString()
        }
        log("onCreate", "coroutine launched")
    }

    private suspend fun getResource() : Int {
        log("getResource", "about to sleep for 5000ms")
        Thread.sleep(5000)
        log("getResource", "finished fetching resource")
        return 1
    }

    private fun log(methodName: String, toLog: String) {
        Log.d(TAG,"$methodName: $toLog: ${Thread.currentThread().name}")
    }
}

When I run this code, I see the following logs:

2020-05-28 11:42:44.364 9819-9819/? D/Coroutines: onCreate: launching coroutine: main
2020-05-28 11:42:44.376 9819-9819/? D/Coroutines: onCreate: coroutine launched: main
2020-05-28 11:42:44.469 9819-9819/? D/Coroutines: getResource: about to sleep for 5000ms: main
2020-05-28 11:42:49.471 9819-9819/com.example.coroutines D/Coroutines: getResource: finished fetching resource: main
2020-05-28 11:42:49.472 9819-9819/com.example.coroutines D/Coroutines: onCreate: resource fetched: 1: main

As you can see, all the logs originated from the main thread, and there is a 5 second gap between the log before and after the Thread.sleep(5000). During that 5 second gap, the UI thread is blocked, I can confirm this by just looking at the emulator; it doens't render any UI because onCreate is blocked.

Now, if I update the getResources function to use the suspend fun delay(5000) instead of using Thread.sleep(5000) like so:

private suspend fun getResource() : Int {
    log("getResource", "about to sleep for 5000ms")
    delay(5000)
    log("getResource", "finished fetching resource")
    return 1
}

Then what I end up seeing confuses me. I understand delay isn't the same as Thread.sleep, but because I am running it within the coroutine context which is backed by Dispatchers.Main, I expected to see the same result as using Thread.sleep.

Instead, what I see is the UI thread is not blocked while the 5 second delay is happening, and the logs look like:

2020-05-28 11:54:19.099 10038-10038/com.example.coroutines D/Coroutines: onCreate: launching coroutine: main
2020-05-28 11:54:19.111 10038-10038/com.example.coroutines D/Coroutines: onCreate: coroutine launched: main
2020-05-28 11:54:19.152 10038-10038/com.example.coroutines D/Coroutines: getResource: about to sleep for 5000ms: main
2020-05-28 11:54:24.167 10038-10038/com.example.coroutines D/Coroutines: getResource: finished fetching resource: main
2020-05-28 11:54:24.168 10038-10038/com.example.coroutines D/Coroutines: onCreate: resource fetched: 1: main

I can see the UI thread is not blocked in this case as the UI renders whilst the delay is taking place and then the text view is updated after 5 seconds.

So, my question is, how does delay, in this case, not block the UI thread (even though the logs in my suspend function still indicate that the function is running on the main thread...)


问:
Table Row onClick Overriding Checkbox
I'm having some issues with checkboxes in a table being "overridden" by the onClick attribute of the table row they are placed in.

I have a column with checkboxes as the leftmost column of a table, and I also have an onClick function defined for each table row. As a result, when I click any of the checkboxes, the onClick function of the table row triggers (though the checkbox is still clicked correctly).

Is there any way I can work around this? Having the table row's onClick only register for the other columns, for example? (I have no clue how the implementation of that would work, unfortunately, but that's the first solution I can think of.)

Thanks in advance!

答:
Take a look at event.stopPropagation()

event.stopPropagation

You'll want to call this in your checkbox click handler.

Title: Table Row onClick Overriding Checkbox


问:
How to avoid insert empty record in mongodb using mongoose
In my script i can create a new collection in mongodb but default one empty record is inserting so how to avoid that.

model.js:

```<code> /* model.js */
 'use strict';

 var mongoose = require('mongoose'),
 Schema = mongoose.Schema;

 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String
    }

   });
   return mongoose.model(suffix, addressSchema);
  }
  module.exports = dynamicModel;
</code>```

data.controller.js:

```<code>      var NewModel = require(path.resolve('./models/model.js'))(collectionName);
      NewModel.create({ category: 1, title: 'Minion' }, function(err, doc) {

      });
</code>```

after created new collection I am seeing like this:

```<code>  _id:ObjectId("5eceb362d538901accc0fefe");
  __v:0
</code>```

答:
You must define these attributes in your model.</p>

```<code> /* model.js */
 'use strict';

 var mongoose = require('mongoose'),
 Schema = mongoose.Schema;

 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String,
    },
    category: {
       type: Number,
    },
    title: {
       type: String,
    }

   });
   return mongoose.model(suffix, addressSchema);
  }
  module.exports = dynamicModel;
</code>```

Body:
In my script i can create a new collection in mongodb but default one empty record is inserting so how to avoid that.

model.js:

 /* model.js */
 'use strict';

 var mongoose = require('mongoose'),
 Schema = mongoose.Schema;

 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String
    }

   });
   return mongoose.model(suffix, addressSchema);
  }
  module.exports = dynamicModel;

data.controller.js:

      var NewModel = require(path.resolve('./models/model.js'))(collectionName);
      NewModel.create({ category: 1, title: 'Minion' }, function(err, doc) {

      });

after created new collection I am seeing like this:

  _id:ObjectId("5eceb362d538901accc0fefe");
  __v:0

Body:
You must define these attributes in your model.

 /* model.js */
 'use strict';

 var mongoose = require('mongoose'),
 Schema = mongoose.Schema;

 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String,
    },
    category: {
       type: Number,
    },
    title: {
       type: String,
    }

   });
   return mongoose.model(suffix, addressSchema);
  }
  module.exports = dynamicModel;


问:
Why create method is not called in django serializer?
I am want to be able to POST an entry to a ManyToManyField (ImageTag) one by one. I am using extra actions to make a nested endpoint under an Image.

I want to be able to POST an entry one POST at a time.

```<code>localhost:8000/my_app/images/IMG_123/image_tags/
</code>```

I want to override the create method on the Serializer to do this. But the problem is its not getting called. Why?

This is my source code:

```<code>#models.py
class ImageTag(models.Model):
    name = models.CharField()
    description = models.CharField()

class Image(models.Model):
    image_id = models.CharField(unique=True)
    image_tags = models.ManyToManyField(ImageTag, blank=True)
    ...

#serializers.py
class ImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Image
        fields = '__all__'

class ImageTagSerializer(serializers.ModelSerializer):
    image_tags = serializers.StringRelatedField(many=True)

    class Meta:
        model = Image
        fields = ('image_tags',)

    def to_internal_value(self, data):
        return data

    def create(self, validated_data):
        print("GOTHERE")
        print("VALI", validated_data)
        return validated_data

#views.py
class ImageExtraAction(viewsets.ModelViewSet):

    @action(detail=True, methods=['get', 'post', 'delete'])
    def image_tags(self, request, capture_id=None):
        capture = self.get_object()

        serializer = ImageTagSerializer(capture, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ImageTagViewSet(ImageExtraAction, viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer
    lookup_field = 'image_id'
    ...

#urls.py
router.register(r'images', ImageTagViewSet, basename='image')
</code>```

答:
The .create() method is not called because you are not creating, rather updating an instance. To create an instance use:

serializer = ImageTagSerializer(data=request.data)

Body:
I am want to be able to POST an entry to a ManyToManyField (ImageTag) one by one. I am using extra actions to make a nested endpoint under an Image.

I want to be able to POST an entry one POST at a time.

localhost:8000/my_app/images/IMG_123/image_tags/

I want to override the create method on the Serializer to do this. But the problem is its not getting called. Why?

This is my source code:

#models.py
class ImageTag(models.Model):
    name = models.CharField()
    description = models.CharField()

class Image(models.Model):
    image_id = models.CharField(unique=True)
    image_tags = models.ManyToManyField(ImageTag, blank=True)
    ...

#serializers.py
class ImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Image
        fields = '__all__'

class ImageTagSerializer(serializers.ModelSerializer):
    image_tags = serializers.StringRelatedField(many=True)

    class Meta:
        model = Image
        fields = ('image_tags',)

    def to_internal_value(self, data):
        return data

    def create(self, validated_data):
        print("GOTHERE")
        print("VALI", validated_data)
        return validated_data

#views.py
class ImageExtraAction(viewsets.ModelViewSet):

    @action(detail=True, methods=['get', 'post', 'delete'])
    def image_tags(self, request, capture_id=None):
        capture = self.get_object()

        serializer = ImageTagSerializer(capture, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ImageTagViewSet(ImageExtraAction, viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer
    lookup_field = 'image_id'
    ...

#urls.py
router.register(r'images', ImageTagViewSet, basename='image')


问:
Eclipse - How to know on which workspace I'm working without clicking/changing main view
Currently working on 4 different branches in a project.

For each branch there's a different workspace in Eclipse.

Problem is when I have multiple Eclipses open on different workspace I have a hard time distinguishing between them and understanding on which workspace currently viewing. (the paths are the same so the window name is the same on all branches

I can choose to do:

File->Switch Workspace->Other...

and it will shows the name of current workspace but im looking for a way for it to appear in my main display windows so i don't need to do this action 100 times a day

答:
you can use

Window -> Preferences -> General -> Workspace -> Workspace Name

or from Toolbar

File-> Switch Workspace -> Other

whatever the path is showing in that pop window, that is your current path.

as @samuel told , you can add

-showlocation

in your eclipse.ini also


问:
Can't access my website via domain name anymore
I have created a KeystoneJS-based website on Google Cloud Platform a couple of months ago.

IP-address (IPv4): 35.209.129.188:3000

Domain name: seebelarus.by

I didn't do anything, I didn't change any settings but now I can't reach my website via domain name. Only IP. Are there any ways to see what settings changed and how can I fix it?

Here's info about DNS:

答:
The cause of this issue is DNS misconfiguration while switching from registrar's DNS servers to Google Cloud DNS. There are no NS records for your domain seebelarus.by at the moment:

```<code>$ dig NS seebelarus.by @8.8.8.8

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> NS seebelarus.by @8.8.8.8
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 19578
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;seebelarus.by.                 IN      NS

;; Query time: 123 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Thu May 28 12:57:06 UTC 2020
;; MSG SIZE  rcvd: 42

$ dig NS seebelarus.by @8.8.4.4

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> NS seebelarus.by @8.8.4.4
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 12620
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;seebelarus.by.                 IN      NS

;; Query time: 85 msec
;; SERVER: 8.8.4.4#53(8.8.4.4)
;; WHEN: Thu May 28 12:57:15 UTC 2020
;; MSG SIZE  rcvd: 42

$ dig NS seebelarus.by @1.1.1.1

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> NS seebelarus.by @1.1.1.1
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 14617
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1452
;; QUESTION SECTION:
;seebelarus.by.                 IN      NS

;; Query time: 727 msec
;; SERVER: 1.1.1.1#53(1.1.1.1)
;; WHEN: Thu May 28 12:57:21 UTC 2020
;; MSG SIZE  rcvd: 42
</code>```

This domain was registered by Open Contact, Ltd:

```<code>$ whois seebelarus.by
Domain Name: seebelarus.by
Registrar: Open Contact, Ltd
Person: HIDDEN!
Email: HIDDEN! Details are available at http://www.cctld.by/whois/
Name Server: ns1.domain.by
Name Server: ns2.domain.by
Updated Date: 2019-11-07
Creation Date: 2015-05-03
Expiration Date: 2021-05-03

-------------------------------------------
Service provided by Reliable Software, Ltd.
</code>```

To solve your issue and switch to Google Cloud DNS you should follow steps below:

go to registrar's domain control panel and set as new DNS servers for your domain, for your domain you should replace:

```<code>ns1.domain.by
ns2.domain.by
</code>```

with:

```<code>ns-cloud-b1-googledomains.com
ns-cloud-b2-googledomains.com
ns-cloud-b3-googledomains.com
ns-cloud-b4-googledomains.com
</code>```

go to Google Cloud DNS and remove from zone NS records:

```<code>ns1.domain.by
ns2.domain.by
</code>```

you don't need them anymore, there should be only related to Google NS records:

```<code>ns-cloud-b1-googledomains.com
ns-cloud-b2-googledomains.com
ns-cloud-b3-googledomains.com
ns-cloud-b4-googledomains.com
</code>```

keep unchanged A record and it's a good time to add CNAME record for www.seebelarus.by.

More details you can find in the documentation Cloud DNS Quickstart.

After that, you should wait 24-48 hours for DNS propagation. You can check status of DNS propagation for your domain with online tools like dnsmap.io, https://dnschecker.org/ or similar.

UPDATE

DNS configuration looks good now:

```<code>$ whois seebelarus.by
Domain Name: seebelarus.by
Registrar: Open Contact, Ltd
Person: HIDDEN!
Email: HIDDEN! Details are available at http://www.cctld.by/whois/
Name Server: ns-cloud-b1.googledomains.com
Name Server: ns-cloud-b2.googledomains.com
Name Server: ns-cloud-b3.googledomains.com
Name Server: ns-cloud-b4.googledomains.com
Updated Date: 2020-05-29
Creation Date: 2015-05-03
Expiration Date: 2021-05-03
</code>```

and

```<code>$ dig NS seebelarus.by

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> NS seebelarus.by
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 56451
;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494

;; QUESTION SECTION:
;seebelarus.by.                 IN      NS

;; ANSWER SECTION:
seebelarus.by.          21599   IN      NS      ns-cloud-b1.googledomains.com.
seebelarus.by.          21599   IN      NS      ns-cloud-b2.googledomains.com.
seebelarus.by.          21599   IN      NS      ns-cloud-b3.googledomains.com.
seebelarus.by.          21599   IN      NS      ns-cloud-b4.googledomains.com.

;; Query time: 21 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Fri May 29 12:16:46 UTC 2020
;; MSG SIZE  rcvd: 163

$ host seebelarus.by
seebelarus.by has address 35.209.129.188
</code>```

Body:
The cause of this issue is DNS misconfiguration while switching from registrar's DNS servers to Google Cloud DNS. There are no NS records for your domain seebelarus.by at the moment:

$ dig NS seebelarus.by @8.8.8.8

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> NS seebelarus.by @8.8.8.8
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 19578
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;seebelarus.by.                 IN      NS

;; Query time: 123 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Thu May 28 12:57:06 UTC 2020
;; MSG SIZE  rcvd: 42

$ dig NS seebelarus.by @8.8.4.4

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> NS seebelarus.by @8.8.4.4
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 12620
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;seebelarus.by.                 IN      NS

;; Query time: 85 msec
;; SERVER: 8.8.4.4#53(8.8.4.4)
;; WHEN: Thu May 28 12:57:15 UTC 2020
;; MSG SIZE  rcvd: 42

$ dig NS seebelarus.by @1.1.1.1

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> NS seebelarus.by @1.1.1.1
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 14617
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1452
;; QUESTION SECTION:
;seebelarus.by.                 IN      NS

;; Query time: 727 msec
;; SERVER: 1.1.1.1#53(1.1.1.1)
;; WHEN: Thu May 28 12:57:21 UTC 2020
;; MSG SIZE  rcvd: 42

This domain was registered by Open Contact, Ltd:

$ whois seebelarus.by
Domain Name: seebelarus.by
Registrar: Open Contact, Ltd
Person: HIDDEN!
Email: HIDDEN! Details are available at http://www.cctld.by/whois/
Name Server: ns1.domain.by
Name Server: ns2.domain.by
Updated Date: 2019-11-07
Creation Date: 2015-05-03
Expiration Date: 2021-05-03

-------------------------------------------
Service provided by Reliable Software, Ltd.

To solve your issue and switch to Google Cloud DNS you should follow steps below:

go to registrar's domain control panel and set as new DNS servers for your domain, for your domain you should replace:

ns1.domain.by
ns2.domain.by

with:

ns-cloud-b1-googledomains.com
ns-cloud-b2-googledomains.com
ns-cloud-b3-googledomains.com
ns-cloud-b4-googledomains.com

go to Google Cloud DNS and remove from zone NS records:

ns1.domain.by
ns2.domain.by

you don't need them anymore, there should be only related to Google NS records:

ns-cloud-b1-googledomains.com
ns-cloud-b2-googledomains.com
ns-cloud-b3-googledomains.com
ns-cloud-b4-googledomains.com

keep unchanged A record and it's a good time to add CNAME record for www.seebelarus.by.

More details you can find in the documentation Cloud DNS Quickstart.

After that, you should wait 24-48 hours for DNS propagation. You can check status of DNS propagation for your domain with online tools like dnsmap.io, https://dnschecker.org/ or similar.

UPDATE

DNS configuration looks good now:

$ whois seebelarus.by
Domain Name: seebelarus.by
Registrar: Open Contact, Ltd
Person: HIDDEN!
Email: HIDDEN! Details are available at http://www.cctld.by/whois/
Name Server: ns-cloud-b1.googledomains.com
Name Server: ns-cloud-b2.googledomains.com
Name Server: ns-cloud-b3.googledomains.com
Name Server: ns-cloud-b4.googledomains.com
Updated Date: 2020-05-29
Creation Date: 2015-05-03
Expiration Date: 2021-05-03

and

$ dig NS seebelarus.by

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> NS seebelarus.by
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 56451
;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494

;; QUESTION SECTION:
;seebelarus.by.                 IN      NS

;; ANSWER SECTION:
seebelarus.by.          21599   IN      NS      ns-cloud-b1.googledomains.com.
seebelarus.by.          21599   IN      NS      ns-cloud-b2.googledomains.com.
seebelarus.by.          21599   IN      NS      ns-cloud-b3.googledomains.com.
seebelarus.by.          21599   IN      NS      ns-cloud-b4.googledomains.com.

;; Query time: 21 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Fri May 29 12:16:46 UTC 2020
;; MSG SIZE  rcvd: 163

$ host seebelarus.by
seebelarus.by has address 35.209.129.188


问:
Best method for storing a list of user IDs
I'm working on a PHP/MySQL rating system right now. For the user to be able to rate the user has to log in. Each user has a unique "UID". There will be multiple rating instances on the website (one for every game, in my case) and I need an efficient way of storing a list of UIDs in a MySQL row (one MySQL row in the ratings table for each instance of the rating system) to keep a tally of who has voted.

I've seen in other systems that the list is stored in a serialized PHP array. Every time a user votes, then serialized array has to extracted, unserialized, the new UID is inserted, the array is re-serialized, and the MySQL row is UPDATEd. Every time the page is loaded, that list has to once again be unserialized and checked to see if the user viewing the page has voted yet to make sure the user doesn't vote twice.

This seems kind of inefficient and cumbersome. Does MySQL have a built in list function to help this process be more efficient? Are there any more clever ways I could fix this problem?

I've considered one possible alternative which is forget the serializing and store the UIDs in a TEXT type field in the MySQL database. I would just append some non-numeric character after each UID (let's say a period [.]). To add a user entry I would just concatenate the UID onto the end of the TEXT field and then a period. When checking if the user has already voted I could just "SELECT * FROM table WHERE votes = '%$UID.%';". Would this work more efficiently or is there a more elegant way of getting the job done?

Follow-up post about the table structure... Efficient MySQL table structure for rating system

答:
In a normalized database, you should store it in a junction table:

```<code>UserRatings
-------------
RatingID int
UserID int
UserVote int
</code>```

I don't know what are your queries. Depending on the application, this might not have the acceptable performance. However, in either case, I suggest you go with the normalized approach, benchmark, and denormalize only if appropriate.

ContentLicense: CC BY-SA 2.5

Body:
In a normalized database, you should store it in a junction table:

UserRatings
-------------
RatingID int
UserID int
UserVote int

I don't know what are your queries. Depending on the application, this might not have the acceptable performance. However, in either case, I suggest you go with the normalized approach, benchmark, and denormalize only if appropriate.

OwnerDisplayName: Mehrdad Afshari


问:
How to access a nested dictionary which is a row in a Dataframe
I have a json file which looks like this

```<code>{
    "file": "name",
    "main": [{
                "question_no": "Q.1",
                "question": "what is ?",
                "answer": [{
                        "user": "John",
                        "comment": "It is defined as",
                        "value": {
                            "numbers": 2,
                            "submitted_value": [{
                                    "time": "4:06",
                                    "my_value": {
                                        "value1": 5,
                                        "value2": 10
                                    }
                                },
                                {
                                    "time": "13:47",
                                    "my_value": {
                                        "value1": 24,
                                        "value2": 30
                                    }
                                }
                            ]
                        }

                    },
                    {
                        "user": "Sam",
                        "comment": "as John said above it simply means",
                        "value": {
                            "numbers": 2,
                            "submitted_value": [{
                                    "time": "6:08",
                                    "my_value": {
                                        "value1": 9,
                                        "value2": 10
                                    }
                                },
                                {
                                    "time": "15:24",
                                    "my_value": {
                                        "value1": 54,
                                        "value2": 19
                                    }
                                }
                            ]
                        },
                        "closed": "no"
                    }
                ]

            }]
            }
</code>```

when I do data = pd.json_normalize(file["main"], record_path='answer', meta='question_no')
the result I get is

```<code>   user                             comment    question_no           value
0  John                    It is defined as       Q.1       [{'my_value': 5, 'value_2': 10}, {'my_value': 24, 'value_2': 30}]
1   Sam  as John said above it simply means       Q.1        [{'my_value': 9, 'value_2': 10}, {'my_value': 54, 'value_2': 19}]

</code>```

I need to access the values inside the list value and dictionary submitted_value to take the sum of my_value and value_2 as a new column. The actual file is a bit big so please consider the time taken to process the sum too.

desired result:

```<code>value1_sum      value2_sum     question_no              user      comment
 29                40                Q.1                    john    It is defined as
 63                29                Q.1                     Sam     as John said above it simply means
</code>```

the position of columns is not an issue.

答:
You can also do this:</p>

```<code>with open('1.json', 'r+') as f:
    data = json.load(f)

df = pd.json_normalize(data['main'],
                       record_path=['answer', 'value', 'submitted_value'],
                       meta=[['question_no'], ['answer', 'user'], ['answer', 'comment']])
df = df.groupby(by=['answer.user', 'question_no', 'answer.comment'], as_index=False).sum()
print(df)

  answer.user question_no                      answer.comment  my_value.value1  my_value.value2
0        John         Q.1                    It is defined as               29               40
1         Sam         Q.1  as John said above it simply means               63               29
</code>```

Body:
I have a json file which looks like this

{
    "file": "name",
    "main": [{
                "question_no": "Q.1",
                "question": "what is ?",
                "answer": [{
                        "user": "John",
                        "comment": "It is defined as",
                        "value": {
                            "numbers": 2,
                            "submitted_value": [{
                                    "time": "4:06",
                                    "my_value": {
                                        "value1": 5,
                                        "value2": 10
                                    }
                                },
                                {
                                    "time": "13:47",
                                    "my_value": {
                                        "value1": 24,
                                        "value2": 30
                                    }
                                }
                            ]
                        }

                    },
                    {
                        "user": "Sam",
                        "comment": "as John said above it simply means",
                        "value": {
                            "numbers": 2,
                            "submitted_value": [{
                                    "time": "6:08",
                                    "my_value": {
                                        "value1": 9,
                                        "value2": 10
                                    }
                                },
                                {
                                    "time": "15:24",
                                    "my_value": {
                                        "value1": 54,
                                        "value2": 19
                                    }
                                }
                            ]
                        },
                        "closed": "no"
                    }
                ]

            }]
            }

when I do data = pd.json_normalize(file["main"], record_path='answer', meta='question_no')
the result I get is

   user                             comment    question_no           value
0  John                    It is defined as       Q.1       [{'my_value': 5, 'value_2': 10}, {'my_value': 24, 'value_2': 30}]
1   Sam  as John said above it simply means       Q.1        [{'my_value': 9, 'value_2': 10}, {'my_value': 54, 'value_2': 19}]

I need to access the values inside the list value and dictionary submitted_value to take the sum of my_value and value_2 as a new column. The actual file is a bit big so please consider the time taken to process the sum too.

desired result:

value1_sum      value2_sum     question_no              user      comment
 29                40                Q.1                    john    It is defined as
 63                29                Q.1                     Sam     as John said above it simply means

the position of columns is not an issue.

Body:
You can also do this:

with open('1.json', 'r+') as f:
    data = json.load(f)

df = pd.json_normalize(data['main'],
                       record_path=['answer', 'value', 'submitted_value'],
                       meta=[['question_no'], ['answer', 'user'], ['answer', 'comment']])
df = df.groupby(by=['answer.user', 'question_no', 'answer.comment'], as_index=False).sum()
print(df)

  answer.user question_no                      answer.comment  my_value.value1  my_value.value2
0        John         Q.1                    It is defined as               29               40
1         Sam         Q.1  as John said above it simply means               63               29


问:
Nativescript Angular Android App forced light mode not working
My nativescript android app build using angular in API 29 doesn't get the styles.xml settings from values-v29 folder.

```<code><style name="AppThemeBase29" parent="AppThemeBase21">
    <item name="android:forceDarkAllowed">false</item>
</style>
</code>```

The values-v29 folder only contains the styles.xml file. I have set the forceDarkAllowed to false as shown above. Besides that, I have also set the theme dynamically in main.tns.ts file by:

```<code>Theme.setMode(Theme.Light);
</code>```

What am I missing? It works on IOS by changing the Info.plist file.

native script version: 6.5.0 angular version: 8

答:
For Android you might have to implement an application delegate, in your main.ts like below

```<code>import { android, on, launchEvent, ApplicationEventData } from '@nativescript/core/application';

// Typescript will require you to define those types
declare namespace androidx {
 export namespace appcompat {
  export namespace app {
   export const AppCompatDelegate: any;
  }
 }
}

if (android) {
 on(launchEvent, (args: ApplicationEventData) => {
  androidx.appcompat.app.AppCompatDelegate.setDefaultNightMode(androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO)
 });
}
</code>```

Body:
My nativescript android app build using angular in API 29 doesn't get the styles.xml settings from values-v29 folder.

The values-v29 folder only contains the styles.xml file. I have set the forceDarkAllowed to false as shown above. Besides that, I have also set the theme dynamically in main.tns.ts file by:

Theme.setMode(Theme.Light);

What am I missing? It works on IOS by changing the Info.plist file.

native script version: 6.5.0 angular version: 8

Body:
For Android you might have to implement an application delegate, in your main.ts like below

import { android, on, launchEvent, ApplicationEventData } from '@nativescript/core/application';

// Typescript will require you to define those types
declare namespace androidx {
 export namespace appcompat {
  export namespace app {
   export const AppCompatDelegate: any;
  }
 }
}

if (android) {
 on(launchEvent, (args: ApplicationEventData) => {
  androidx.appcompat.app.AppCompatDelegate.setDefaultNightMode(androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO)
 });
}


问:
Get data from a APIview in django rest framework
In my app I am trying to get the User data using a get request and it works in Postman but the problem occurs when I try to send the data from FrontEnd as we cannot send Body in get Request

URL:

```<code>           path('user/meta/', UserDetails.as_view()),
</code>```

Views.py

```<code>class UserDetails(APIView):
    """Get basic details of user"""

    def get(self, request):

        username = request.data["username"]
        if User.objects.filter(username = username).exists():

            user = User.objects.get(username = username)
            print(user)

            return Response({
                'verified': user.verified,
            })
        else:
            return Response("User doesn't exists", status=status.HTTP_400_BAD_REQUEST)
</code>```

How should I modify it such that I can get the data from get request?

答:
The good practice is to use query params in such case,

so your url will look like,

/user-info/?username=john

and you modify your code to,

```<code>    username= self.request.query_params.get('username')
</code>```

Body:
In my app I am trying to get the User data using a get request and it works in Postman but the problem occurs when I try to send the data from FrontEnd as we cannot send Body in get Request

URL:

           path('user/meta/', UserDetails.as_view()),

Views.py

class UserDetails(APIView):
    """Get basic details of user"""

    def get(self, request):

        username = request.data["username"]
        if User.objects.filter(username = username).exists():

            user = User.objects.get(username = username)
            print(user)

            return Response({
                'verified': user.verified,
            })
        else:
            return Response("User doesn't exists", status=status.HTTP_400_BAD_REQUEST)

How should I modify it such that I can get the data from get request?

Body:
The good practice is to use query params in such case,

so your url will look like,

/user-info/?username=john

and you modify your code to,

    username= self.request.query_params.get('username')


问:
JS how to stop previous while true when calling it again
I am trying to code a snake game using JS so I am rendering the game using SVG and moving the drawn parts using JS and loops

my problem is that I want to keep the rendering life "The while loop" but Every time I press a new key to change the snake direction The loop call stacks.

I tried looking for ways to stop that but I have no idea.

Does anyone have an idea on how to approach this problem?

const changeDirection = async key => {
  while(true){
    move(key);
    await sleep(10 * speed);
  }
}
```

答:
It might be easier, rather than keeping track of the interval IDs, to have a single interval which runs persistently. When changeDirection is called, just reassign a variable that's referenced inside the interval:

```<code>let key;
setInterval(() => {
  if (key) {
    move(key);
  }
}, 10 * speed);
const changeDirection = (keyParam) => {
  key = keyParam;
};
</code>```

Body:
It might be easier, rather than keeping track of the interval IDs, to have a single interval which runs persistently. When changeDirection is called, just reassign a variable that's referenced inside the interval:

let key;
setInterval(() => {
  if (key) {
    move(key);
  }
}, 10 * speed);
const changeDirection = (keyParam) => {
  key = keyParam;
};


问:
'OSError: [Errno 22] Invalid argument' when merging files using PyPDF2
I am simply trying to merge some PDF files using python, more specifically PyPDF2.
Easy enough, but for some reason I get an error, which simply do not understand.

While searching for a solution, I found, that other people had this problem as well. However, no for me satisfying solution was posted.

My code for merging the files:

```<code>from PyPDF2 import PdfFileMerger

def merge(self, work_files, destination_file):
    pdf_merger = PdfFileMerger()

    for pdf in work_files:
        pdf_merger.append(pdf)
        #also tried the following with the same results:
        #with open(pdf, 'wb') as fileobj:
            #merger.append(fileobj)

    with open(destination_file, 'wb') as fileobj:
      pdf_merger.write(fileobj)
</code>```

whereas work_files is a list of of paths to the pdfs to merge and destination_file is the file the merged pdf is supposed to be saved.

This produces the following error (full stacktrace provided as requested for):

```<code>Traceback (most recent call last):
      File "main.py", line 9, in <module>
         merger.append(fileobj)
      File "/home/user/.local/lib/python3.8/sitepackages/PyPDF2/merger.py",line 203,
      in append
         self.merge(len(self.pages), fileobj, bookmark, pages,
      import_bookmarks)
      File "/home/user/.local/lib/python3.8/site-
      packages/PyPDF2/merger.py",
      line 133, in merge
         pdfr = PdfFileReader(fileobj, strict=self.strict)
      File "/home/user/.local/lib/python3.8/site-
      packages/PyPDF2/pdf.py", line 1084,
      in __init__
         self.read(stream)
      File "/home/user/.local/lib/python3.8/site
      packages/PyPDF2/pdf.py", line 1689,
      in read
         stream.seek(-1, 2)
    OSError: [Errno 22] Invalid argument
</code>```

I have tried different ways of inputting the paths, I have tried relative paths, absolute paths as well as parsing them into another file, without any success.

I am using python 3.8 and working with Linux Ubuntu 20.04.

I would be thankful for any help.

答: After trying out other ways to merge the PDF files, I embarrassingly realized, that my test file were actually damaged file, which could not even be read by the system - problem solved.</p>

Body:
I am simply trying to merge some PDF files using python, more specifically PyPDF2.
Easy enough, but for some reason I get an error, which simply do not understand.

While searching for a solution, I found, that other people had this problem as well. However, no for me satisfying solution was posted.

My code for merging the files:

from PyPDF2 import PdfFileMerger

def merge(self, work_files, destination_file):
    pdf_merger = PdfFileMerger()

    for pdf in work_files:
        pdf_merger.append(pdf)
        #also tried the following with the same results:
        #with open(pdf, 'wb') as fileobj:
            #merger.append(fileobj)

    with open(destination_file, 'wb') as fileobj:
      pdf_merger.write(fileobj)

whereas work_files is a list of of paths to the pdfs to merge and destination_file is the file the merged pdf is supposed to be saved.

This produces the following error (full stacktrace provided as requested for):

Traceback (most recent call last):
      File "main.py", line 9, in <module>
         merger.append(fileobj)
      File "/home/user/.local/lib/python3.8/sitepackages/PyPDF2/merger.py",line 203,
      in append
         self.merge(len(self.pages), fileobj, bookmark, pages,
      import_bookmarks)
      File "/home/user/.local/lib/python3.8/site-
      packages/PyPDF2/merger.py",
      line 133, in merge
         pdfr = PdfFileReader(fileobj, strict=self.strict)
      File "/home/user/.local/lib/python3.8/site-
      packages/PyPDF2/pdf.py", line 1084,
      in __init__
         self.read(stream)
      File "/home/user/.local/lib/python3.8/site
      packages/PyPDF2/pdf.py", line 1689,
      in read
         stream.seek(-1, 2)
    OSError: [Errno 22] Invalid argument

I have tried different ways of inputting the paths, I have tried relative paths, absolute paths as well as parsing them into another file, without any success.

I am using python 3.8 and working with Linux Ubuntu 20.04.

I would be thankful for any help.


问:
Extract xml comments for public members only
I'm using xml comments to document public as well as internal and private members of my components. I would like to package the generated documentation xml files with component assemblies in order to enable "rich" (e.g. with method, exceptions and parameter descriptions) Visual Studio Intellisense with the end product. The problem with it is that the C# compiler creates documentation entries for everything (including internal classes, methods, private fields of internal enums etc.) and there seems to be no switch to "only public members" mode.

Now I don't want to go over 50 files with XX methods in each and remove all comments for private and internal members. Even if I did that, I probably would not have much success with auto-gen'd resource files, because these strongly-typed resource classes are automatically commented and non-public.

My question is: is there some option/flag that I'm overlooking? If no, are there some tools that could help separate public members from the rest (before I start to code one)?

答:
SandCastle Help File Builder has an option to recreate the xml files containing only the configured access modes for methods, properties, etc...

The only "downside" is that you'll have to generate a documentation.

EDIT

Since it's been a long time ago I forgot that I added a "component" to SHFB to generate the XML.

The good news is that this component is included in SHFB.

You have to add the "Intellisense Component" to the SHFB project. It will then generate the XML according to the configured SHFB project.

For more info: Intellisense Component in SHFB


问:
How to append custom string to error output and redirect it to a file
Given:

An ffprobe command that detects duration of an mp4 video files on a remote host.

Expected:

Output of ffprobe is prefixed with custom string and redirected to a text file.

Problem:

Sometimes due to network error, ffprobe fails with some error message. I would like to capture that error, prefix it with a custom string and send it to a text file.

Example:

This command appends "ABC=55" to out.txt where 55 is the discovered duration:

ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 https://example.com/video.mp4' | awk '{print "ABC="$1}' 2>&1 >> out.txt

However, if that same command encounters a network error, instead of writing "ABC=Error message here", it writes noting to text file and shows that message in console.

Question

How do I tweak this part to capture execution errors, prefix them with "ABC=" and send to out.txt?

| awk '{print "ABC="$1}' 2>&1 >> out.txt

Thank you.

EDIT

This solved the problem:

2>&1 | awk '{print "ABC="$0}'

答:
Give this a try:</p>

```<code>ffprobe cmd... 2>&1|awk '{print "ABC="$1}' >output.txt
</code>```

Body:
Give this a try:

ffprobe cmd... 2>&1|awk '{print "ABC="$1}' >output.txt


问:
view page source does not show page in nextjs
I shifted my project from CRA to nextjs because of SEO. On Sever side rendering, the client gets a complete HTML page as a response but in my case when i view page source of my landing page then i just see

.  On every pages, the page source shows the same.

Here is my code

pages/index.js

```<code>const IndexPage = () => {
  return (
    <Layout title="Home">
      <Home />
    </Layout>
  );
};

export default IndexPage;
</code>```

_app.js

```<code>class MyApp extends App {
  render() {
    const { Component, pageProps, apolloClient } = this.props;
    return (
        <ApolloProvider client={apolloClient}>
            <UserProvider>
              <RoleBasedComponent comp={Component} {...pageProps} />
            </UserProvider>
        </ApolloProvider>
    );
  }
}

export default withApollo(MyApp, {
  ssr: false,
});
</code>```

Is there something i did to violate the concept of server side rendering? Can anyone help me to understand why the HTML response is not viewable when looking at the view page source? I am totally confused and I afraid if google bot cannot index the page for SEO.

UPDATE

UserContext.js

```<code>const UserContext = createContext();

// Use this wherever current user data is required eg const {currentUser, loading} = useContext(UserContext)
const UserProvider = ({ children }) => {
  const token = cookies.getSession();
  return (
    <Query
      query={GET_CURRENT_USER}
      variables={{
        input: {
          token,
        },
      }}
    >
      {({ data, refetch, loading }) => {
        const currentUser = get(data, 'currentUser.data');

        if (loading) return <div />;

        return (
          <UserContext.Provider
            value={{ currentUser, loading, refetchUser: refetch }}
          >
            {children}
          </UserContext.Provider>
        );
      }}
    </Query>
  );
};
</code>```

答:
When rendering the component ``MyApp` you're passing:

```<code>{export default withApollo(MyApp, {
  ssr: false, // Should be true
});}
</code>```

I would give a read to this page - https://www.apollographql.com/docs/react/performance/server-side-rendering/

It can probably help.

Body:
I shifted my project from CRA to nextjs because of SEO. On Sever side rendering, the client gets a complete HTML page as a response but in my case when i view page source of my landing page then i just see

.  On every pages, the page source shows the same.

Here is my code

pages/index.js

const IndexPage = () => {
  return (
    <Layout title="Home">
      <Home />
    </Layout>
  );
};

export default IndexPage;

_app.js

class MyApp extends App {
  render() {
    const { Component, pageProps, apolloClient } = this.props;
    return (
        <ApolloProvider client={apolloClient}>
            <UserProvider>
              <RoleBasedComponent comp={Component} {...pageProps} />
            </UserProvider>
        </ApolloProvider>
    );
  }
}

export default withApollo(MyApp, {
  ssr: false,
});

Is there something i did to violate the concept of server side rendering? Can anyone help me to understand why the HTML response is not viewable when looking at the view page source? I am totally confused and I afraid if google bot cannot index the page for SEO.

UPDATE

UserContext.js

const UserContext = createContext();

// Use this wherever current user data is required eg const {currentUser, loading} = useContext(UserContext)
const UserProvider = ({ children }) => {
  const token = cookies.getSession();
  return (
    <Query
      query={GET_CURRENT_USER}
      variables={{
        input: {
          token,
        },
      }}
    >
      {({ data, refetch, loading }) => {
        const currentUser = get(data, 'currentUser.data');

        if (loading) return
;

        return (
          <UserContext.Provider
            value={{ currentUser, loading, refetchUser: refetch }}
          >
            {children}
          </UserContext.Provider>
        );
      }}
    </Query>
  );
};

Body:
When rendering the component ``MyApp` you're passing:

{export default withApollo(MyApp, {
  ssr: false, // Should be true
});}

I would give a read to this page - https://www.apollographql.com/docs/react/performance/server-side-rendering/

It can probably help.


问:
Porting Java `Character.isJavaIdentifierStart` to javascript/typescript
I'm working on porting an ANTLR4 grammar from java -> typescript.

Parts of the grammar are using java specific features:

```<code>JavaLetter
    :   [a-zA-Z$_] // these are the "java letters" below 0xFF
    |   // covers all characters above 0xFF which are not a surrogate
        ~[\u0000-\u00FF\uD800-\uDBFF]
        {Character.isJavaIdentifierStart(_input.LA(-1))}?
    ;
</code>```

I need to port Character.isJavaIdentifierStart method to javascript/typescript.

What's the easiest way to go about porting this?  I looked at the source implementation and providing a direct port seems like a lot of work (not even sure if its technically legal?).

I'm thinking that a simple regex could provide the same functionality (probably at a cost of performance)?

答:
You could just dump the character set, then put it into a suitable search structure for fast lookup (a search tree).

Here is the program for dumping:

import java.util.*;

/*
 * Print numeric ranges [LOW,HIGH] for the characters for which Java says that:
 * Character.isJavaIdentifierStart(i) is true ... if "--start" is passed to main.
 * Character.isJavaIdentifierPart(i)  is true ... if "--part"  is passed to main.
 * Those that are "part" but not "start" i.e. those that cannot be used as first chars if "--notstart"  is passed to main.
 */

class CharRangePrinter {

   // The "Range" expresses that a value may be
   // between [low,high]: low <= x <= high.
   // A range of length 1 is of course [limit,limit].

   private static class Range {

      final int low,high;

      public Range(int low,int high) {
         assert(low<=high);
         this.low = low;
         this.high = high;
      }

      public int length() {
         return high-low+1;
      }

      public String toString() {
         int length = high-low+1;
         return "[" + low + "," + high + "]";
      }
   }

   // simple option handling

   private final static String want_start_str    = "--start";
   private final static String want_part_str     = "--part";
   private final static String want_nostart_str  = "--nostart";

   // printing; 3 whitespaces at the start of each line
   // and a line contains max 78 characters (excluding the \n)

   private final static int indents     = 3;
   private final static int width_limit = 78;

   private static void printRanges(List<Range> ranges) {
      StringBuilder buf = new StringBuilder();
      for (int i=0;i<ranges.size();i++) {
         if (i>0) { buf.append(","); }
         String hold = buf.toString();
         Range range = ranges.get(i);
         buf.append(range);
         if (buf.length()+indents>width_limit) {
            outLine(hold);
            buf=new StringBuilder();
            buf.append(range);
         }
      }
      outLine(buf.toString());
   }

   private static void outLine(String x) {
      for (int i=0;i<indents;i++) { out(" "); }
      out(x);
      out("\n");
   }

   private static void out(String x) {
      System.out.print(x);
   }

   private static enum WantWhat {start,part,nostart};

   private static WantWhat handleArgv(String[] argv) {
      boolean good_argv = true;
      WantWhat want = null;
      if (argv.length!=1) {
         good_argv = false;
      }
      if (good_argv) {
         String arg = argv[0];
         if (want_start_str.equals(arg)) {
            want = WantWhat.start;
         }
         if (want_part_str.equals(arg)) {
            want = WantWhat.part;
         }
         if (want_nostart_str.equals(arg)) {
            want = WantWhat.nostart;
         }
         good_argv = (want != null);
      }
      if (!good_argv) {
         System.err.println("Pass " + want_start_str + " to print codepoints for Character.isJavaIdentifierStart()");
         System.err.println("Pass " + want_part_str  + " to print codepoints for Character.isJavaIdentifierPart()");
         System.err.println("Pass " + want_nostart_str  + " to print codepoints that can be 'part' but cannot be 'start'");
         System.exit(1);
      }
      return want;
   }

   public static void main(String[] argv) {

      WantWhat want = handleArgv(argv); assert(want!=null);

      int start=0;
      int end=-1;

      List<Range> ranges = new LinkedList<Range>();

      for (int i=0;i<0xFFFF;i++) {
         boolean is;
         switch (want) {
         case start:
            is = Character.isJavaIdentifierStart(i);
            break;
         case part:
            is = Character.isJavaIdentifierPart(i);
            break;
         case nostart:
            is = Character.isJavaIdentifierPart(i) && !Character.isJavaIdentifierStart(i);
            break;
         default:
            throw new IllegalStateException("WTF");
         }
         if (is) {
            if (end < 0) {
               // not currently doing a run; start run
               start = i;
               end   = i;
            }
            else {
               // extend current run
               end = i;
            }
         }
         else {
            if (end < 0) {
               // not currently doing a run; do nothing
            }
            else {
               // close current run
               int length = end-start+1;
               ranges.add(new Range(start,end));
               end=-1;
            }
         }
      }
      printRanges(ranges);
   }
}
```

Body:
I'm working on porting an ANTLR4 grammar from java -> typescript.

Parts of the grammar are using java specific features:

JavaLetter
    :   [a-zA-Z$_] // these are the "java letters" below 0xFF
    |   // covers all characters above 0xFF which are not a surrogate
        ~[\u0000-\u00FF\uD800-\uDBFF]
        {Character.isJavaIdentifierStart(_input.LA(-1))}?
    ;

I need to port Character.isJavaIdentifierStart method to javascript/typescript.

What's the easiest way to go about porting this?  I looked at the source implementation and providing a direct port seems like a lot of work (not even sure if its technically legal?).

I'm thinking that a simple regex could provide the same functionality (probably at a cost of performance)?