问:
Importing openCV in python idle error: shared object file
I have been trying to use the cv2 library in python (in IDLE on raspberry pi 3) but I can't manage to import it successfully.

when I type import cv2, I get this:

```<code>Traceback (most recent call last):
File "/home/pi/Desktop/python/test.py", line 2, in <module>
from .cv2 import *
ImportError: libjasper .so.1: cannot open shared object file: No such file or directory
</code>```

I have used the terminal to update, upgrade, and install opencv along with pretty much every other thing I could find relating to opencv or lib. I currently can import cv2 in the terminal but not in IDLE. What do I need to do to be able to import the cv2 library? Thanks in advance.

答:
Recommended way of installing opencv on linux as given by opencv docs "https://docs.opencv.org/4.2.0/d2/de6/tutorial_py_setup_in_ubuntu.html" for python3 is:

```<code>sudo apt install python3-opencv
</code>```

for python2:

```<code>sudo apt install python-opencv
</code>```

On Raspberry pi you may occasionally need to run:

```<code>sudo apt update --fix-missing
</code>```

It will auto-install all the dependencies.

Body:
I have been trying to use the cv2 library in python (in IDLE on raspberry pi 3) but I can't manage to import it successfully.

when I type import cv2, I get this:

Traceback (most recent call last):
File "/home/pi/Desktop/python/test.py", line 2, in <module>
from .cv2 import *
ImportError: libjasper .so.1: cannot open shared object file: No such file or directory

I have used the terminal to update, upgrade, and install opencv along with pretty much every other thing I could find relating to opencv or lib. I currently can import cv2 in the terminal but not in IDLE. What do I need to do to be able to import the cv2 library? Thanks in advance.

Body:
Recommended way of installing opencv on linux as given by opencv docs "https://docs.opencv.org/4.2.0/d2/de6/tutorial_py_setup_in_ubuntu.html" for python3 is:

sudo apt install python3-opencv

for python2:

sudo apt install python-opencv

On Raspberry pi you may occasionally need to run:

sudo apt update --fix-missing

It will auto-install all the dependencies.


来源: stackexchange

问:
Does GraphQL Query Analysis only refer to Queries?
GraphQL related resources explain how query analysis can be done to protect the GraphQL endpoint. Some of the approaches which are being used are query depth analysis, query complexity analysis, etc. The question that I have is, does Query Analysis only refer to Queries? What about Mutations and Subscriptions? Or are all 3 (Query, Mutation, Subscription) included when we talk about query analysis?

答:
Apollo Tracing is one of the Query Analysis Tools and based on what I have used it in graphql-java , it can be used on all Query , Mutation and Subscription. So , I believe the term Query Analysis can apply to all of them.

After all , all of them are handled in a pretty much the same way internally inside a GraphQL engine as defined by the spec. In the Execution Operation section, you can see both Query and Mutation has the same execution logic.The only differences are that Query is allow to execute in parallel while mutation can only execute in serial.

Then in the subscription response stream section ,it mentions :

The ExecuteSubscriptionEvent() algorithm is intentionally similar to
  ExecuteQuery() since this is how each event result is produced.

which mean at the end, its execution logic is the same as Query.

ContentLicense: CC BY-SA 4.0


问:
Is DI the only solution to Singleton and/or static objects?
I have been told that Singletons are hard to test.

http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/

http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/

I have been told that Static methods/objects are no good either.

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

So basically the only solution appears to be dependency injection.

But ... I really can't get used to DI, take this example:

In my framework I have a class that manages SQL. This class (and many other of my framework) uses a singleton Logger to logs message (and many other helpers).

With DI my code would turn to:

```<code>global $logger; //> consider i have been instanciated it at the start of my fw

$query = new PreparedQuery($logger);
$query->prepare() etc.
</code>```

Now that doesn't seem too bad. But consider a page that needs many queries I believe it's pretty redundant to have to write everytime $logger in the constructor, especially if you consider if PreparedQuery needed many other dependencies in the constructor.

The only solution to avoid singleton that I have found is to use a method (or just a simple function) in the main application that stores every references to this helper objects (Service Locator/Container) but this doens't solve the problem of hiding the dependencies

So in your experience other than DI what is a good pattern to use?

Solution:

For everyone interesetd the creator of PHPunit explains how to solve the Singleton problem (and how to solve static methods testing problem with PHP 5.3)

(singleton) http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html

(static) http://sebastian-bergmann.de/archives/883-Stubbing-and-Mocking-Static-Methods.html

Pretty interesting read if you ask me.

答: Logging is usually the example where static singletons are OK. You don't need to mock your logging anyway, do you?

ContentLicense: CC BY-SA 3.0

Body:
I have been told that Singletons are hard to test.

http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/

http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/

I have been told that Static methods/objects are no good either.

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

So basically the only solution appears to be dependency injection.

But ... I really can't get used to DI, take this example:

In my framework I have a class that manages SQL. This class (and many other of my framework) uses a singleton Logger to logs message (and many other helpers).

With DI my code would turn to:

global $logger; //> consider i have been instanciated it at the start of my fw

$query = new PreparedQuery($logger);
$query->prepare() etc.

Now that doesn't seem too bad. But consider a page that needs many queries I believe it's pretty redundant to have to write everytime $logger in the constructor, especially if you consider if PreparedQuery needed many other dependencies in the constructor.

The only solution to avoid singleton that I have found is to use a method (or just a simple function) in the main application that stores every references to this helper objects (Service Locator/Container) but this doens't solve the problem of hiding the dependencies

So in your experience other than DI what is a good pattern to use?

Solution:

For everyone interesetd the creator of PHPunit explains how to solve the Singleton problem (and how to solve static methods testing problem with PHP 5.3)

(singleton) http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html

(static) http://sebastian-bergmann.de/archives/883-Stubbing-and-Mocking-Static-Methods.html

Pretty interesting read if you ask me.


问:
how to remove white lines from geom_tile (heat map) using ggplot2
I am having trouble removing the white lines between tiles in my heat map. Below is my code and picture. Has anyone encountered this before?

```<code>t <- ggplot(Drug_heatmap_df_final,
   aes(x=reorder(Drug,Total_Deaths), y=Start_Date, fill=Total_Deaths)) +
   geom_tile() +
   labs(title="Heatmap of Total Deaths per month by Drug", x="Drug", y="Month") +
   theme(plot.title = element_text(hjust=.5)) +
   scale_y_date(date_breaks="1 year" , labels = date_format("%b-%Y")) +
   theme(axis.text.x = element_text(size=13))

plot(t)
</code>```

答: So I struggled with this same problem, unable to make my offending axis (a 24 hour period) discrete. In the end I realised that where I had plotted tiles every 2 minutes (1/30 of an hour), my csv data file had rounded the points up to 0.03 intervals, leaving gaps in between tiles, hence the white lines. I simply changed the number of decimal places in the excel sheet from 2 to many, giving 0.03333333 intervals and the white lines are gone. Horray! my heatmap before vs after</p>

Body:
I am having trouble removing the white lines between tiles in my heat map. Below is my code and picture. Has anyone encountered this before?

t <- ggplot(Drug_heatmap_df_final,
   aes(x=reorder(Drug,Total_Deaths), y=Start_Date, fill=Total_Deaths)) +
   geom_tile() +
   labs(title="Heatmap of Total Deaths per month by Drug", x="Drug", y="Month") +
   theme(plot.title = element_text(hjust=.5)) +
   scale_y_date(date_breaks="1 year" , labels = date_format("%b-%Y")) +
   theme(axis.text.x = element_text(size=13))

plot(t)


问:
Increase in number and show that number in entry box
I created global variable name count </p>

```<code>import tkinter as tk
from tkinter import ttk
import os
from csv import DictWriter, DictReader

data_label_frame=tk.LabelFrame()
data_label_frame.pack()

LARGE_FONT = ('Verdana' , 16,'bold')
global count
count=0
class sea_of_btc(tk.Tk):
    def __init__(self , *args , **kwargs):

        tk.Tk.__init__(self, *args , **kwargs)
        container = tk.Frame(self)
        container.pack(side = "top" , fill = "both" , expand = True)

        container.grid_rowconfigure(0 , weight =1 )
        container.grid_columnconfigure(0 , weight =1)
        self.config(background='#FAEBEF')
        self.frames = {}

        for F in (start_page , page_one ):
            frame = F(container , self)
            self.frames [F] = frame
            frame.grid (row = 0 , column = 0 , sticky= "nsew")
        self.show_frame(start_page)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        return frame

class start_page(tk.Frame):
    def __init__(self , parent , controller ):
        tk.Frame.__init__(self, parent)
</code>```

<p>Here now I want that whenever register_func will be called there will be increase in number count and after that whenever I open the frame it show me that number in entry box and user can not change that number means that it just work for the serial number to show in entry box    </p>

```<code>class page_one (tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        registration_number = tk.Label(data_label_frame, text = 'Registration No :', font = LARGE_FONT)
        registration_number.grid(row=0,column=0,padx=5  , pady=5 , sticky =tk.W )

        registration_number_var=tk.StringVar()
        registration_number_entry = ttk.Entry(data_label_frame,width = 5, font=LARGE_FONT ,textvariable=registration_number_var,
                                              )

        registration_number_entry.grid(row =1, column =0,padx=10,pady=10 , ipady=5 , sticky=tk.E)

        def register_fucn():
            count += 1
            with open('new.csv', 'a', newline='') as data_file:
                dict_writer = DictWriter(data_file, fieldnames=['Registration No',
                                                               ])
        registar_btn = ttk.Button(data_label_frame , text ='Registar' ,command= register_fucn)
        registar_btn.grid(row=2 , column=1, sticky =tk.E , padx=10 , pady=10,ipady=5)
</code>```

答:
Follow these steps to make the user unable to change the number in the Entry widget while increasing the number each time, when the Button is pressed.

Globalize the variable storing the number you want to show, inside the function.

Change the state of the Entry widget to NORMAL after globalizing the variable.

Increase the variable as much you want.

Then insert the variable inside the Entry widget.

Finally, change the state of the Entry widget to DISABLED.

Like I have done in this Example:

```<code>import tkinter as tk

var = 10

def func(en):
    global var

    en.configure(state=tk.NORMAL)

    en.delete(0, tk.END)
    var = var + 1
    en.insert(0, var)
    en.configure(state=tk.DISABLED)

root = tk.Tk()

e = tk.Entry(root)
e.pack()

b = tk.Button(root, text='Click', command=lambda: func(e))
b.pack()

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

Body:
I created global variable name count

import tkinter as tk
from tkinter import ttk
import os
from csv import DictWriter, DictReader

data_label_frame=tk.LabelFrame()
data_label_frame.pack()

LARGE_FONT = ('Verdana' , 16,'bold')
global count
count=0
class sea_of_btc(tk.Tk):
    def __init__(self , *args , **kwargs):

        tk.Tk.__init__(self, *args , **kwargs)
        container = tk.Frame(self)
        container.pack(side = "top" , fill = "both" , expand = True)

        container.grid_rowconfigure(0 , weight =1 )
        container.grid_columnconfigure(0 , weight =1)
        self.config(background='#FAEBEF')
        self.frames = {}

        for F in (start_page , page_one ):
            frame = F(container , self)
            self.frames [F] = frame
            frame.grid (row = 0 , column = 0 , sticky= "nsew")
        self.show_frame(start_page)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        return frame

class start_page(tk.Frame):
    def __init__(self , parent , controller ):
        tk.Frame.__init__(self, parent)

Here now I want that whenever register_func will be called there will be increase in number count and after that whenever I open the frame it show me that number in entry box and user can not change that number means that it just work for the serial number to show in entry box

class page_one (tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        registration_number = tk.Label(data_label_frame, text = 'Registration No :', font = LARGE_FONT)
        registration_number.grid(row=0,column=0,padx=5  , pady=5 , sticky =tk.W )

        registration_number_var=tk.StringVar()
        registration_number_entry = ttk.Entry(data_label_frame,width = 5, font=LARGE_FONT ,textvariable=registration_number_var,
                                              )

        registration_number_entry.grid(row =1, column =0,padx=10,pady=10 , ipady=5 , sticky=tk.E)

        def register_fucn():
            count += 1
            with open('new.csv', 'a', newline='') as data_file:
                dict_writer = DictWriter(data_file, fieldnames=['Registration No',
                                                               ])
        registar_btn = ttk.Button(data_label_frame , text ='Registar' ,command= register_fucn)
        registar_btn.grid(row=2 , column=1, sticky =tk.E , padx=10 , pady=10,ipady=5)

Body:
Follow these steps to make the user unable to change the number in the Entry widget while increasing the number each time, when the Button is pressed.

Globalize the variable storing the number you want to show, inside the function.

Change the state of the Entry widget to NORMAL after globalizing the variable.

Increase the variable as much you want.

Then insert the variable inside the Entry widget.

Finally, change the state of the Entry widget to DISABLED.

Like I have done in this Example:

import tkinter as tk

var = 10

def func(en):
    global var

    en.configure(state=tk.NORMAL)

    en.delete(0, tk.END)
    var = var + 1
    en.insert(0, var)
    en.configure(state=tk.DISABLED)

root = tk.Tk()

e = tk.Entry(root)
e.pack()

b = tk.Button(root, text='Click', command=lambda: func(e))
b.pack()

root.mainloop()


问:
keep audio pitch constant in javafx video player on changing speed
I have developed a video player using javafx but when I increase the rate of the player i.e the speed of the player using mediaPlayer.setRate(1.5) method, the speed of the video is increased, but the audio sounds like a chipmunk.

I need to implement functionality like with youtube where if we increase the speed, it doesn't sound like a chipmunk.

Please help me - what can I do to achieve this?

What java api, class or 3rd party library should I use in my program in order to modify the audio pitch whilst running the video.

答:
Got solution

Use VLCJ : http://capricasoftware.co.uk/projects/vlcj

VLCJ is a java wrapper framework that uses native vlc libraries.

They have very nice documentation and examples on Github.

It also supports JavaFx.

Github link :

VlcJ : https://github.com/caprica

VlcJ - JavaFx : https://github.com/caprica/vlcj-javafx


问:
Value Error : Only 2 class/es in training fold, but 1 in overall dataset. This is not supported for decision_function with imbalanced folds
I am learning machine learning and creating my first model on #mnist data set.

Can anyone help me over here? I have tried Stratified Fold, kfold and other methods to resolve this issue.

Pandas Version '0.25.1', Python Version 3.7, using Anaconda Distribution.

```<code>from  sklearn.model_selection import train_test_split
train_set ,test_set = train_test_split(mnist,test_size = 0.2, random_state = 29)
from sklearn.linear_model import SGDClassifier
sgd_clf = SGDClassifier(random_state=29)
sgd_clf.fit(X_train,y_train_5)

X_train, y_train = train_set.drop('label',axis = 1), train_set[['label']]
X_test, y_test = test_set.drop('label',axis = 1),test_set[['label']]

y_train_5 = (y_train == 5) #True for all 5's and false otherwise
y_test_5 = (y_train == 5)

from sklearn.model_selection import cross_val_predict

print(X_train.shape)
print(y_train_5.shape)
cross_val_predict(sgd_clf, X_train, y_train_5, cv=3, method="decision_function")
</code>```

Last line of the code block gives an error:

```<code>RuntimeWarning: Number of classes in training fold (2) does not match total number of classes (1). Results may not be appropriate for your use case. To fix this, use a cross-validation technique resulting in properly stratified folds
  RuntimeWarning)
ValueError                                Traceback (most recent call last)
<ipython-input-39-da1ad024473a> in <module>
      3 print(X_train.shape)
      4 print(y_train_5.shape)
----> 5 cross_val_predict(sgd_clf, X_train, y_train_5, cv=3, method="decision_function")

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in cross_val_predict(estimator, X, y, groups, cv, n_jobs, verbose, fit_params, pre_dispatch, method)
    787     prediction_blocks = parallel(delayed(_fit_and_predict)(
    788         clone(estimator), X, y, train, test, verbose, fit_params, method)
--> 789         for train, test in cv.split(X, y, groups))
    790
    791     # Concatenate the predictions

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self, iterable)
    919             # remaining jobs.
    920             self._iterating = False
--> 921             if self.dispatch_one_batch(iterator):
    922                 self._iterating = self._original_iterator is not None
    923

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in dispatch_one_batch(self, iterator)
    757                 return False
    758             else:
--> 759                 self._dispatch(tasks)
    760                 return True
    761

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in _dispatch(self, batch)
    714         with self._lock:
    715             job_idx = len(self._jobs)
--> 716             job = self._backend.apply_async(batch, callback=cb)
    717             # A job can complete so quickly than its callback is
    718             # called before we get here, causing self._jobs to

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\_parallel_backends.py in apply_async(self, func, callback)
    180     def apply_async(self, func, callback=None):
    181         """Schedule a func to be run"""
--> 182         result = ImmediateResult(func)
    183         if callback:
    184             callback(result)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\_parallel_backends.py in __init__(self, batch)
    547         # Don't delay the application, to avoid keeping the input
    548         # arguments in memory
--> 549         self.results = batch()
    550
    551     def get(self):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self)
    223         with parallel_backend(self._backend, n_jobs=self._n_jobs):
    224             return [func(*args, **kwargs)
--> 225                     for func, args, kwargs in self.items]
    226
    227     def __len__(self):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in <listcomp>(.0)
    223         with parallel_backend(self._backend, n_jobs=self._n_jobs):
    224             return [func(*args, **kwargs)
--> 225                     for func, args, kwargs in self.items]
    226
    227     def __len__(self):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in _fit_and_predict(estimator, X, y, train, test, verbose, fit_params, method)
    887             n_classes = len(set(y)) if y.ndim == 1 else y.shape[1]
    888             predictions = _enforce_prediction_order(
--> 889                 estimator.classes_, predictions, n_classes, method)
    890     return predictions, test
    891

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in _enforce_prediction_order(classes, predictions, n_classes, method)
    933                                  'is not supported for decision_function '
    934                                  'with imbalanced folds. {}'.format(
--> 935                                     len(classes), n_classes, recommendation))
    936
    937         float_min = np.finfo(predictions.dtype).min

ValueError: Only 2 class/es in training fold, but 1 in overall dataset. This is not supported for decision_function with imbalanced folds. To fix this, use a cross-validation technique resulting in properly stratified folds
</code>```

答:
I ran through a similar problem and on further investigation found a warning message with the error log-

DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().

There are two ways to solve this:

Use the hint in the warning message and change your code as:

```<code>cross_val_predict(sgd_clf, X_train, y_train_5.values.ravel(), cv=3,
method="decision_function")
</code>```

refer - answere here

Also, using the hint from - A column-vector y was passed when a 1d array was expected.; I released my mistake and did the following:

Even in your error log- Number of classes in training fold (2) does not match total number of classes (1)

I assume y_train_5 here is a DataFrame, (probably you are working your way through Aurelien's publication)

The expected type for y_train_5 is an array-type object (meaning the shaoe to be (n,) or one-dimensional), but DataFrame is 2-dimensional, in your case (n,1).

All you need to do is pass the Series object for your column vector as-

y_train_5.iloc[:,0] (I prefer this)

y_train_5.{COLUMN_NAME} (another variant)

Try running below in your console.

```<code>> y_train_5.iloc[:,0].shape
(n,)
</code>```

```<code>cross_val_predict(sgd_clf, X_train, y_train_5.iloc[:,0], cv=3,
method="decision_function")

</code>```

Body:
I am learning machine learning and creating my first model on #mnist data set.

Can anyone help me over here? I have tried Stratified Fold, kfold and other methods to resolve this issue.

Pandas Version '0.25.1', Python Version 3.7, using Anaconda Distribution.

from  sklearn.model_selection import train_test_split
train_set ,test_set = train_test_split(mnist,test_size = 0.2, random_state = 29)
from sklearn.linear_model import SGDClassifier
sgd_clf = SGDClassifier(random_state=29)
sgd_clf.fit(X_train,y_train_5)

X_train, y_train = train_set.drop('label',axis = 1), train_set[['label']]
X_test, y_test = test_set.drop('label',axis = 1),test_set[['label']]

y_train_5 = (y_train == 5) #True for all 5's and false otherwise
y_test_5 = (y_train == 5)

from sklearn.model_selection import cross_val_predict

print(X_train.shape)
print(y_train_5.shape)
cross_val_predict(sgd_clf, X_train, y_train_5, cv=3, method="decision_function")

Last line of the code block gives an error:

RuntimeWarning: Number of classes in training fold (2) does not match total number of classes (1). Results may not be appropriate for your use case. To fix this, use a cross-validation technique resulting in properly stratified folds
  RuntimeWarning)
ValueError                                Traceback (most recent call last)
<ipython-input-39-da1ad024473a> in <module>
      3 print(X_train.shape)
      4 print(y_train_5.shape)
----> 5 cross_val_predict(sgd_clf, X_train, y_train_5, cv=3, method="decision_function")

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in cross_val_predict(estimator, X, y, groups, cv, n_jobs, verbose, fit_params, pre_dispatch, method)
    787     prediction_blocks = parallel(delayed(_fit_and_predict)(
    788         clone(estimator), X, y, train, test, verbose, fit_params, method)
--> 789         for train, test in cv.split(X, y, groups))
    790
    791     # Concatenate the predictions

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self, iterable)
    919             # remaining jobs.
    920             self._iterating = False
--> 921             if self.dispatch_one_batch(iterator):
    922                 self._iterating = self._original_iterator is not None
    923

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in dispatch_one_batch(self, iterator)
    757                 return False
    758             else:
--> 759                 self._dispatch(tasks)
    760                 return True
    761

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in _dispatch(self, batch)
    714         with self._lock:
    715             job_idx = len(self._jobs)
--> 716             job = self._backend.apply_async(batch, callback=cb)
    717             # A job can complete so quickly than its callback is
    718             # called before we get here, causing self._jobs to

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\_parallel_backends.py in apply_async(self, func, callback)
    180     def apply_async(self, func, callback=None):
    181         """Schedule a func to be run"""
--> 182         result = ImmediateResult(func)
    183         if callback:
    184             callback(result)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\_parallel_backends.py in __init__(self, batch)
    547         # Don't delay the application, to avoid keeping the input
    548         # arguments in memory
--> 549         self.results = batch()
    550
    551     def get(self):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self)
    223         with parallel_backend(self._backend, n_jobs=self._n_jobs):
    224             return [func(*args, **kwargs)
--> 225                     for func, args, kwargs in self.items]
    226
    227     def __len__(self):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in <listcomp>(.0)
    223         with parallel_backend(self._backend, n_jobs=self._n_jobs):
    224             return [func(*args, **kwargs)
--> 225                     for func, args, kwargs in self.items]
    226
    227     def __len__(self):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in _fit_and_predict(estimator, X, y, train, test, verbose, fit_params, method)
    887             n_classes = len(set(y)) if y.ndim == 1 else y.shape[1]
    888             predictions = _enforce_prediction_order(
--> 889                 estimator.classes_, predictions, n_classes, method)
    890     return predictions, test
    891

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in _enforce_prediction_order(classes, predictions, n_classes, method)
    933                                  'is not supported for decision_function '
    934                                  'with imbalanced folds. {}'.format(
--> 935                                     len(classes), n_classes, recommendation))
    936
    937         float_min = np.finfo(predictions.dtype).min

ValueError: Only 2 class/es in training fold, but 1 in overall dataset. This is not supported for decision_function with imbalanced folds. To fix this, use a cross-validation technique resulting in properly stratified folds

Body:
I ran through a similar problem and on further investigation found a warning message with the error log-

DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().

There are two ways to solve this:

Use the hint in the warning message and change your code as:

cross_val_predict(sgd_clf, X_train, y_train_5.values.ravel(), cv=3,
method="decision_function")

refer - answere here

Also, using the hint from - A column-vector y was passed when a 1d array was expected.; I released my mistake and did the following:

Even in your error log- Number of classes in training fold (2) does not match total number of classes (1)

I assume y_train_5 here is a DataFrame, (probably you are working your way through Aurelien's publication)

The expected type for y_train_5 is an array-type object (meaning the shaoe to be (n,) or one-dimensional), but DataFrame is 2-dimensional, in your case (n,1).

All you need to do is pass the Series object for your column vector as-

y_train_5.iloc[:,0] (I prefer this)

y_train_5.{COLUMN_NAME} (another variant)

Try running below in your console.

> y_train_5.iloc[:,0].shape
(n,)

cross_val_predict(sgd_clf, X_train, y_train_5.iloc[:,0], cv=3,
method="decision_function")


问:
Why doesn't my bubble sort work properly?
I have been trying to create a BubbleSort to sort out an array. The array's name is UserNameArray, the format of the array is . The  is a six-character string of numerals and the  is a string. An example would look like this: 123456James.

My program sorts out some of the data but it fails to run a couple of times to really sort out all the data.

```<code>UserNameArray = ["234511Jack","734636Dan","237894Daniel", "124119James", "000001Test","999999Donald"]
def BubbleSort():
    for i in range(0,len(UserNameArray)-1):
        for j in range(0,i):
            UserID = int(UserNameArray[j][0:5])
            UserIDNext = int(UserNameArray[j+1][0:5])
            print(i,j)
            print(UserID,UserIDNext)
            if UserIDNext < UserID:
                store = UserNameArray[j]
                UserNameArray[j] = UserNameArray[j+1]
                UserNameArray[j+1] = store
            print(UserNameArray)
BubbleSort()
</code>```

Thank you.

答:
Try this:

UserNameArray = ["234511Jack","734636Dan","237894Daniel", "124119James", "000001Test","999999Donald"]
def BubbleSort():
    for i in range(len(UserNameArray)-1,0,-1): // you use wrong direction here
        for j in range(0,i):
            UserID = int(UserNameArray[j][0:5])
            UserIDNext = int(UserNameArray[j+1][0:5])
            print(i,j)
            print(UserID,UserIDNext)
            if UserIDNext < UserID:
                store = UserNameArray[j]
                UserNameArray[j] = UserNameArray[j+1]
                UserNameArray[j+1] = store
            print(UserNameArray)
BubbleSort()
```

Body:
I have been trying to create a BubbleSort to sort out an array. The array's name is UserNameArray, the format of the array is . The  is a six-character string of numerals and the  is a string. An example would look like this: 123456James.

My program sorts out some of the data but it fails to run a couple of times to really sort out all the data.

UserNameArray = ["234511Jack","734636Dan","237894Daniel", "124119James", "000001Test","999999Donald"]
def BubbleSort():
    for i in range(0,len(UserNameArray)-1):
        for j in range(0,i):
            UserID = int(UserNameArray[j][0:5])
            UserIDNext = int(UserNameArray[j+1][0:5])
            print(i,j)
            print(UserID,UserIDNext)
            if UserIDNext < UserID:
                store = UserNameArray[j]
                UserNameArray[j] = UserNameArray[j+1]
                UserNameArray[j+1] = store
            print(UserNameArray)
BubbleSort()

Thank you.


问:
SELECT all (but one column as null)
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

```<code>SELECT *, id AS (SELECT '') FROM my_table WHERE 1
</code>```

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

答:
You can do something like:

```<code>SELECT null AS id, t.* FROM my_table t
</code>```

But it will include the id twice. You'll need to specify the columns if you only want the null id column.

```<code>SELECT null As id, t.col1, t.col2 FROM my_table t
</code>```

Title: SELECT all (but one column as null)

Body:
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

SELECT *, id AS (SELECT '') FROM my_table WHERE 1

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

Body:
You can do something like:

SELECT null AS id, t.* FROM my_table t

But it will include the id twice. You'll need to specify the columns if you only want the null id column.

SELECT null As id, t.col1, t.col2 FROM my_table t


问:
How to display full file path in JTree?
I would like to print out the whole file path when I click a file in the File tree. At the moment when I click a file it prints out only the path name from the line System.out.println( tree.getLastSelectedPathComponent());

I tried doing File file = (File) tree.getPath(); to get the full path but I get the error (java.lang.ClassCastException: javax.swing.tree.DefaultMutableTreeNode cannot be cast to java.io.File).

My full code is below

```<code>import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class NewerFileTree extends JPanel implements Runnable {

    protected static final String File = null;
    private DefaultMutableTreeNode root;
    private DefaultTreeModel treeModel;
    private JTree tree;

    public void run() {
        JFrame frame = new JFrame("File Browser");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        File fileRoot = new File("C://");
        root = new DefaultMutableTreeNode(new FileNode(fileRoot));
        treeModel = new DefaultTreeModel(root);

        tree = new JTree(treeModel);
        tree.setShowsRootHandles(true);
        JScrollPane scrollPane = new JScrollPane(tree);

        tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent event) {
                File file = (File) tree.getLastSelectedPathComponent();
                System.out.println(tree.getLastSelectedPathComponent());
            }
        });

        frame.add(scrollPane);
        frame.setLocationByPlatform(true);
        frame.setSize(640, 480);
        frame.setVisible(true);

        CreateChildNodes ccn
                = new CreateChildNodes(fileRoot, root);
        new Thread(ccn).start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new NewerFileTree());
    }

    public class CreateChildNodes implements Runnable {

        private DefaultMutableTreeNode root;
        private File fileRoot;

        public CreateChildNodes(File fileRoot,
                DefaultMutableTreeNode root) {
            this.fileRoot = fileRoot;
            this.root = root;
        }

        public void run() {
            createChildren(fileRoot, root);
        }

        private void createChildren(File fileRoot,
                DefaultMutableTreeNode node) {
            File[] files = fileRoot.listFiles();
            if (files == null) {
                return;
            }

            for (File file : files) {
                DefaultMutableTreeNode childNode
                        = new DefaultMutableTreeNode(new FileNode(file));

                DefaultMutableTreeNode childNodes = new DefaultMutableTreeNode("hello");
                node.add(childNode);
                if (file.isDirectory()) {
                    createChildren(file, childNode);
                }
            }
        }
    }

    public class FileNode {

        private File file;

        public FileNode(File file) {
            this.file = file;
        }

        @Override
        public String toString() {
            String name = file.getName();
            if (name.equals("")) {
                return file.getAbsolutePath();
            } else {
                return name;
            }
        }
    }
}```

I am working in the `tree.addTreeSelectionListener`.

```

答:
The fix seen here is in two parts, marked by /* new */. Basically:

Change the FileNode to add a getFile() method (not strictly necessary, but good encapsulation).

Get the FileNode from the DefaultMutableTreeNode, then get the File from that.

```<code>import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class NewerFileTree extends JPanel implements Runnable {

    protected static final String File = null;
    private DefaultMutableTreeNode root;
    private DefaultTreeModel treeModel;
    private JTree tree;

    public void run() {
        JFrame frame = new JFrame("File Browser");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        File fileRoot = new File("C://");
        root = new DefaultMutableTreeNode(new FileNode(fileRoot));
        treeModel = new DefaultTreeModel(root);

        tree = new JTree(treeModel);
        tree.setShowsRootHandles(true);
        JScrollPane scrollPane = new JScrollPane(tree);

        tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent event) {
                /* new */
                DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)
                        tree.getLastSelectedPathComponent();
                FileNode fileNode = (FileNode)dmtn.getUserObject();
                File file = fileNode.getFile();
                System.out.println(file);
            }
        });

        frame.add(scrollPane);
        frame.setLocationByPlatform(true);
        frame.setSize(640, 480);
        frame.setVisible(true);

        CreateChildNodes ccn = new CreateChildNodes(fileRoot, root);
        new Thread(ccn).start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new NewerFileTree());
    }

    public class CreateChildNodes implements Runnable {

        private DefaultMutableTreeNode root;
        private File fileRoot;

        public CreateChildNodes(File fileRoot,
                DefaultMutableTreeNode root) {
            this.fileRoot = fileRoot;
            this.root = root;
        }

        public void run() {
            createChildren(fileRoot, root);
        }

        private void createChildren(File fileRoot,
                DefaultMutableTreeNode node) {
            File[] files = fileRoot.listFiles();
            if (files == null) {
                return;
            }

            for (File file : files) {
                DefaultMutableTreeNode childNode
                        = new DefaultMutableTreeNode(new FileNode(file));

                DefaultMutableTreeNode childNodes = new DefaultMutableTreeNode("hello");
                node.add(childNode);
                if (file.isDirectory()) {
                    createChildren(file, childNode);
                }
            }
        }
    }

    public class FileNode {

        private File file;

        public FileNode(File file) {
            this.file = file;
        }

        /* new */
        public File getFile() {
            return file;
        }

        @Override
        public String toString() {
            String name = file.getName();
            if (name.equals("")) {
                return file.getAbsolutePath();
            } else {
                return name;
            }
        }
    }
}
</code>```

Title: How to display full file path in JTree?

Body:
I would like to print out the whole file path when I click a file in the File tree. At the moment when I click a file it prints out only the path name from the line System.out.println( tree.getLastSelectedPathComponent());

I tried doing File file = (File) tree.getPath(); to get the full path but I get the error (java.lang.ClassCastException: javax.swing.tree.DefaultMutableTreeNode cannot be cast to java.io.File).

My full code is below

import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class NewerFileTree extends JPanel implements Runnable {

    protected static final String File = null;
    private DefaultMutableTreeNode root;
    private DefaultTreeModel treeModel;
    private JTree tree;

    public void run() {
        JFrame frame = new JFrame("File Browser");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        File fileRoot = new File("C://");
        root = new DefaultMutableTreeNode(new FileNode(fileRoot));
        treeModel = new DefaultTreeModel(root);

        tree = new JTree(treeModel);
        tree.setShowsRootHandles(true);
        JScrollPane scrollPane = new JScrollPane(tree);

        tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent event) {
                File file = (File) tree.getLastSelectedPathComponent();
                System.out.println(tree.getLastSelectedPathComponent());
            }
        });

        frame.add(scrollPane);
        frame.setLocationByPlatform(true);
        frame.setSize(640, 480);
        frame.setVisible(true);

        CreateChildNodes ccn
                = new CreateChildNodes(fileRoot, root);
        new Thread(ccn).start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new NewerFileTree());
    }

    public class CreateChildNodes implements Runnable {

        private DefaultMutableTreeNode root;
        private File fileRoot;

        public CreateChildNodes(File fileRoot,
                DefaultMutableTreeNode root) {
            this.fileRoot = fileRoot;
            this.root = root;
        }

        public void run() {
            createChildren(fileRoot, root);
        }

        private void createChildren(File fileRoot,
                DefaultMutableTreeNode node) {
            File[] files = fileRoot.listFiles();
            if (files == null) {
                return;
            }

            for (File file : files) {
                DefaultMutableTreeNode childNode
                        = new DefaultMutableTreeNode(new FileNode(file));

                DefaultMutableTreeNode childNodes = new DefaultMutableTreeNode("hello");
                node.add(childNode);
                if (file.isDirectory()) {
                    createChildren(file, childNode);
                }
            }
        }
    }

    public class FileNode {

        private File file;

        public FileNode(File file) {
            this.file = file;
        }

        @Override
        public String toString() {
            String name = file.getName();
            if (name.equals("")) {
                return file.getAbsolutePath();
            } else {
                return name;
            }
        }
    }
}```

I am working in the `tree.addTreeSelectionListener`.

Body:
The fix seen here is in two parts, marked by /* new */. Basically:

Change the FileNode to add a getFile() method (not strictly necessary, but good encapsulation).

Get the FileNode from the DefaultMutableTreeNode, then get the File from that.

import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class NewerFileTree extends JPanel implements Runnable {

    protected static final String File = null;
    private DefaultMutableTreeNode root;
    private DefaultTreeModel treeModel;
    private JTree tree;

    public void run() {
        JFrame frame = new JFrame("File Browser");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        File fileRoot = new File("C://");
        root = new DefaultMutableTreeNode(new FileNode(fileRoot));
        treeModel = new DefaultTreeModel(root);

        tree = new JTree(treeModel);
        tree.setShowsRootHandles(true);
        JScrollPane scrollPane = new JScrollPane(tree);

        tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent event) {
                /* new */
                DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)
                        tree.getLastSelectedPathComponent();
                FileNode fileNode = (FileNode)dmtn.getUserObject();
                File file = fileNode.getFile();
                System.out.println(file);
            }
        });

        frame.add(scrollPane);
        frame.setLocationByPlatform(true);
        frame.setSize(640, 480);
        frame.setVisible(true);

        CreateChildNodes ccn = new CreateChildNodes(fileRoot, root);
        new Thread(ccn).start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new NewerFileTree());
    }

    public class CreateChildNodes implements Runnable {

        private DefaultMutableTreeNode root;
        private File fileRoot;

        public CreateChildNodes(File fileRoot,
                DefaultMutableTreeNode root) {
            this.fileRoot = fileRoot;
            this.root = root;
        }

        public void run() {
            createChildren(fileRoot, root);
        }

        private void createChildren(File fileRoot,
                DefaultMutableTreeNode node) {
            File[] files = fileRoot.listFiles();
            if (files == null) {
                return;
            }

            for (File file : files) {
                DefaultMutableTreeNode childNode
                        = new DefaultMutableTreeNode(new FileNode(file));

                DefaultMutableTreeNode childNodes = new DefaultMutableTreeNode("hello");
                node.add(childNode);
                if (file.isDirectory()) {
                    createChildren(file, childNode);
                }
            }
        }
    }

    public class FileNode {

        private File file;

        public FileNode(File file) {
            this.file = file;
        }

        /* new */
        public File getFile() {
            return file;
        }

        @Override
        public String toString() {
            String name = file.getName();
            if (name.equals("")) {
                return file.getAbsolutePath();
            } else {
                return name;
            }
        }
    }
}


问:
Simple contact form success popup on same page
I have a simple contact form with contact.html and mail.php page. I want a success popup on the same page when click on submit button. Perhaps needs to use ajax. If anyone could help me. Thanks a lot.

mail.php-

```<code><?php
 $name = $_POST['name'];
 $email = $_POST['email'];
 $recipient = "example@gmail.com";
 $subject = "Contact Form";
 $mailheader = "From: $email \r\n";
 mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
 echo "Thank You!" . " -" . "<a href='form.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";
?>
</code>```

contact.html-

```<code><form action="mail.php" method="post" id="custom-form">
 <input type="text" placeholder="Name" name="name" required="">
 <input type="text" placeholder="Email" name="email" required="">
 <button class="btn" type="submit" value="send">Submit</button>
</form>
</code>```

答:
in contact.html

```<code><form action="mail.php" method="post" id="custom-form">
  <input type="text" placeholder="Name" name="name" required="">
  <input type="text" placeholder="Email" name="email" required="">
  <button class="btn" type="submit" value="send">Submit</button>
</form>
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title processing">Loading...</h4>
      </div>
     <div class="modal-body">
       <p class="repons2"></p>
     </div>
   </div>
</div></div>
<script>
  $('#custom-form').submit(function (e) {
    e.preventDefault();
    var form_data = new FormData($(this)[0]);
    var fa = $(this);
    $('#myModal').modal('show');
    $.ajax({
      url: fa.attr('action'),
      type: 'post',
      data: form_data,
      dataType: 'json',
      success: function (response) {
        $('.repons2').html(response.messages)
        $('.processing').html(response.status)
      }
   });
 });
</script>
</code>```

in mail.php

```<code><?php
      $name = $_POST['name'];
      $email = $_POST['email'];
      $recipient = "example@gmail.com";
      $subject = "Contact Form";
      $mailheader = "From: $email \r\n";
      if(mail($recipient, $subject, $formcontent, $mailheader)){
          $status="success send";
          $message= "Thank You!" . " -" . "<a href='form.html' style='text- decoration:none;color:#ff0099;'> Return Home</a>";
      }else{
         $status="fail send";
         $message="sending error";
      }
      $data=[
             "status"=>$status,
             "messages"=>$message
           ]
          echo json_encode($data);
?>
</code>```

don't forget to load the jquery for ajax to work

Body:
I have a simple contact form with contact.html and mail.php page. I want a success popup on the same page when click on submit button. Perhaps needs to use ajax. If anyone could help me. Thanks a lot.

mail.php-

<?php
 $name = $_POST['name'];
 $email = $_POST['email'];
 $recipient = "example@gmail.com";
 $subject = "Contact Form";
 $mailheader = "From: $email \r\n";
 mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
 echo "Thank You!" . " -" . " Return Home";
?>

contact.html-

<form action="mail.php" method="post" id="custom-form">
 <input type="text" placeholder="Name" name="name" required="">
 <input type="text" placeholder="Email" name="email" required="">
 <button class="btn" type="submit" value="send">Submit</button>
</form>

Body:
in contact.html

<form action="mail.php" method="post" id="custom-form">
  <input type="text" placeholder="Name" name="name" required="">
  <input type="text" placeholder="Email" name="email" required="">
  <button class="btn" type="submit" value="send">Submit</button>
</form>
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title processing">Loading...</h4>
      </div>
     <div class="modal-body">
       <p class="repons2"></p>
     </div>
   </div>
</div></div>
<script>
  $('#custom-form').submit(function (e) {
    e.preventDefault();
    var form_data = new FormData($(this)[0]);
    var fa = $(this);
    $('#myModal').modal('show');
    $.ajax({
      url: fa.attr('action'),
      type: 'post',
      data: form_data,
      dataType: 'json',
      success: function (response) {
        $('.repons2').html(response.messages)
        $('.processing').html(response.status)
      }
   });
 });
</script>

in mail.php

<?php
      $name = $_POST['name'];
      $email = $_POST['email'];
      $recipient = "example@gmail.com";
      $subject = "Contact Form";
      $mailheader = "From: $email \r\n";
      if(mail($recipient, $subject, $formcontent, $mailheader)){
          $status="success send";
          $message= "Thank You!" . " -" . "<a href='form.html' style='text- decoration:none;color:#ff0099;'> Return Home</a>";
      }else{
         $status="fail send";
         $message="sending error";
      }
      $data=[
             "status"=>$status,
             "messages"=>$message
           ]
          echo json_encode($data);
?>

don't forget to load the jquery for ajax to work


问:
how to install tkinter with Pycharm?
I used sudo apt-get install python3.6-tk and it works fine. Tkinter works if I open python in terminal, but I cannot get it installed on my Pycharm project. pip install command says it cannot find Tkinter. I cannot find python-tk in the list of possible installs either.

Is there a way to get Tkinter just standard into every virtualenv when I make a new project in Pycharm?

Edit: on Linux Mint

Edit2: It is a clear problem of Pycharm not getting tkinter guys. If I run my local python file from terminal it works fine. Just that for some reason Pycharm cannot find anything tkinter related.

答:
Pycharm comes with tkinter by default. But there are some circumstances that your installation might be missing tkinter. In that case you have to follow below mentioned steps.

For python 2 use:

```<code>sudo apt-get install python-tk
</code>```

For python 3 use:

```<code>sudo apt-get install python3-tk
</code>```

When you display info about packages it states:

Basically you have to import it

```<code>from tkinter import *

top = Tk()
# Code to add widgets will go here...
top.mainloop()
</code>```

Title: how to install tkinter with Pycharm?

Body:
Pycharm comes with tkinter by default. But there are some circumstances that your installation might be missing tkinter. In that case you have to follow below mentioned steps.

For python 2 use:

sudo apt-get install python-tk

For python 3 use:

sudo apt-get install python3-tk

When you display info about packages it states:

Basically you have to import it

from tkinter import *

top = Tk()
# Code to add widgets will go here...
top.mainloop()


答:
```<code>UserNameArray = [
    "234511Jack",
    "734636Dan",
    "237894Daniel",
    "124119James",
    "000001Test",
    "999999Donald"
]
def BubbleSort():
    for i in range(0,len(UserNameArray)-1):
        for j in range(0,len(UserNameArray)-1-i):
            UserID = int(UserNameArray[j][0:5])
            UserIDNext = int(UserNameArray[j+1][0:5])
            if UserIDNext < UserID:
                store = UserNameArray[j]
                UserNameArray[j] = UserNameArray[j+1]
                UserNameArray[j+1] = store

BubbleSort()
print(UserNameArray)
</code>```

<p>! for j in range(0,len(UserNameArray)-1-i):</p>

Title: Why doesn't my bubble sort work properly?

Body:
UserNameArray = [
    "234511Jack",
    "734636Dan",
    "237894Daniel",
    "124119James",
    "000001Test",
    "999999Donald"
]
def BubbleSort():
    for i in range(0,len(UserNameArray)-1):
        for j in range(0,len(UserNameArray)-1-i):
            UserID = int(UserNameArray[j][0:5])
            UserIDNext = int(UserNameArray[j+1][0:5])
            if UserIDNext < UserID:
                store = UserNameArray[j]
                UserNameArray[j] = UserNameArray[j+1]
                UserNameArray[j+1] = store

BubbleSort()
print(UserNameArray)

! for j in range(0,len(UserNameArray)-1-i):


问:
django rest framework dynamic url route
I'm currently doing a small project in Django (2.2.5) and djangorestframework (3.10.3). I'm having a problem getting the view connected to the router. I'd really appreciate a second pair of eyes to help me try to figure out what is wrong

For the urls I have tried the following 2:

```<code>router = routers.DefaultRouter()
router.register(r'<chatroom>', views.ChatRoomViewSet)
router.register(r'<str:chatroom>', views.ChatRoomViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls',namespace='rest_framework')),
    path('admin/', admin.site.urls),
]
</code>```

and then added the router to urlpatterns.

The viewset is:

```<code>class ChatRoomViewSet(viewsets.ModelViewSet):

    queryset = ChatRoom.objects.all().order_by('name')
    serializer_class = ChatRoomSerializer
    lookup_field = 'name'

    def get_viewset(self, request, name=None):
        name = self.kwargs.get('name', None)
        queryset = ChatRoom.objects.filter(name=name)
        return queryset
</code>```

And the serializer is

```<code>class ChatRoomSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = ChatRoom
        fields = ['url', 'name']
        lookup_field = 'name'
</code>```

The model is:

```<code>class ChatRoom(models.Model):
    name = models.CharField(max_length=255, default="")

    def __str__(self):
        return self.name
</code>```

Is there something I obviously missed?

答: Replace get_viewset by get_queryset in your viewset. Also, you either declare queryset attribute in a viewset or implement get_queryset function.

Title: django rest framework dynamic url route

Body:
I'm currently doing a small project in Django (2.2.5) and djangorestframework (3.10.3). I'm having a problem getting the view connected to the router. I'd really appreciate a second pair of eyes to help me try to figure out what is wrong

For the urls I have tried the following 2:

router = routers.DefaultRouter()
router.register(r'<chatroom>', views.ChatRoomViewSet)
router.register(r'<str:chatroom>', views.ChatRoomViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls',namespace='rest_framework')),
    path('admin/', admin.site.urls),
]

and then added the router to urlpatterns.

The viewset is:

class ChatRoomViewSet(viewsets.ModelViewSet):

    queryset = ChatRoom.objects.all().order_by('name')
    serializer_class = ChatRoomSerializer
    lookup_field = 'name'

    def get_viewset(self, request, name=None):
        name = self.kwargs.get('name', None)
        queryset = ChatRoom.objects.filter(name=name)
        return queryset

And the serializer is

class ChatRoomSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = ChatRoom
        fields = ['url', 'name']
        lookup_field = 'name'

The model is:

class ChatRoom(models.Model):
    name = models.CharField(max_length=255, default="")

    def __str__(self):
        return self.name

Is there something I obviously missed?


问:
Adding a help button to an InnoSetup wizard page
I have a setup script with a custom wizard page to get a choice from the user.  It would be nice to have a help button and to supply a small CHM file with the installable so that I can provide a detailed explanation of what the choices are.

Anyone know whether there is an easy way to do this?

答:
See this post for details on how to include a file with the installation package and reference that file before installation has started.

To add a button to the install wizard, I included the following code in the InitializeWizard event handler.

procedure CreateHelpButton (ParentForm   : TSetupForm ;
                            X            : integer ;
                            Y            : integer ;
                            W            : integer ;
                            H            : integer) ;

var
  HelpButton : TNewButton ;
begin
  HelpButton         := TNewButton.Create (ParentForm) ;
  HelpButton.Left    := X ;
  HelpButton.Top     := Y ;
  HelpButton.Width   := W ;
  HelpButton.Height  := H ;
  HelpButton.Caption := '&Help' ;
  HelpButton.OnClick := @HelpButtonOnClick ;
  HelpButton.Parent  := ParentForm ;
end;

procedure InitializeWizard () ;

begin
  CreateHelpButton (
    WizardForm, ScaleX (20), WizardForm.CancelButton.Top,
    WizardForm.CancelButton.Width, WizardForm.CancelButton.Height) ;
end;
```


问:
Conditional formatting won't work if the content of the cell is a formula
I've applied a custom formula conditional formatting that highlights the cell in column C if it matches with column K.

The formula I used is =MATCH(C3,$K$3:$K$988,0). However, it does not highlight if the content of the cell is a formula (the formula on the cell is =if(isblank(A47),"",C46+1)).here is a screenshot of the sheet with the formula
.

I tried typing the number manually, and it works, but won't work if it is a formula. If I type it manually, the format should be PLAIN TEXT so the conditional formatting will work. I tried to put in it AUTOMATIC, it does not work. Here is a screenshot of the sheet if I type the number manually
.

I'm not sure why this is happening because it works well in other sheets with the same formula. Please help me. Thank you!

答:
Adding one to C46 produces a number. If the values in column K are formatted as text it won't match with them. If you want to keep the numbers in column K formatted as text, you need to convert the number you're looking up to text before doing the lookup. You can use

```<code>MATCH(text(C3,"@"),$K$3:$K$988,0)
</code>```

or just

```<code>MATCH(C3&"",$K$3:$K$988,0)
</code>```

Body:
Adding one to C46 produces a number. If the values in column K are formatted as text it won't match with them. If you want to keep the numbers in column K formatted as text, you need to convert the number you're looking up to text before doing the lookup. You can use

MATCH(text(C3,"@"),$K$3:$K$988,0)

or just

MATCH(C3&"",$K$3:$K$988,0)


问:
get left or right position from heading in degrees
I am trying to determine if one degree on a circle is closer to the right or the left of another degree on a circle.

For example, if I have a heading of 350 degrees and another heading of 10 degrees, then I need to be able to determine that 10 degrees is to the right of 350 degrees on a circle (because it's only 20 degrees from the right -- as opposed to 340 degrees from the left).

How could this be accomplished?

答:
What you actually need is see if the difference between deg1 and deg2 is less then 180 (then deg2 on the right side) or more then it (then deg2 is on the left side

The problem is, that the deg reset at 360, means the diff between 10 and 350 is 20.. for that you can just add 360 and module by 360.

Like this

function closerSide(deg1, deg2){
  return (360+deg1-deg2)%360 > 180 ? 'deg2 on the right' : 'deg2 on the left'
}
function from180(deg){return Math.abs(180-deg)}

// tests
[[10, 350], [200,220], [30, 50], [350, 10], [180, 50]].forEach(t => console.log(closerSide(...t)))```


问:
How can I force a TD with no content to render its border?
The TD has a DIV inside which I removed using jQuery's fadeOut function, but when it finishes the border disappears too.

I want to avoid that, is there any way other than adding a " " (which causes it to be ugly)?

EDIT: I am using Internet Explorer (6 and 7)

答: Depending on what exactly you're trying to accomplish, you could set the visibility-property of the div to hidden instead of setting its display-property to none, ie you'd have to restore display and opacity and set visibility manually after the call to fadeOut().

OwnerDisplayName: Juan Manuel

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Graeme Perrow

OwnerDisplayName: Christoph

LastEditorDisplayName: Christoph


问:
SQL query to get the latest price from the data?
I have this data in my Oracle table:

In this table, I have multiple products with having product_id and price at a particular time.

I want to write a SQL query to get latest price of each product based on the TIME column (Oracle - Long Type).

But here is the problem, for our table price monitoring for the product starts at 23:00 previous date.

Output required: when I passed 2-Dec-2019 as parameter into the SQL query

How can I do this with a SQL query? Or do I need to write a stored procedure for it, based on if and else condition?

Thanks in advance.

答:
You may extend the idea from other answer (using ROW_NUMBER) to define a view providing only the records with the last price per day.

You must provide you dimensions (product_id and day) in the PARTITION BY clause, which will work for any product and any day - selecting only the row with the highest time per day and product.

```<code>create view last_price_per_day as
with last_price as (
select
  SYSTEM_DATE, PRODUCT_ID, TIME, CURRENT_PRICE,
  row_number() over (partition by PRODUCT_ID, SYSTEM_DATE order by TIME desc) as rn
from tab)
select
  SYSTEM_DATE, PRODUCT_ID, TIME, CURRENT_PRICE
from last_price
where rn = 1;
</code>```

Note that this approach is superior to altervatives using MAX(TIME) in correlated subquery, as it works fine even if ties occurres (more rows with the same highest time).

If this is a relevant topic, you may add further columns to the ORDER BY clause, e.g. by adding CURRENT_PRICE DESC you will get the highest price from the tied rows.

A good check for such last row views is to verify if the columns in PARTITIEN BY and ORDER BY  are unique in the table.

In your case PRODUCT_ID, SYSTEM_DATE, TIME should be unique, otherwise the view is not deterministic and will return on repeated queries different results - which may be not what you expect.

Body:
You may extend the idea from other answer (using ROW_NUMBER) to define a view providing only the records with the last price per day.

You must provide you dimensions (product_id and day) in the PARTITION BY clause, which will work for any product and any day - selecting only the row with the highest time per day and product.

create view last_price_per_day as
with last_price as (
select
  SYSTEM_DATE, PRODUCT_ID, TIME, CURRENT_PRICE,
  row_number() over (partition by PRODUCT_ID, SYSTEM_DATE order by TIME desc) as rn
from tab)
select
  SYSTEM_DATE, PRODUCT_ID, TIME, CURRENT_PRICE
from last_price
where rn = 1;

Note that this approach is superior to altervatives using MAX(TIME) in correlated subquery, as it works fine even if ties occurres (more rows with the same highest time).

If this is a relevant topic, you may add further columns to the ORDER BY clause, e.g. by adding CURRENT_PRICE DESC you will get the highest price from the tied rows.

A good check for such last row views is to verify if the columns in PARTITIEN BY and ORDER BY  are unique in the table.

In your case PRODUCT_ID, SYSTEM_DATE, TIME should be unique, otherwise the view is not deterministic and will return on repeated queries different results - which may be not what you expect.


问:
How to add a comment to a cell in Excel using Xlwings
Im trying to add a comment to cell A1 with the following code and this causes the jupyter notebook to freeze. On restarting I notice an empty comment was inserted on A1.

```<code>sht.range("A1").api.AddComment="My comment"
</code>```

How can I add a comment to a cell? The actual VBA is

sht.Range("A1").AddComment "My comment"

答:
Solved it.</p>

```<code>sht.range("A1").api.AddComment(Text="My Comment")
</code>```

Body:
Im trying to add a comment to cell A1 with the following code and this causes the jupyter notebook to freeze. On restarting I notice an empty comment was inserted on A1.

sht.range("A1").api.AddComment="My comment"

How can I add a comment to a cell? The actual VBA is

sht.Range("A1").AddComment "My comment"

Body:
Solved it.

sht.range("A1").api.AddComment(Text="My Comment")


问:
Java: compile-time resolution and "most specific method" as it applies to variable arity
Could someone help me understand section 15.12.2.5 of the JLS re: most specific method?

(bludgeoned cut&paste from JLS follows)

In addition, one variable arity member method named m is more specific than another variable arity member method of the same name if either:

One member method has n parameters and the other has k parameters, where n >= k. The types of the parameters of the first member method are T1, . . . , Tn-1 , Tn[], the types of the parameters of the other method are U1, . . . , Uk-1, Uk[]. If the second method is generic then let R1 ... Rp p1, be its formal type parameters, let Bl be the declared bound of Rl, 1lp, let A1 ... Ap be the actual type arguments inferred (§15.12.2.7) for this invocation under the initial constraints Ti << Ui,1ik-1, Ti << Uk, kin and let Si = Ui[R1 = A1, ..., Rp = Ap] 1ik; otherwise let Si = Ui, 1ik. Then:
      for all j from 1 to k-1, Tj <: Sj, and,
      for all j from k to n, Tj <: Sk, and,
      If the second method is a generic method as described above then Al <: Bl[R1 = A1, ..., Rp = Ap], 1lp.

One member method has k parameters and the other has n parameters, where n >= k. The types of the parameters of the first method are U1, . . . , Uk-1, Uk[], the types of the parameters of the other method are T1, . . ., Tn-1, Tn[]. If the second method is generic then let R1 ... Rp p1, be its formal type parameters, let Bl be the declared bound of Rl, 1lp, let A1 ... Ap be the actual type arguments inferred (§15.12.2.7) for this invocation under the initial constraints Ui << Ti, 1ik-1, Uk << Ti, kin and let Si = Ti[R1 = A1, ..., Rp = Ap] 1in; otherwise let Si = Ti, 1in. Then:
      for all j from 1 to k-1 , Uj <: Sj, and,
      for all j from k to n , Uk <: Sj, and,
      If the second method is a generic method as described above then Al <: Bl[R1 = A1, ..., Rp = Ap], 1lp.

Ignoring the issue generics, does this mean varargs is more important than subtyping, or subtyping is more important than varargs, when deciding whether one method is more specific than another? I can't figure it out.

Concrete example: Which of the following compute() methods is "more specific" according to the JLS?

```<code>package com.example.test.reflect;

class JLS15Test
{
    int compute(Object o1, Object o2, Object... others) { return 1; }
    int compute(String s1, Object... others)            { return 2; }

    public static void main(String[] args)
    {
        JLS15Test y = new JLS15Test();
        System.out.println(y.compute(y,y,y));
        System.out.println(y.compute("hi",y,y));
    }
}
</code>```

I can't figure out which is "more specific"; the output prints

```<code>1
2
</code>```

I'm confused how to interpret the results. When the first argument was a String, the compiler picked the method with the more specific subtype. When the first argument was an Object, the compiler picked the method with the fewer number of optional varargs.

NOTE: If you are not reading this section of the JLS, and you are giving an answer that depends on the types of the arguments, you are not helping me. If you carefully read the JLS, other than the parts relating to generics, the definition of "more specific" depends on the declared arguments, not on the actual arguments -- this comes into play in other parts of the JLS (can't find it at the moment).

e.g. for fixed arity methods, compute(String s) would be more specific than compute(Object o). But I'm trying to understand the relevant section of the JLS re: variable arity methods.

答:
After reading the JLS multiple times, I finally think I understand this section.

What they are saying is that if there are two variable-arity methods, for the purposes of deciding which is "more specific", you can consider the one with the shorter argument list to be extended so that is of equal length to the longer one. e.g.

```<code>int compute(Object o1, Object o2, Object... others)
int compute(String s1, Object... others)
</code>```

can be considered (only for the purposes of "more specific") to be equivalent to

```<code>int compute(Object o1, Object o2, Object... others)
int compute(String s1, Object,    Object... others)
</code>```

and then the argument types are compared, one by one, with the latter method being more specific.

(more rigorously, the first one has n = 3, k = 2, n >= k, with String <: Object [String is a subtype of Object] and the JLS dictates comparing the types directly of each parameter for j between 1 and k-1 [one less than the shorter length], comparing the vararg type of the shorter method signature with the remaining parameters of the longer method.)

In the following case:

```<code>int compute(Object o1, Object o2, String... strings)
int compute(Object o1, String... strings)
</code>```

these would be equivalent (only for the purposes of "more specific") to

```<code>int compute(Object o1, Object o2, String... strings)
int compute(Object o1, String,    String... strings)
</code>```

and the latter more specific.

So variable-arity never trumps subtyping for the purposes of comparing "more specific" methods which are both of variable arity.

However, fixed-arity methods are always considered first (JLS 15.12.2.2 and 15.12.2.3) before variable-arity methods.

Body:
Could someone help me understand section 15.12.2.5 of the JLS re: most specific method?

(bludgeoned cut&paste from JLS follows)

In addition, one variable arity member method named m is more specific than another variable arity member method of the same name if either:

One member method has n parameters and the other has k parameters, where n >= k. The types of the parameters of the first member method are T1, . . . , Tn-1 , Tn[], the types of the parameters of the other method are U1, . . . , Uk-1, Uk[]. If the second method is generic then let R1 ... Rp p1, be its formal type parameters, let Bl be the declared bound of Rl, 1lp, let A1 ... Ap be the actual type arguments inferred (§15.12.2.7) for this invocation under the initial constraints Ti << Ui,1ik-1, Ti << Uk, kin and let Si = Ui[R1 = A1, ..., Rp = Ap] 1ik; otherwise let Si = Ui, 1ik. Then:
      for all j from 1 to k-1, Tj <: Sj, and,
      for all j from k to n, Tj <: Sk, and,
      If the second method is a generic method as described above then Al <: Bl[R1 = A1, ..., Rp = Ap], 1lp.

One member method has k parameters and the other has n parameters, where n >= k. The types of the parameters of the first method are U1, . . . , Uk-1, Uk[], the types of the parameters of the other method are T1, . . ., Tn-1, Tn[]. If the second method is generic then let R1 ... Rp p1, be its formal type parameters, let Bl be the declared bound of Rl, 1lp, let A1 ... Ap be the actual type arguments inferred (§15.12.2.7) for this invocation under the initial constraints Ui << Ti, 1ik-1, Uk << Ti, kin and let Si = Ti[R1 = A1, ..., Rp = Ap] 1in; otherwise let Si = Ti, 1in. Then:
      for all j from 1 to k-1 , Uj <: Sj, and,
      for all j from k to n , Uk <: Sj, and,
      If the second method is a generic method as described above then Al <: Bl[R1 = A1, ..., Rp = Ap], 1lp.

Ignoring the issue generics, does this mean varargs is more important than subtyping, or subtyping is more important than varargs, when deciding whether one method is more specific than another? I can't figure it out.

Concrete example: Which of the following compute() methods is "more specific" according to the JLS?

package com.example.test.reflect;

class JLS15Test
{
    int compute(Object o1, Object o2, Object... others) { return 1; }
    int compute(String s1, Object... others)            { return 2; }

    public static void main(String[] args)
    {
        JLS15Test y = new JLS15Test();
        System.out.println(y.compute(y,y,y));
        System.out.println(y.compute("hi",y,y));
    }
}

I can't figure out which is "more specific"; the output prints

1
2

I'm confused how to interpret the results. When the first argument was a String, the compiler picked the method with the more specific subtype. When the first argument was an Object, the compiler picked the method with the fewer number of optional varargs.

NOTE: If you are not reading this section of the JLS, and you are giving an answer that depends on the types of the arguments, you are not helping me. If you carefully read the JLS, other than the parts relating to generics, the definition of "more specific" depends on the declared arguments, not on the actual arguments -- this comes into play in other parts of the JLS (can't find it at the moment).

e.g. for fixed arity methods, compute(String s) would be more specific than compute(Object o). But I'm trying to understand the relevant section of the JLS re: variable arity methods.

Body:
After reading the JLS multiple times, I finally think I understand this section.

What they are saying is that if there are two variable-arity methods, for the purposes of deciding which is "more specific", you can consider the one with the shorter argument list to be extended so that is of equal length to the longer one. e.g.

int compute(Object o1, Object o2, Object... others)
int compute(String s1, Object... others)

can be considered (only for the purposes of "more specific") to be equivalent to

int compute(Object o1, Object o2, Object... others)
int compute(String s1, Object,    Object... others)

and then the argument types are compared, one by one, with the latter method being more specific.

(more rigorously, the first one has n = 3, k = 2, n >= k, with String <: Object [String is a subtype of Object] and the JLS dictates comparing the types directly of each parameter for j between 1 and k-1 [one less than the shorter length], comparing the vararg type of the shorter method signature with the remaining parameters of the longer method.)

In the following case:

int compute(Object o1, Object o2, String... strings)
int compute(Object o1, String... strings)

these would be equivalent (only for the purposes of "more specific") to

int compute(Object o1, Object o2, String... strings)
int compute(Object o1, String,    String... strings)

and the latter more specific.

So variable-arity never trumps subtyping for the purposes of comparing "more specific" methods which are both of variable arity.

However, fixed-arity methods are always considered first (JLS 15.12.2.2 and 15.12.2.3) before variable-arity methods.


问:
Convert single byte character string (half width) to double byte (full width)
Recently I came across this code in a C# application.

```<code>cDataString = Strings.StrConv(cDataString, VbStrConv.Wide);
</code>```

I understand that the StrConv is a string function of VB. You can call it by including 'using Microsoft.VisualBasic;'.

It is supposed to covert half width japanese characters into full width ones.

My question is:
Is there a way to achieve the same WITHOUT using the VB functions and WITHOUT including the VB headers, using only the standard c# functions? I know there are many c# string conversion functions and some of them can convert from unicode to ansi and vice versa and so on. But I am not sure if any of those will directly get the exact same result as the above VB one. So, can this be done in c#?

Thank you for your time and efforts.

Update:
I came across this question that was asked 5 years ago. The answers and discussions do show some ways in which it could be done. What I would specifically like to know is that, after 5 years and new versions and what nots, is there a simpler and better way to do this in .NET without depending on VB functions or VB libraries?

答:
Not a generic solution, but in my particular case (Half-width Japanese katakana ﾗｰﾒﾝ to Full-width katakana ラーメン), String#Normalize with NFKC option did the job.

Note that this method is not entirely compatible with VB one (e.g. it converts full-width numbers ４２ to half-width numbers 42), so you need to select characters to replace like:

// Half-width katakana to Full-width katakana
Regex halfKatakana = new Regex(@"[\uFF61-\uFF9F]+");
cDataString = halfKatakana.Replace(cDataString, (m) => m.Value.Normalize(NormalizationForm.FormKC));
```

Body:
Recently I came across this code in a C# application.

cDataString = Strings.StrConv(cDataString, VbStrConv.Wide);

I understand that the StrConv is a string function of VB. You can call it by including 'using Microsoft.VisualBasic;'.

It is supposed to covert half width japanese characters into full width ones.

My question is:
Is there a way to achieve the same WITHOUT using the VB functions and WITHOUT including the VB headers, using only the standard c# functions? I know there are many c# string conversion functions and some of them can convert from unicode to ansi and vice versa and so on. But I am not sure if any of those will directly get the exact same result as the above VB one. So, can this be done in c#?

Thank you for your time and efforts.

Update:
I came across this question that was asked 5 years ago. The answers and discussions do show some ways in which it could be done. What I would specifically like to know is that, after 5 years and new versions and what nots, is there a simpler and better way to do this in .NET without depending on VB functions or VB libraries?


问:
moment js calculate time diffrence from now to date
I'm new to all the developing stuff and, I need to calculate the time difference between now and a later date.

Below is the code I have written but for some reason it doesn't show the correct time difference.

I think that the problem lies in the now = moment();
because I debugged it a lot
can anyone help

```<code>var express = require('express');
var moment = require('moment');
var app = express();

app.get('/from/:day/:month/:year', function (req, res) {
    var now = moment();

    var urlDate = req.params;
    var dateJSON = JSON.stringify(urlDate);
    var obj = JSON.parse(dateJSON);

    var final = moment([obj.year, obj.month, obj.day]);

    var years = final.diff(now, 'year');
    now.add(years, 'years');

    var months = final.diff(now, 'months');
    now.add(months, 'months');

    var days = final.diff(now, 'days');

    console.log(years + ' years ' + months + ' months ' + days + ' days');
    res.send(years + ' years ' + months + ' months ' + days + ' days');
});

app.listen(3000);
</code>```

答:
Your date format is wrong. You can use the default date format which is: YYYY-MM-DD

So

```<code>var final = moment(`${obj.year}-${obj.month}-${obj.day}`);
var years = final.diff(now, 'year');
    now.add(years, 'years');
</code>```

Note: You don't have to stringify and parse. It is already an object

```<code>var urlDate = req.params;
    //var dateJSON = JSON.stringify(urlDate);
    //var obj = JSON.parse(dateJSON);
year=urlDate.year
</code>```

Body:
I'm new to all the developing stuff and, I need to calculate the time difference between now and a later date.

Below is the code I have written but for some reason it doesn't show the correct time difference.

I think that the problem lies in the now = moment();
because I debugged it a lot
can anyone help

var express = require('express');
var moment = require('moment');
var app = express();

app.get('/from/:day/:month/:year', function (req, res) {
    var now = moment();

    var urlDate = req.params;
    var dateJSON = JSON.stringify(urlDate);
    var obj = JSON.parse(dateJSON);

    var final = moment([obj.year, obj.month, obj.day]);

    var years = final.diff(now, 'year');
    now.add(years, 'years');

    var months = final.diff(now, 'months');
    now.add(months, 'months');

    var days = final.diff(now, 'days');

    console.log(years + ' years ' + months + ' months ' + days + ' days');
    res.send(years + ' years ' + months + ' months ' + days + ' days');
});

app.listen(3000);

Body:
Your date format is wrong. You can use the default date format which is: YYYY-MM-DD

So

var final = moment(`${obj.year}-${obj.month}-${obj.day}`);
var years = final.diff(now, 'year');
    now.add(years, 'years');

Note: You don't have to stringify and parse. It is already an object

var urlDate = req.params;
    //var dateJSON = JSON.stringify(urlDate);
    //var obj = JSON.parse(dateJSON);
year=urlDate.year


问:
Without import the Angular Service to the module, can we use it?
Without import the Angular Service to the module, can we use it?

```<code>providers: [ApiService,EmployeeService,DataService,MatDatepickerModule,StudentServiceService
  ,  { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
  { provide: MAT_DATE_FORMATS, useValue: DateFormats }],
})
</code>```

here I have imported all the service classes. my question is 'Without import the Angular Service to the module, can we use it?'

答:
with Angular 6 + you can mark services line this

```<code>@Injectable({provideIn: 'root'})
class MyService {
...
}
</code>```

then you dont need to provide them explicitly

Body:
Without import the Angular Service to the module, can we use it?

providers: [ApiService,EmployeeService,DataService,MatDatepickerModule,StudentServiceService
  ,  { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
  { provide: MAT_DATE_FORMATS, useValue: DateFormats }],
})

here I have imported all the service classes. my question is 'Without import the Angular Service to the module, can we use it?'

Body:
with Angular 6 + you can mark services line this

@Injectable({provideIn: 'root'})
class MyService {
...
}

then you dont need to provide them explicitly


问:
How to compare 2 iframes and get difference visually?
Case :

I have 2 iframes and both have lot of divs and other controls so both iframes are like the medium size of HTML websites.  I want to compare both and find out differences.

I thought different options here :

Solution 1: Take a full screenshot of 2 iframes and compare both screenshots using the pillow library of Python which draws the grid on the mismatch area in a screenshot. But here the issue is I did not find any code on the internet which can take full iframe screenshots (I have a long iframe with a scroll bar). I tried almost all answers on SO but all are working for a normal page but not for the iframe.

Reference : https://blog.rinatussenov.com/automating-manual-visual-regression-tests-with-python-and-selenium-be66be950196

Solution 2: Get somehow all HTML code from both iframe and compare it, but this won't be easy to analyze result because it will find some HTML code that is different or have a mismatch in 2 iframes. This will be more like text compare and not a good solution I believe.

So I am looking for either code which can take a full screenshot of iframe using Python or Javascript OR some better option which allows me to compare 2 iframes and find out differences.

I tried almost all answers which google find our as per below :

Sample Iframe is given here where whole html is within iframe : https://grapesjs.com/demo.html , If some code can take full screenshot of this iframe then it will be easy to compare for me.

答:
I have 2 iframes and both have lot of divs and other controls so both iframes are like the medium size of HTML websites. I want to compare both and find out differences.

What do you want compare ? CSS rules/properties differences ? Data/text differences ? Or visual render ?

Compare visual render

You can extract the iframe URL and load the page with Selenium to take screenshot (see example). Also you have firefox extension Selenium IDE.


问:
How to securely create PHP variables with extract
In my previous post i ask how to create variables from an array ( PHP Variables made with foreach ) i got several answers and i was testing extract() but i have seen several against it for security reasons.

Now my question here is how can i use extract in a secure way from a $_POST that has an array that was made using jquery serialized.

With secure i mean that if a user inputs the wrong data, the secure way can take care of that with no problems.

THe PHP Site has a small warning in the extract command the says the following:

Do not use extract() on untrusted
  data, like user input (i.e. $_GET,
  $_FILES, etc.). If you do, for example
  if you want to run old code that
  relies on register_globals
  temporarily, make sure you use one of
  the non-overwriting extract_type
  values such as EXTR_SKIP and be aware
  that you should extract in the same
  order that's defined in
  variables_order within the php.ini.

It warns about the use but does not provide an example at least of how to solve the user of extract in a secure way.

答:
Don't use extract(), just use foreach() on POST/GET to create your own array/object.
extract() will be nightmare to debug once your code starts getting bigger.</p>


问:
Google Colab - How to 'restart runtime' using python code or command line interface?
Can someone suggest me programatically 'restart runtime'? Any programmatically restarting option is fine, python or CLI (Command Line Interface), without using GUI. </p>

答:
To add to Bob's answer - once you kill yourself (which the kernel process is doing), there's no going back.
So you won't be able to programmatically resume the execution after the self-destruct call.

But you can make it work without changing code - i.e. there's a limited number of reasons to restart (e.g. installing modules, especially if they were imported, switching Tensorflow versions etc.), and in your final run of the notebook, they shouldn't be necessary.

Here's a complete example of installing Detectron2 on top of a notebook about object detection:

%%time
# deps installation
try:
  import detectron2
except ImportError:
  !git clone https://github.com/facebookresearch/detectron2 detectron2_repo
  !pip install -e detectron2_repo
  print('Stopping RUNTIME! Please run again.')
  import os
  os.kill(os.getpid(), 9)
```


问:
Parsing XML files that do not have 'root' node in Python
My client wants me to parse over 100,00 xml files and converting them into a text file.

I have successfully parse a couple of files and converting them into a text file. However I managed to do that by editing the xml and adding <root></root> in the xml file.

This would seem inefficient since I would have to edit nearly 100,00 xml files to achieve my desired result.

Is there anyway for my python code to recognize the first node and read it as the root node?

I have tried using the method showed in Python XML Parsing without root
,however I do not fully understand it and I do not know where to implement this.

The XML format is as follows:

```<code><Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
        <UserID></UserID>
        <Date></Date>
        <icontent></icontent>
  </InitPost>
  <Post>
       <UserID></UserID>
       <Date></Date>
       <rcontent></rcontent>
  </Post>
</Thread>
</code>```

And this is my code on how to parse the XML files:

```<code>import os
from xml.etree import ElementTree

saveFile = open('test3.txt','w')

for path, dirs, files in os.walk("data/sample"):
   for f in files:
    fileName = os.path.join(path, f)
    with open(fileName, "r", encoding="utf8") as myFile:
        dom = ElementTree.parse(myFile)

        thread = dom.findall('Thread')

        for t in thread:

            threadID = str(t.find('ThreadID').text)
            threadID = threadID.strip()

            title = str(t.find('Title').text)
            title = title.strip()

            userID = str(t.find('InitPost/UserID').text)
            userID = userID.strip()

            date = str(t.find('InitPost/Date').text)
            date = date.strip()

            initPost = str(t.find('InitPost/icontent').text)
            initPost = initPost.strip()

        post = dom.findall('Thread/Post')
</code>```

The rest of the code is just writing to the output text file.

答:
Load the xml as text and wrap it with root element. </p>

<p>'1.xml' is the xml you have posted</p>

```<code>from xml.etree import ElementTree as ET

files = ['1.xml'] # your list of files goes here
for file in files:
    with open(file) as f:
        # wrap it with <r>
        xml = '<r>' + f.read() + '</r>'
        root = ET.fromstring(xml)
        print('Now we are ready to work with the xml')
</code>```

Body:
My client wants me to parse over 100,00 xml files and converting them into a text file.

I have successfully parse a couple of files and converting them into a text file. However I managed to do that by editing the xml and adding <root></root> in the xml file.

This would seem inefficient since I would have to edit nearly 100,00 xml files to achieve my desired result.

Is there anyway for my python code to recognize the first node and read it as the root node?

I have tried using the method showed in Python XML Parsing without root
,however I do not fully understand it and I do not know where to implement this.

The XML format is as follows:

<Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
        <UserID></UserID>
        <Date></Date>
        <icontent></icontent>
  </InitPost>
  <Post>
       <UserID></UserID>
       <Date></Date>
       <rcontent></rcontent>
  </Post>
</Thread>

And this is my code on how to parse the XML files:

import os
from xml.etree import ElementTree

saveFile = open('test3.txt','w')

for path, dirs, files in os.walk("data/sample"):
   for f in files:
    fileName = os.path.join(path, f)
    with open(fileName, "r", encoding="utf8") as myFile:
        dom = ElementTree.parse(myFile)

        thread = dom.findall('Thread')

        for t in thread:

            threadID = str(t.find('ThreadID').text)
            threadID = threadID.strip()

            title = str(t.find('Title').text)
            title = title.strip()

            userID = str(t.find('InitPost/UserID').text)
            userID = userID.strip()

            date = str(t.find('InitPost/Date').text)
            date = date.strip()

            initPost = str(t.find('InitPost/icontent').text)
            initPost = initPost.strip()

        post = dom.findall('Thread/Post')

The rest of the code is just writing to the output text file.

Body:
Load the xml as text and wrap it with root element.

'1.xml' is the xml you have posted

from xml.etree import ElementTree as ET

files = ['1.xml'] # your list of files goes here
for file in files:
    with open(file) as f:
        # wrap it with <r>
        xml = '<r>' + f.read() + '</r>'
        root = ET.fromstring(xml)
        print('Now we are ready to work with the xml')