问:
Python Tkinter updating time on message
I want to display the time when I am displaying my message. I did it but the time would not be updated. It will remain as the time when I started the mainloop. Below I attached my code. I will appreciate any form of help I could get as I am a noob trying to learn Python. Thanks. </p>

```<code>    from tkinter import *
    import time

    time3 = time.strftime('%H:%M:%S')

    def tick():
        global time1
        time2 = time.strftime('%H:%M:%S')
        clock.config(text=time2)
        clock.after(200, tick)

    root = Tk()
    root.title("Test GUI")
    time1 = ' '

    def newfile():
        message = (time3 + ':' + "Creating new file..... \n")
        text.insert(0.0, message)

    def openfile():
        message = (time3 + ':' + "Opening existing file..... \n")
        text.insert(0.0, message)

    def starttest():
        message = (time3 + ':' + "Start testing \n")
        text.insert(0.0, message)

    def stoptest():
        message = (time3 + ':' + "Stop testing \n")
        text.insert(0.0, message)

    topFrame = Frame(root)
    topFrame.pack(side = TOP)
    bottomFrame = Frame(root)
    bottomFrame.pack(side = BOTTOM)

    clock = Label(root, font=('times', 10, 'bold'), bd = 1, relief = SUNKEN, anchor = E)
    but1 = Button(topFrame, text = "START", command = starttest)
    but2 = Button(topFrame, text = "STOP", command = stoptest)
    text = Text(topFrame, width = 35, height = 5, wrap = WORD)

    clock.pack(side = BOTTOM, fill = X)
    but1.grid(row = 3, column = 3)
    but2.grid(row = 3, column = 4)
    text.grid(row = 1, column = 0, columnspan =2, sticky = W)

    menu = Menu(topFrame)
    root.config(menu = menu)

    subMenu = Menu(menu)
    menu.add_cascade(label = "File", menu = subMenu)
    subMenu.add_command(label = "New File", command = newfile)
    subMenu.add_command(label = "Open File", command = openfile)

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

答:
Firstly, I would recommend you write your application as a class (see Best way to structure a tkinter application) as it will be more organized.

```<code>class Timer(tk.Frame):
    def __init__(self, parent): # create the time frame...
        self.parent = parent
        self.time_1 = " "
        self.time_label = tk.Label(text=self.time_1)
        self.time_label.pack()
        self.random_lbl = tk.Label(text="hi lol")
        self.random_lbl.pack()
        self.update_clock() # we start the clock here.
</code>```

When you update the time, stick to the variable you used for the time (say, in this case, it's time_1):

```<code>    def update_clock(self): # update the clock...
        self.time_2 = time.strftime("%H:%M:%S")
        self.time_1 = self.time_2 # we are changing time_1 here.
        self.time_label.config(text=self.time_1)
        self.parent.after(200, self.update_clock) # then we redo the process.

root = tk.Tk() # create the root window.
timer = Timer(root)
root.mainloop()
</code>```

Title: Python Tkinter updating time on message

Body:
I want to display the time when I am displaying my message. I did it but the time would not be updated. It will remain as the time when I started the mainloop. Below I attached my code. I will appreciate any form of help I could get as I am a noob trying to learn Python. Thanks.

    from tkinter import *
    import time

    time3 = time.strftime('%H:%M:%S')

    def tick():
        global time1
        time2 = time.strftime('%H:%M:%S')
        clock.config(text=time2)
        clock.after(200, tick)

    root = Tk()
    root.title("Test GUI")
    time1 = ' '

    def newfile():
        message = (time3 + ':' + "Creating new file..... \n")
        text.insert(0.0, message)

    def openfile():
        message = (time3 + ':' + "Opening existing file..... \n")
        text.insert(0.0, message)

    def starttest():
        message = (time3 + ':' + "Start testing \n")
        text.insert(0.0, message)

    def stoptest():
        message = (time3 + ':' + "Stop testing \n")
        text.insert(0.0, message)

    topFrame = Frame(root)
    topFrame.pack(side = TOP)
    bottomFrame = Frame(root)
    bottomFrame.pack(side = BOTTOM)

    clock = Label(root, font=('times', 10, 'bold'), bd = 1, relief = SUNKEN, anchor = E)
    but1 = Button(topFrame, text = "START", command = starttest)
    but2 = Button(topFrame, text = "STOP", command = stoptest)
    text = Text(topFrame, width = 35, height = 5, wrap = WORD)

    clock.pack(side = BOTTOM, fill = X)
    but1.grid(row = 3, column = 3)
    but2.grid(row = 3, column = 4)
    text.grid(row = 1, column = 0, columnspan =2, sticky = W)

    menu = Menu(topFrame)
    root.config(menu = menu)

    subMenu = Menu(menu)
    menu.add_cascade(label = "File", menu = subMenu)
    subMenu.add_command(label = "New File", command = newfile)
    subMenu.add_command(label = "Open File", command = openfile)

    tick()
    root.mainloop()

Body:
Firstly, I would recommend you write your application as a class (see Best way to structure a tkinter application) as it will be more organized.

class Timer(tk.Frame):
    def __init__(self, parent): # create the time frame...
        self.parent = parent
        self.time_1 = " "
        self.time_label = tk.Label(text=self.time_1)
        self.time_label.pack()
        self.random_lbl = tk.Label(text="hi lol")
        self.random_lbl.pack()
        self.update_clock() # we start the clock here.

When you update the time, stick to the variable you used for the time (say, in this case, it's time_1):

    def update_clock(self): # update the clock...
        self.time_2 = time.strftime("%H:%M:%S")
        self.time_1 = self.time_2 # we are changing time_1 here.
        self.time_label.config(text=self.time_1)
        self.parent.after(200, self.update_clock) # then we redo the process.

root = tk.Tk() # create the root window.
timer = Timer(root)
root.mainloop()


来源: stackexchange

问:
Powershell devbox Magento installation using Docker
Today I am trying to install the Magento DevBox now. Here you can configure your choice, so I choosed for the Create New Installation

I have downloaded the zip file and extracted it in the location:  .docker

Now when I use PowerShell to locate to this folder and I want to install this package it asks me about a sudo password for Magento 2. I did not created this password before so how am I supposed to solve this? Because after blank imputs for this password for instance it stops the installation..

In the picture a printscreen:

So this is what u get after 3 attempts to get through this...

```<code>Install Magento
.[sudo] password for magento2:
Sorry, try again
. [sudo] password for magento2:
Sorry, try again
. [sudo] password for magento2:
Sorry, try again
. sudo: 3 incorrect password attempts Executing shell command:
cd /var/www/magento2 && COMPOSER_AUTH="{\"http-basic\": {\"repo.magento.com\ repo.magento.com magento/project-community-edition:2.1.6 .
</code>```

答:
No answer, I guess it is an empty password, but sudo is not accepting it. What I did to solve the problem was, first connect to the docker container using the SSH port ( user magento2 ), and changed the password to "magento2".
After that, I executed m2devbox-init.bat again, used that password and it worked!

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
Today I am trying to install the Magento DevBox now. Here you can configure your choice, so I choosed for the Create New Installation

I have downloaded the zip file and extracted it in the location:  .docker

Now when I use PowerShell to locate to this folder and I want to install this package it asks me about a sudo password for Magento 2. I did not created this password before so how am I supposed to solve this? Because after blank imputs for this password for instance it stops the installation..

In the picture a printscreen:

So this is what u get after 3 attempts to get through this...

Install Magento
.[sudo] password for magento2:
Sorry, try again
. [sudo] password for magento2:
Sorry, try again
. [sudo] password for magento2:
Sorry, try again
. sudo: 3 incorrect password attempts Executing shell command:
cd /var/www/magento2 && COMPOSER_AUTH="{\"http-basic\": {\"repo.magento.com\ repo.magento.com magento/project-community-edition:2.1.6 .


问:
how to replace the text with desired text in a para
I have the following code.. in this I am trying to find the particular text and replace with desired one.. this is working fine if the string is in same case.. if we give with  capitals (like.. the as The) it is not giving out put.. so what is the solution for this.. can we use regular expressions in this  one..? please help me</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>  <head>   <title> New Document
</title> <script
type="text/javascript"
src="jquery-1.4.2.min.js"></script>
<script> $(document).ready(function(){
$('#replace').click(function(){ var
oldstr=$('#inputstring').val(); var
newstr=$('#newstring').val(); var
para=$('#para').html();

var x=para.replace(oldstr,newstr);
$('#para').empty().html(x);

}) }) </script>  </head>

<body> Enter your string here:<input
type="text" id="inputstring"><br>
Enter new string here:<input
type="text" id="newstring"><br> <input
type="button" id="replace"
value="Replace"><br>

<p id="para">This is the new paragraph
written to test how to replace the a
string with desired string</p>
</body> </html>
</code>```

答:
You need to use ignorecase flag for the regular expression.

```<code>para.replace(new RegExp(oldstr, 'i'), newstr
</code>```

Docs: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

ContentLicense: CC BY-SA 2.5

Body:
I have the following code.. in this I am trying to find the particular text and replace with desired one.. this is working fine if the string is in same case.. if we give with  capitals (like.. the as The) it is not giving out put.. so what is the solution for this.. can we use regular expressions in this  one..? please help me

<!DOCTYPE HTML PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
     <title> New Document
</title>

 Enter your string here:<input
type="text" id="inputstring">

Enter new string here:<input
type="text" id="newstring">
 <input
type="button" id="replace"
value="Replace">

This is the new paragraph
written to test how to replace the a
string with desired string

Body:
You need to use ignorecase flag for the regular expression.

para.replace(new RegExp(oldstr, 'i'), newstr

Docs: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions


问:
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Azure Active Directory is only supported on Windows operating systems
We are trying to run sql files from Jenkins Linux machine using Liquibase to the Microsoft SQL server db and getting the error as:

ERROR: Build step failed with exception java.lang.RuntimeException:
  Error getting database connection using driver
  com.microsoft.sqlserver.jdbc.SQLServerDriver using url
  jdbc:sqlserver://*********.database.windows.net:***;database=*********;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;Authentication=ActiveDirectoryIntegrated'
  at org.jenkinsci.plugins.liquibase.evaluator.AbstractLiquibaseBuilder.createJdbcConnection(AbstractLiquibaseBuilder.java:236)
  at org.jenkinsci.plugins.liquibase.evaluator.AbstractLiquibaseBuilder.createLiquibase(AbstractLiquibaseBuilder.java:164)
  at org.jenkinsci.plugins.liquibase.evaluator.AbstractLiquibaseBuilder.perform(AbstractLiquibaseBuilder.java:129)at hudson.tasks.BuildStepCompatibilityLayer.perform(BuildStepCompatibilityLayer.java:78)at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)at hudson.model.Build$BuildExecution.build(Build.java:205)at hudson.model.Build$BuildExecution.doRun(Build.java:162)
  at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:534)
  at hudson.model.Run.execute(Run.java:1720)at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)at hudson.model.ResourceController.execute(ResourceController.java:98)at hudson.model.Executor.run(Executor.java:404)
  Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: **Azure
  Active Directory is only supported on Windows operating
  systems.**at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1289)at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:773)

We have tried connecting  directly with SQL server authentication and it was successful but while using Azure service principal credential we are getting this error. How do we use Azure SPN to work with Liquibase?

答:
Are you sure you want to connect using active directory integrated to SQL Azure? You should try to connect using the admin server login of SQL Azure or using a login created on SQL Azure. If that is the case, please look how to create the connection string on the samples contained on below article.

https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-java

Hope this helps.

Regards,

Alberto Morillo


问:
Select all children with the key in array with Firebase in Android
Let me start by saiyng that I'm a complete beginner with Android and Firebase too. I'm using a small project to learn booth technologies and I came across with this challenge.

Imagine I have the following Firebase Database structure:

```<code>{
    "projects": {
        "p01": {
            "name": "Projecto #1",
            "created_at": "2017-01-01 20:00:00",
            "tags": {
                "t01": true,
                "t03": true
            }
        },
        "p02": {
            "name": "Projecto #2",
            "created_at": "2017-02-01 02:20:33",
            "tags": {
                "t02": true,
            }
        }
    },
    "tags": {
        "t01": {
            "color": "#000CCC",
            "name": "Nature"
        },
        "t02": {
            "color": "#DD00FF",
            "name": "Technology"
        },
        "t03": {
            "color": "#438DC2",
            "name": "Social"
        }
    }
}
</code>```

I want to display a list view with all my projects, and on each row I want to display the title of the project and a list of tags with its background color. That I managed to too, but I think the way I achieved it, its not the best practice.

First I create a value event listener to get all all projects, like this:

```<code>fbdRef.child("projects").addValueEventListener(new ValueEventListener() {
</code>```

And on the onDataChange I have a for loop that reads and adds all the projects to an ArrayList, but in that loop I do something first asyncronously. Something like this:

```<code>for(DataSnapshot tagSnapshot: projectSnapshot.child("tags").getChildren()){
     fbdRef.child("tags/" + tagSnapshot.getKey()).addValueEventListener(new ValueEventListener() {
</code>```

I'm reading all tags, one by one, and updating its item on ListView, this looks ugly and it may be slow. I really am struggling with noSql concept of Firebase and the best way to structure my databases.

What is the best way to get all tags content from each project?

答:
The direct alternative is to:

```<code>reference.child("projects").addChildEventListener(...);
</code>```

Then for each child added, or moved, or remove, pass it to the adapter and update the adapter.

Since you probably don't want to handle every situation, there is Firebase-Ui library which provides an adapter to display the list: https://github.com/firebase/FirebaseUI-Android

You should also check your data structure since the tags are outside the element itself you are doing 2 queries, you should simply add the "name" and "color" attribute to the Project model. The key for structuring data in Firebase is to do it by thinking what the views need. Avoid unnecessary nesting and extra queries.

Body:
Let me start by saiyng that I'm a complete beginner with Android and Firebase too. I'm using a small project to learn booth technologies and I came across with this challenge.

Imagine I have the following Firebase Database structure:

{
    "projects": {
        "p01": {
            "name": "Projecto #1",
            "created_at": "2017-01-01 20:00:00",
            "tags": {
                "t01": true,
                "t03": true
            }
        },
        "p02": {
            "name": "Projecto #2",
            "created_at": "2017-02-01 02:20:33",
            "tags": {
                "t02": true,
            }
        }
    },
    "tags": {
        "t01": {
            "color": "#000CCC",
            "name": "Nature"
        },
        "t02": {
            "color": "#DD00FF",
            "name": "Technology"
        },
        "t03": {
            "color": "#438DC2",
            "name": "Social"
        }
    }
}

I want to display a list view with all my projects, and on each row I want to display the title of the project and a list of tags with its background color. That I managed to too, but I think the way I achieved it, its not the best practice.

First I create a value event listener to get all all projects, like this:

fbdRef.child("projects").addValueEventListener(new ValueEventListener() {

And on the onDataChange I have a for loop that reads and adds all the projects to an ArrayList, but in that loop I do something first asyncronously. Something like this:

for(DataSnapshot tagSnapshot: projectSnapshot.child("tags").getChildren()){
     fbdRef.child("tags/" + tagSnapshot.getKey()).addValueEventListener(new ValueEventListener() {

I'm reading all tags, one by one, and updating its item on ListView, this looks ugly and it may be slow. I really am struggling with noSql concept of Firebase and the best way to structure my databases.

What is the best way to get all tags content from each project?

Body:
The direct alternative is to:

reference.child("projects").addChildEventListener(...);

Then for each child added, or moved, or remove, pass it to the adapter and update the adapter.

Since you probably don't want to handle every situation, there is Firebase-Ui library which provides an adapter to display the list: https://github.com/firebase/FirebaseUI-Android

You should also check your data structure since the tags are outside the element itself you are doing 2 queries, you should simply add the "name" and "color" attribute to the Project model. The key for structuring data in Firebase is to do it by thinking what the views need. Avoid unnecessary nesting and extra queries.


问:
Basic VBSCRIPT and HTML
I am introducing myself into VbScript, can someone tell me what is wrong with my code? When I run it in IE the output is blank... I would expect the Hello World

E1: I am saving the file as .html

```<code><html>

<body>

<script language="vbscript" type="text/vbscript">

   document.write("Hello World!")

</script>

</body>

</html>
</code>```

答:
The document.write() is JavaScript and not VBScript. You just need to use tge following to display it on your browser:

```<code><html>

<body>
  <script>
    document.write("Hello World!");
  </script>
</body>

</html>
</code>```

But if you want to really use VBScript, then you need to use a supporting browser, which I feel I don't think there's any at the moment. Looks like you may need to turn on the feature before you can use it:

VBScript in Internet Explorer

Here are simple steps to turn on or turn off VBScript in your Internet Explorer:

Follow Tools » Internet Options from the menu

Select Security tab from the dialog box

Click the Custom Level button

Scroll down till you find Scripting option

Select Enable radio button under Active scripting

Finally click OK and come out

Title: Basic VBSCRIPT and HTML

Body:
The document.write() is JavaScript and not VBScript. You just need to use tge following to display it on your browser:

<html>

<body>
  <script>
    document.write("Hello World!");
  </script>
</body>

</html>

But if you want to really use VBScript, then you need to use a supporting browser, which I feel I don't think there's any at the moment. Looks like you may need to turn on the feature before you can use it:

VBScript in Internet Explorer

Here are simple steps to turn on or turn off VBScript in your Internet Explorer:

Follow Tools » Internet Options from the menu

Select Security tab from the dialog box

Click the Custom Level button

Scroll down till you find Scripting option

Select Enable radio button under Active scripting

Finally click OK and come out


问:
LaTeX: Indent subcaption in figure environment
See this MWE:

```<code>% !TeX spellcheck = en_US
\documentclass[12pt]{article}
\usepackage[onehalfspacing]{setspace}
\usepackage[a4paper, margin=2.5cm]{geometry}
\usepackage{mathptmx}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[hang]{caption}
\usepackage{subcaption}
\usepackage[bottom]{footmisc}
\usepackage{dcolumn} %makes r output work
\usepackage{tabularx}
\newcolumntype{L}[1]{>{\raggedright\arraybackslash}p{#1}}
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\newcolumntype{R}[1]{>{\raggedleft\arraybackslash}p{#1}}
\newcommand{\possessivecite}[1]{\citeauthor{#1}'s (\citeyear{#1})}
\usepackage{pdfpages}
\usepackage{hyperref}
\usepackage{pdflscape}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}

\begin{landscape}
    \setcapmargin[2cm]

\begin{figure}[]
    \captionsetup{justification=centering}
    \caption{Main Caption. }
    \label{fig:val_efcts}
    \begin{subfigure}{0.55\textwidth}
        \caption{X}
        \includegraphics[width=\textwidth] {example-image-a}
    \end{subfigure}
    \begin{subfigure}{0.55\textwidth}
        \caption{Y}
        \includegraphics[width=\textwidth] {example-image-b}
    \end{subfigure}
    \begin{subfigure}{0.55\textwidth}
        \caption{Z}
        \includegraphics[width=\textwidth] {example-image-c}
    \end{subfigure}
    \captionsetup{justification=raggedright}    \subcaption*{This subcaption is supposed to be ragged right and intented by 4 cm. \\ This is in a new line.}
\end{figure}

\end{landscape}

\end{document}
</code>```

It should be self-explanatory, mostly. I'd like the last subcaption below the picture to be ragged right, but indented 2 cm. I tried to use \setcapmargin, but that does not work, creating the "undefined control sequence" error (so it's an unknown command).

答:
Since you're writing a caption without numbering, set it in a \parbox where you have some more control over the placement and alignment:

```<code>\documentclass{article}

\usepackage{graphicx}
\usepackage[hang]{caption}
\usepackage{subcaption}

\begin{document}

\begin{figure}[]
    \captionsetup{justification=centering}
    \caption{Main Caption. }
    \label{fig:val_efcts}
    \begin{subfigure}{0.3\textwidth}
      \caption{X}
      \includegraphics[width=\linewidth] {example-image-a}
    \end{subfigure}\hfill
    \begin{subfigure}{0.3\textwidth}
      \caption{Y}
      \includegraphics[width=\linewidth] {example-image-b}
    \end{subfigure}\hfill
    \begin{subfigure}{0.3\textwidth}
      \caption{Z}
      \includegraphics[width=\linewidth] {example-image-c}
    \end{subfigure}

    \hspace*{4cm}%
    \parbox{\dimexpr\linewidth-8cm}{\raggedright
    \strut This subcaption is supposed to be ragged right and indented by 4cm. \\
    This is in a new line.\strut%
    }
\end{figure}

\end{document}
</code>```

Note the use of \struts to support correct baseline alignment when dealing with text inside \parboxes. For more on this, see How to keep a constant baseline skip when using minipages (or \parboxes)?

Body:
See this MWE:

% !TeX spellcheck = en_US
\documentclass[12pt]{article}
\usepackage[onehalfspacing]{setspace}
\usepackage[a4paper, margin=2.5cm]{geometry}
\usepackage{mathptmx}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[hang]{caption}
\usepackage{subcaption}
\usepackage[bottom]{footmisc}
\usepackage{dcolumn} %makes r output work
\usepackage{tabularx}
\newcolumntype{L}[1]{>{\raggedright\arraybackslash}p{#1}}
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\newcolumntype{R}[1]{>{\raggedleft\arraybackslash}p{#1}}
\newcommand{\possessivecite}[1]{\citeauthor{#1}'s (\citeyear{#1})}
\usepackage{pdfpages}
\usepackage{hyperref}
\usepackage{pdflscape}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}

\begin{landscape}
    \setcapmargin[2cm]

\begin{figure}[]
    \captionsetup{justification=centering}
    \caption{Main Caption. }
    \label{fig:val_efcts}
    \begin{subfigure}{0.55\textwidth}
        \caption{X}
        \includegraphics[width=\textwidth] {example-image-a}
    \end{subfigure}
    \begin{subfigure}{0.55\textwidth}
        \caption{Y}
        \includegraphics[width=\textwidth] {example-image-b}
    \end{subfigure}
    \begin{subfigure}{0.55\textwidth}
        \caption{Z}
        \includegraphics[width=\textwidth] {example-image-c}
    \end{subfigure}
    \captionsetup{justification=raggedright}    \subcaption*{This subcaption is supposed to be ragged right and intented by 4 cm. \\ This is in a new line.}
\end{figure}

\end{landscape}

\end{document}

It should be self-explanatory, mostly. I'd like the last subcaption below the picture to be ragged right, but indented 2 cm. I tried to use \setcapmargin, but that does not work, creating the "undefined control sequence" error (so it's an unknown command).

Body:
Since you're writing a caption without numbering, set it in a \parbox where you have some more control over the placement and alignment:

\documentclass{article}

\usepackage{graphicx}
\usepackage[hang]{caption}
\usepackage{subcaption}

\begin{document}

\begin{figure}[]
    \captionsetup{justification=centering}
    \caption{Main Caption. }
    \label{fig:val_efcts}
    \begin{subfigure}{0.3\textwidth}
      \caption{X}
      \includegraphics[width=\linewidth] {example-image-a}
    \end{subfigure}\hfill
    \begin{subfigure}{0.3\textwidth}
      \caption{Y}
      \includegraphics[width=\linewidth] {example-image-b}
    \end{subfigure}\hfill
    \begin{subfigure}{0.3\textwidth}
      \caption{Z}
      \includegraphics[width=\linewidth] {example-image-c}
    \end{subfigure}

    \hspace*{4cm}%
    \parbox{\dimexpr\linewidth-8cm}{\raggedright
    \strut This subcaption is supposed to be ragged right and indented by 4cm. \\
    This is in a new line.\strut%
    }
\end{figure}

\end{document}

Note the use of \struts to support correct baseline alignment when dealing with text inside \parboxes. For more on this, see How to keep a constant baseline skip when using minipages (or \parboxes)?


问:
Custom sort Map Java
i have some troubles when i want to sort a map, when i create a map passing a string, it comes organized like

```<code>nombre=EDIFICADORA JUANA, descripcion=  LOS frst com MEJORES Estamso para servir LOS, correo1=rst008@guan.com, correo2=oipoa@gmaio.com, numero1=24602254, numero2=55655545
</code>```

When i create a map using this data it comes disordered, this is the method that creates the map:

```<code>   private HashMap<String, String> getMap(String rawData) {
    HashMap<String, String> map = new HashMap<>();
    String[] pairs = rawData.split(","); // split into key-value pairs
    for(String pair: pairs) {
        pair = pair.trim(); // get rid of extraneous white-space
        String[] components = pair.split("=");
        String key = components[0].trim();
        String value = components[1].trim();
        map.put(key, value); // put the pair into the map
    }
    return map;
}
</code>```

This function returns something like:

0 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

1 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

2 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

3 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

4 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso
par"

5 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

How can i sort this Map like the string value comes?

I expect:

0 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

1 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso par"

2 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

3 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

4 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

5 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

答:
The issue is that you're using a HashMap. From their docs:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time

You're looking for something that maintains the order you are putting things into the map, so a LinkedHashMap could help. If that isn't enough for you, you could write your own Map implementation that implements SortedMap.

Title: Custom sort Map Java

Body:
i have some troubles when i want to sort a map, when i create a map passing a string, it comes organized like

nombre=EDIFICADORA JUANA, descripcion=  LOS frst com MEJORES Estamso para servir LOS, correo1=rst008@guan.com, correo2=oipoa@gmaio.com, numero1=24602254, numero2=55655545

When i create a map using this data it comes disordered, this is the method that creates the map:

   private HashMap<String, String> getMap(String rawData) {
    HashMap<String, String> map = new HashMap<>();
    String[] pairs = rawData.split(","); // split into key-value pairs
    for(String pair: pairs) {
        pair = pair.trim(); // get rid of extraneous white-space
        String[] components = pair.split("=");
        String key = components[0].trim();
        String value = components[1].trim();
        map.put(key, value); // put the pair into the map
    }
    return map;
}

This function returns something like:

0 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

1 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

2 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

3 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

4 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso
par"

5 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

How can i sort this Map like the string value comes?

I expect:

0 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

1 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso par"

2 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

3 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

4 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

5 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"


问:
Connecting to JDBC
When trying to connect to a local database using JDBC and Apache Derby with a Properties file, I get the following exception:

```<code>java.sql.SQLException: Database 'Mobsters' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver$1.run(Unknown Source)
at org.apache.derby.jdbc.InternalDriver$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
at com.adrian.mobsters.gui.controllers.MainController.getDBConnection(MainController.java:401)
at com.adrian.mobsters.gui.controllers.MainController$2.call(MainController.java:388)
at com.adrian.mobsters.gui.controllers.MainController$2.call(MainController.java:376)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1423)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
Caused by: ERROR XJ004: Database 'Mobsters' not found.
    at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
    at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
    ... 22 more
</code>```

I am using a properties file:

```<code>create=true
databaseName=Mobsters
user=myuser
password=mypw!
shutdown=true
</code>```

I know the database doesn't exist. Shouldn't this create the database? This is am embedded application database that should be created if it does not exist.

Code used to setup database connection:

```<code>public void initializeDB() {
    Task<Void> task = new Task() {
        @Override
        protected Void call() throws Exception {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            Properties properties = loadDBProperties();
            // Decide on the db system directory: <userhome>/.addressbook/
            String userHomeDir = System.getProperty("user.home", ".");
            String systemDir = userHomeDir + "/.mobsters";
            new File(systemDir).mkdir();
            // Set the db system directory.
            System.setProperty("derby.system.home", systemDir);

            getDBConnection(properties);

            MobsterDBUtils.createMobsterTable(getDBConnection());
            return null;
        }
    };

    new Thread(task).start();
}

public void getDBConnection(Properties properties) {
    String url = "jdbc:derby:";
    try {
         connection.set(DriverManager.getConnection(url, properties));
    } catch (SQLException ex) {
        Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public Properties loadDBProperties() {
    Properties prop = new Properties();

    InputStream is = MainController.class.getResourceAsStream("/derby/DerbyConfig.properties");

    try {
        prop.load(is);
    } catch (IOException ex) {
        Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return prop;
}
</code>```

As far as I know, the properties file is being properly imported:

(this isn't confidential login information)

答: Adding shutdown=true to the URL will shut the connection down. With this property added, the database is not created. This should be used when done with the database connection.

Title: Connecting to JDBC

Body:
When trying to connect to a local database using JDBC and Apache Derby with a Properties file, I get the following exception:

java.sql.SQLException: Database 'Mobsters' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver$1.run(Unknown Source)
at org.apache.derby.jdbc.InternalDriver$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
at com.adrian.mobsters.gui.controllers.MainController.getDBConnection(MainController.java:401)
at com.adrian.mobsters.gui.controllers.MainController$2.call(MainController.java:388)
at com.adrian.mobsters.gui.controllers.MainController$2.call(MainController.java:376)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1423)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
Caused by: ERROR XJ004: Database 'Mobsters' not found.
    at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
    at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
    ... 22 more

I am using a properties file:

create=true
databaseName=Mobsters
user=myuser
password=mypw!
shutdown=true

I know the database doesn't exist. Shouldn't this create the database? This is am embedded application database that should be created if it does not exist.

Code used to setup database connection:

public void initializeDB() {
    Task<Void> task = new Task() {
        @Override
        protected Void call() throws Exception {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            Properties properties = loadDBProperties();
            // Decide on the db system directory: <userhome>/.addressbook/
            String userHomeDir = System.getProperty("user.home", ".");
            String systemDir = userHomeDir + "/.mobsters";
            new File(systemDir).mkdir();
            // Set the db system directory.
            System.setProperty("derby.system.home", systemDir);

            getDBConnection(properties);

            MobsterDBUtils.createMobsterTable(getDBConnection());
            return null;
        }
    };

    new Thread(task).start();
}

public void getDBConnection(Properties properties) {
    String url = "jdbc:derby:";
    try {
         connection.set(DriverManager.getConnection(url, properties));
    } catch (SQLException ex) {
        Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public Properties loadDBProperties() {
    Properties prop = new Properties();

    InputStream is = MainController.class.getResourceAsStream("/derby/DerbyConfig.properties");

    try {
        prop.load(is);
    } catch (IOException ex) {
        Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return prop;
}

As far as I know, the properties file is being properly imported:

(this isn't confidential login information)


问:
load a page outside the router-outlet in angular 4
I am working on a angular 4 application and I want load login.page.ts outside of the router-outlet

this is my home.component.html file

```<code><div class="container">
   <top-nav-bar></top-nav-bar>
   <lett-nav-bar></lett-nav-bar>
   <router-outlet></router-outlet>
</div>
</code>```

routes configs

```<code>const MAINMENU_ROUTES: Routes = [
    { path: 'login', component: LoginComponent },
    { path: '', redirectTo: 'home', pathMatch: 'full'},
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];
</code>```

with this, I can load login page inside the router but I want to load login page in full screen before coming to the router-outlet.

答:
You cannot route to a page without a router outlet. Based on what you are describing, it sounds like you need another router outlet at a higher level, say in an App Component. Something like this:

```<code><div class="container">
   <router-outlet></router-outlet>
</div>
</code>```

Then you can route the login page and the home component into this router outlet.

Your route configuration would then look something like this:

```<code>    { path: 'login', component: LoginComponent },
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard],
      children: [
       { path: 'child1', component: Child1Component },
       { path: 'child2', component: Child2Component }
      ]
    }
</code>```

The login and home routes would then appear in the App Component's router outlet, so the login page would be shown full screen with no nav bars. And the child1 and child2 routes would appear in the Home Component's router outlet.

Body:
I am working on a angular 4 application and I want load login.page.ts outside of the router-outlet

this is my home.component.html file

   <top-nav-bar></top-nav-bar>
   <lett-nav-bar></lett-nav-bar>
   <router-outlet></router-outlet>

routes configs

const MAINMENU_ROUTES: Routes = [
    { path: 'login', component: LoginComponent },
    { path: '', redirectTo: 'home', pathMatch: 'full'},
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];

with this, I can load login page inside the router but I want to load login page in full screen before coming to the router-outlet.

Body:
You cannot route to a page without a router outlet. Based on what you are describing, it sounds like you need another router outlet at a higher level, say in an App Component. Something like this:

<div class="container">
   <router-outlet></router-outlet>
</div>

Then you can route the login page and the home component into this router outlet.

Your route configuration would then look something like this:

    { path: 'login', component: LoginComponent },
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard],
      children: [
       { path: 'child1', component: Child1Component },
       { path: 'child2', component: Child2Component }
      ]
    }

The login and home routes would then appear in the App Component's router outlet, so the login page would be shown full screen with no nav bars. And the child1 and child2 routes would appear in the Home Component's router outlet.


问:
Pad binaries in elixir by a variable amount
I need a function that can produce a binary that consists of a certain number of 0 octets. I though the following would be possible

```<code>def padding(length) do
  bits = length * 8
  <<0::bits>>
end
</code>```

OR

```<code>def padding(length) do
  <<0::binary-size(length)>>
end
</code>```

Both of these fail with an argument error. Why is it not passible to pass a variable to create a binary in elixir. It looks from this link like it would be possible in erlang. http://erlang.org/pipermail/erlang-questions/2008-December/040703.html

Also what would be a simple way to implement this function in Elixir

答:
You were almost there. Your first attempt needs an explicit size() to work:

```<code>iex(1)> length = 5
5
iex(2)> bits = length * 8
40
iex(3)> <<0::size(bits)>>
<<0, 0, 0, 0, 0>>
</code>```

I don't think there's a way to create this binary using ::binary-size(N). The Erlang mailing list thread you linked to also multiplies the number of bytes with 8 before constructing the binary. Elixir just doesn't allow expressions in size() like Erlang does though.

You can also use :binary.copy/2 but I'm not sure if that's as efficient as the above:

```<code>iex(4)> :binary.copy(<<0>>, 5)
<<0, 0, 0, 0, 0>>
</code>```

Body:
I need a function that can produce a binary that consists of a certain number of 0 octets. I though the following would be possible

def padding(length) do
  bits = length * 8
  <<0::bits>>
end

OR

def padding(length) do
  <<0::binary-size(length)>>
end

Both of these fail with an argument error. Why is it not passible to pass a variable to create a binary in elixir. It looks from this link like it would be possible in erlang. http://erlang.org/pipermail/erlang-questions/2008-December/040703.html

Also what would be a simple way to implement this function in Elixir

Body:
You were almost there. Your first attempt needs an explicit size() to work:

iex(1)> length = 5
5
iex(2)> bits = length * 8
40
iex(3)> <<0::size(bits)>>
<<0, 0, 0, 0, 0>>

I don't think there's a way to create this binary using ::binary-size(N). The Erlang mailing list thread you linked to also multiplies the number of bytes with 8 before constructing the binary. Elixir just doesn't allow expressions in size() like Erlang does though.

You can also use :binary.copy/2 but I'm not sure if that's as efficient as the above:

iex(4)> :binary.copy(<<0>>, 5)
<<0, 0, 0, 0, 0>>


问:
How to avoid adding field change handling methods and other boilerplates in react form?
I have a react based form with more than 10 fields in it, I have states for those ten form fields (controlled component).

Most of these input fields are of type text only but other types fields will be added later.

Problem is that I need to write 10 change handlers for them to set state correctly and then add method bindings for each of them in constructor.

I am quite new to react and may be not aware about correct
  methodologies and techniques.

Please guide me to how to improve my current code structure and avoid writing boiler plates and repetitive error prone code.

My current Registration component is like below -

```<code>export default class Register extends Component {

    constructor(props){
        super(props);
        this.state = {
            regName              : '',
            regAdd1              : '',
            regAdd2              : '',
            regState             : '',
            regZipCode           : '',
            regCity              : '',
            regPhone             : ''
        };
        // add bindings .... ugh..
        this.changeRegAdd1 = this.changeRegAdd1.bind(this);
        this.changeRegAdd2 = this.changeRegAdd2.bind(this);
        //Similary binding for other handlers...
    }

    // add individual field change handlers ... ugh...
    changeRegName(e) {
        this.setState({regName:e.target.value});
    }

    changeRegAdd1(e) {
        this.setState({regAdd1:e.target.value});
    }

    changeRegAdd2(e) {
        this.setState({regAdd2:e.target.value});
    }

    changeRegState(e) {
        this.setState({regState:e.target.value});
    }

    // Similary for other change handler ....

    handleSubmit(e) {
        e.preventDefault();
        // validate then do other stuff
    }

    render(){

        let registrationComp = (
                <div className="row">
                    <div className="col-md-12">
                        <h3>Registration Form</h3>
                        <fieldset>
                              <div className="form-group">
                                <div className="col-xs-12">
                                    <label htmlFor="regName">Name</label>
                                    <input type="text" placeholder="Name"
                                        onChange={this.changeregName} value = {this.state.regName} className="form-control" required autofocus/>
                                </div>
                              </div>

                              <div className="form-group">
                                <div className="col-xs-12">
                                    <label htmlFor="regAdd1">Address Line1</label>

                                    <input
                                        type        = "text"
                                        placeholder = "Address Line1"
                                        onChange    = {this.changeregAdd1}
                                        value       = {this.state.regAdd1}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    <input
                                        type        = "text"
                                        placeholder = "Address Line2"
                                        onChange    = {this.changeregAdd2}
                                        value       = {this.state.regAdd2}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />
                                </div>
                              </div>

                              <div className="form-group">
                                <div className="col-xs-6">
                                    <label htmlFor="regState">State</label>
                                    <input
                                        type        = "text"
                                        placeholder = "State"
                                        onChange    = {this.changeregState}
                                        value       = {this.state.regState}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />
                                </div>
                                <div className="col-xs-6">
                                    <label htmlFor="regZipCode">Zip Code</label>
                                    <input
                                        type        = "text"
                                        placeholder = "Zip Code"
                                        onChange    = {this.changeregZipCode}
                                        value       = {this.state.regZipCode}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />
                                </div>
                              </div>

                              <div className="form-group">
                                <div className="col-xs-12">
                                    <label htmlFor="regCity">City</label>
                                    <input
                                        type        = "text"
                                        placeholder = "City"
                                        title       = "City"
                                        onChange    = {this.changeregCity}
                                        value       = {this.state.regCity}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />
                                </div>
                              </div>
                              {/* other form fields */}
                          </fieldset>
                      </div>
                    </div>
            );

            return  registrationComp;
    }
}
</code>```

答:
Take a look at how it's done in NeoForm:

data state is directly mapped to form fields

one onChange handler for the entire form

per-field (for example onBlur) and form (for example onSubmit) validation

plain object and Immutable state helpers

easy integration with Redux or any other state management solution

It uses context internally and really small and modular source code is easy to follow.

Body:
I have a react based form with more than 10 fields in it, I have states for those ten form fields (controlled component).

Most of these input fields are of type text only but other types fields will be added later.

Problem is that I need to write 10 change handlers for them to set state correctly and then add method bindings for each of them in constructor.

I am quite new to react and may be not aware about correct
  methodologies and techniques.

Please guide me to how to improve my current code structure and avoid writing boiler plates and repetitive error prone code.

My current Registration component is like below -

export default class Register extends Component {

    constructor(props){
        super(props);
        this.state = {
            regName              : '',
            regAdd1              : '',
            regAdd2              : '',
            regState             : '',
            regZipCode           : '',
            regCity              : '',
            regPhone             : ''
        };
        // add bindings .... ugh..
        this.changeRegAdd1 = this.changeRegAdd1.bind(this);
        this.changeRegAdd2 = this.changeRegAdd2.bind(this);
        //Similary binding for other handlers...
    }

    // add individual field change handlers ... ugh...
    changeRegName(e) {
        this.setState({regName:e.target.value});
    }

    changeRegAdd1(e) {
        this.setState({regAdd1:e.target.value});
    }

    changeRegAdd2(e) {
        this.setState({regAdd2:e.target.value});
    }

    changeRegState(e) {
        this.setState({regState:e.target.value});
    }

    // Similary for other change handler ....

    handleSubmit(e) {
        e.preventDefault();
        // validate then do other stuff
    }

    render(){

        let registrationComp = (

Registration Form

                        <fieldset>

                                    Name
                                    <input type="text" placeholder="Name"
                                        onChange={this.changeregName} value = {this.state.regName} className="form-control" required autofocus/>

                                    Address Line1

                                    <input
                                        type        = "text"
                                        placeholder = "Address Line1"
                                        onChange    = {this.changeregAdd1}
                                        value       = {this.state.regAdd1}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    <input
                                        type        = "text"
                                        placeholder = "Address Line2"
                                        onChange    = {this.changeregAdd2}
                                        value       = {this.state.regAdd2}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    State
                                    <input
                                        type        = "text"
                                        placeholder = "State"
                                        onChange    = {this.changeregState}
                                        value       = {this.state.regState}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    Zip Code
                                    <input
                                        type        = "text"
                                        placeholder = "Zip Code"
                                        onChange    = {this.changeregZipCode}
                                        value       = {this.state.regZipCode}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    City
                                    <input
                                        type        = "text"
                                        placeholder = "City"
                                        title       = "City"
                                        onChange    = {this.changeregCity}
                                        value       = {this.state.regCity}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                              {/* other form fields */}
                          </fieldset>

            );

            return  registrationComp;
    }
}


问:
How to do a filtered aggregate with Django's ORM
I have a Django model like:

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

    name = models.CharField(max_length=10)

class Topic(models.Model):

    name = models.CharField(max_length=10)

class Annotator(models.Model):

    post = models.ForeignKey(Post, related_name='annotations')

    topic = models.ForeignKey(Topic)

    name = models.CharField(max_length=10)
</code>```

How do I find all Post records that don't have an associated Annotator record with a specific topic and Annotator name value?

Without the topic and name filtering criteria, the Django query would look like:

```<code>qs = Post.objects.all()
qs = qs.annotate(annotations_count=Count('annotations'))
qs = qs.filter(annotations_count=0)
</code>```

but what I want to do would be something like:

```<code>qs = Post.objects.all()
qs = qs.annotate(annotations_count=Count('annotations' where name='annotator1' and topic='topic1'))
qs = qs.filter(annotations_count=0)
</code>```

which obviously isn't legal.

I'm currently using .raw() to perform a traditional LEFT OUTER JOIN so I can do this filtering in the WHERE clause, but this prevents me from re-using a lot of code and filters I've rewritten using the Django ORM.

How do you add filtering criteria to Django's .annotate() method, or otherwise achieve the same result?

I'm using Django 1.11.

答:
How do I find all Post records that don't have an associated Annotator record with a specific topic and Annotator name value?

If I understand your question, you are looking for .exclude():

```<code>Post.objects.exclude(
    annotator__topic='topic1',
    annotator__name='annotator1'
)
</code>```

Body:
I have a Django model like:

class Post(models.Model):

    name = models.CharField(max_length=10)

class Topic(models.Model):

    name = models.CharField(max_length=10)

class Annotator(models.Model):

    post = models.ForeignKey(Post, related_name='annotations')

    topic = models.ForeignKey(Topic)

    name = models.CharField(max_length=10)

How do I find all Post records that don't have an associated Annotator record with a specific topic and Annotator name value?

Without the topic and name filtering criteria, the Django query would look like:

qs = Post.objects.all()
qs = qs.annotate(annotations_count=Count('annotations'))
qs = qs.filter(annotations_count=0)

but what I want to do would be something like:

qs = Post.objects.all()
qs = qs.annotate(annotations_count=Count('annotations' where name='annotator1' and topic='topic1'))
qs = qs.filter(annotations_count=0)

which obviously isn't legal.

I'm currently using .raw() to perform a traditional LEFT OUTER JOIN so I can do this filtering in the WHERE clause, but this prevents me from re-using a lot of code and filters I've rewritten using the Django ORM.

How do you add filtering criteria to Django's .annotate() method, or otherwise achieve the same result?

I'm using Django 1.11.

Body:
How do I find all Post records that don't have an associated Annotator record with a specific topic and Annotator name value?

If I understand your question, you are looking for .exclude():

Post.objects.exclude(
    annotator__topic='topic1',
    annotator__name='annotator1'
)


问:
Having troubles pushing into an array which is a property of an object
I have this array called "players" which stores all the players, each element of this array contains each individual player stored as an object, and this player object contains a property called "time" which in it of itself is an array. When ever I try to push an integer into this time array, I get a "time.push() is not a function" error.

```<code>players[data.num].time.push(uptime());
</code>```

what I am attempting here is array[index].array.push()

This array is undefined and is declared like this.time = [];
The player objects were made by constructor function as well.

Here are the other arrays I mentioned before;

```<code>var players = [];
players.push(new Player(0,0,true));
</code>```

Player() is a constructor function that contains this.time = [];

Any help is appreciated.

答:
I base my answer upon that you have an array of objects with another array in each object. Then this should work.

```<code>var objs = [{array:[]},{array:[]},{array:[]}]

objs[0].array.push("test");

console.log(objs)
</code>```

http://jsbin.com/romubeyoyu/edit?js,console

Body:
I have this array called "players" which stores all the players, each element of this array contains each individual player stored as an object, and this player object contains a property called "time" which in it of itself is an array. When ever I try to push an integer into this time array, I get a "time.push() is not a function" error.

players[data.num].time.push(uptime());

what I am attempting here is array[index].array.push()

This array is undefined and is declared like this.time = [];
The player objects were made by constructor function as well.

Here are the other arrays I mentioned before;

var players = [];
players.push(new Player(0,0,true));

Player() is a constructor function that contains this.time = [];

Any help is appreciated.

Body:
I base my answer upon that you have an array of objects with another array in each object. Then this should work.

var objs = [{array:[]},{array:[]},{array:[]}]

objs[0].array.push("test");

console.log(objs)

http://jsbin.com/romubeyoyu/edit?js,console


问:
Angular/Firebase app ~10seconds until change shows in browser
I am running into a strange angular 4 refresh issue when using firebase authentication.

I was able to reproduce the issue in a simple app that should show if a user was able to login using firebase auth (Google account) or not.

The issue is, that the result message gets printed in the console, but it does not get displayed in the browser right away. After around 10 seconds the screen refreshes and the error message shows up.

How can I avoid this delay?

app.component.ts

```<code>import {Component} from '@angular/core';
import {AuthService} from './auth-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  msg: string;

  constructor(private authService: AuthService) {}

  login() {
    this.authService.loginWithGoogle()
      .then(() => {
          console.log('success');
          this.msg = 'success';
        }
      )
      .catch((err) => {
         console.log('error:'+ err);
         this.msg = err.message;
      });
  }
}
</code>```

app.compontent.html

```<code><div>Error is: {{msg}}</div>
<button (click)="login()">
Login
</button>
</code>```

auth.service.ts

```<code>import {AngularFireAuth} from 'angularfire2/auth';
import * as firebase from 'firebase/app';

@Injectable()
export class AuthService {

constructor(private afAuth: AngularFireAuth) {
}

loginWithGoogle() {
     return this.afAuth.auth.signInWithPopup(new
firebase.auth.GoogleAuthProvider());
  }
}
</code>```

You can look at the issue here: https://jaidev1-27a1b.firebaseapp.com/

Use any google account for login.

UPDATE: This only happens with chrome. Using chrome 59

答: It is because of cache. Disable cache while debugging. </p>

Body:
I am running into a strange angular 4 refresh issue when using firebase authentication.

I was able to reproduce the issue in a simple app that should show if a user was able to login using firebase auth (Google account) or not.

The issue is, that the result message gets printed in the console, but it does not get displayed in the browser right away. After around 10 seconds the screen refreshes and the error message shows up.

How can I avoid this delay?

app.component.ts

import {Component} from '@angular/core';
import {AuthService} from './auth-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  msg: string;

  constructor(private authService: AuthService) {}

  login() {
    this.authService.loginWithGoogle()
      .then(() => {
          console.log('success');
          this.msg = 'success';
        }
      )
      .catch((err) => {
         console.log('error:'+ err);
         this.msg = err.message;
      });
  }
}

app.compontent.html

Error is: {{msg}}

<button (click)="login()">
Login
</button>

auth.service.ts

import {AngularFireAuth} from 'angularfire2/auth';
import * as firebase from 'firebase/app';

@Injectable()
export class AuthService {

constructor(private afAuth: AngularFireAuth) {
}

loginWithGoogle() {
     return this.afAuth.auth.signInWithPopup(new
firebase.auth.GoogleAuthProvider());
  }
}

You can look at the issue here: https://jaidev1-27a1b.firebaseapp.com/

Use any google account for login.

UPDATE: This only happens with chrome. Using chrome 59


问:
How to translate whole website by google transltion?
This is my code :

```<code><div id="wrap">
 ⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯
 ⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯
</div>

<script type="text/javascript">
  google.load("language", "1");
  google.setOnLoadCallback(submitChange);
  var wrap_text = '';
  function submitChange(){
   wrap_text = document.getElementById('wrap').innerHTML;
   google.language.translate(wrap_text, 'zh-CN', 'zh-TW', function(result) {
    var resultBody = document.getElementById('wrap');
    alert(result.translation);
    if (result.translation){
     resultBody.innerHTML = result.translation;
   }
    else {
    resultBody.innerHTML = wrap_text；

    }
   });
   return false;
  }

</script>
</code>```

it does not work, if I replace wrap_text to some words, it works.

who can help me, thanks!

答:
I think you have to escape it to work, at least that's what they did in the example code:

```<code>var sourceText = escape(document.getElementById("sourceText").innerHTML);
</code>```

See: http://code.google.com/apis/language/translate/v2/getting_started.html

Body:
This is my code :

 ⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯
 ⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯

it does not work, if I replace wrap_text to some words, it works.

who can help me, thanks!

Body:
I think you have to escape it to work, at least that's what they did in the example code:

var sourceText = escape(document.getElementById("sourceText").innerHTML);

See: http://code.google.com/apis/language/translate/v2/getting_started.html


问:
Laravel - get all records that contains a specific string
I'm trying to get a query that gives me every record that contains a specific string in a specific column( no matter if the first letter is uppercase or lowercase.

For example: The string I'm passing is test

And I have 30 records in my database. 5 of them have do contain test ( lowercase ) and 5 of them Test ( uppercase ) . The 20 other records are useless, so I don't need them.

I've got some help yesterday but couldn't make it like I really want it and the output is also wrong.

Thats the code:

```<code>$search = $request['search'];
        $usergroups = Usergroups::where('name', 'like', '%' . str_slug($search, ' ') . '%')->simplePaginate(3);
</code>```

$search is a variable that contains the string I want to search for.

If I want to search for Test, I get just every record back. No matter if it contains Test, test, or unicorn bla bla. I get just everything back.

Does someone knows a way to fix that? I've tried to write a custom paginate class but that haven't worked for me.

答:
I'm not so sure but I think there is an error with the class. If I output $usergroups I get this:

```<code>current_page    1
data:
   // my data
from    1
last_page   2
next_page_url   "http://blabla.de/test?page=2"
path    "http://blabla.de/test"
per_page    3
prev_page_url
to  3
total   5
</code>```

You can clearly see that there is a total of 5 items ( and thats true ), and there are 2 pages. Thats also true cause I've set the pagination to paginate(3).

If I output the links in my blade I get something like this:

But if I click on "2" - to get to the last page, I don't know why but the links change immediately to 1-7.

So before I want to change the pagination link, I get the right amound of items, but if I change to ?page=2, I get all the items in my table. I don't know why but maybe thats a mistake by laravel. I also tried it with laravel 5.3 ( currently 5.4 ) but got the same problem. If I look into the phpmyadmin query log and manually try the query out, I also get the perfect output. If I use ->get() instead of ->paginate(); I also get the right output. I have no clue anymore.

Body:
I'm trying to get a query that gives me every record that contains a specific string in a specific column( no matter if the first letter is uppercase or lowercase.

For example: The string I'm passing is test

And I have 30 records in my database. 5 of them have do contain test ( lowercase ) and 5 of them Test ( uppercase ) . The 20 other records are useless, so I don't need them.

I've got some help yesterday but couldn't make it like I really want it and the output is also wrong.

Thats the code:

$search = $request['search'];
        $usergroups = Usergroups::where('name', 'like', '%' . str_slug($search, ' ') . '%')->simplePaginate(3);

$search is a variable that contains the string I want to search for.

If I want to search for Test, I get just every record back. No matter if it contains Test, test, or unicorn bla bla. I get just everything back.

Does someone knows a way to fix that? I've tried to write a custom paginate class but that haven't worked for me.

Body:
I'm not so sure but I think there is an error with the class. If I output $usergroups I get this:

current_page    1
data:
   // my data
from    1
last_page   2
next_page_url   "http://blabla.de/test?page=2"
path    "http://blabla.de/test"
per_page    3
prev_page_url
to  3
total   5

You can clearly see that there is a total of 5 items ( and thats true ), and there are 2 pages. Thats also true cause I've set the pagination to paginate(3).

If I output the links in my blade I get something like this:

But if I click on "2" - to get to the last page, I don't know why but the links change immediately to 1-7.

So before I want to change the pagination link, I get the right amound of items, but if I change to ?page=2, I get all the items in my table. I don't know why but maybe thats a mistake by laravel. I also tried it with laravel 5.3 ( currently 5.4 ) but got the same problem. If I look into the phpmyadmin query log and manually try the query out, I also get the perfect output. If I use ->get() instead of ->paginate(); I also get the right output. I have no clue anymore.


问:
Error connecting to mysql database.
It might be a duplicate, but i went through all the solution that are suggested in other posts at stackoverflow but cannot find a solution.

```<code> <?php
$PDO= new PDO('mysql:host= 127.0.0.1; dbname = social_network; charset= utf8', 'root', '' );
$PDO-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>
</code>```

The error i am having is as follows:

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2019] Unknown character set in C:\xampp\htdocs\social_network\create_account.php:2 Stack trace: #0 C:\xampp\htdocs\social_network\create_account.php(2): PDO->__construct('mysql:host= 127...', 'root', '') #1 {main} thrown in C:\xampp\htdocs\social_network\create_account.php on line 2

I appreciate your quick asnwer.

答:
```<code>$host = '127.0.0.1';
$database = 'social_network';
$user = 'root';
$password = '';
$charset = 'utf8';
$options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false
    ];
$dsn = "mysql:host=$host;dbname=$database;charset=$charset";
$db = new PDO($dsn, $user, $password, $options);
</code>```

This should work! Check this url (https://phpdelusions.net/pdo) PDO is better explained there! Your issus is about the charset

Title: Error connecting to mysql database.

Body:
It might be a duplicate, but i went through all the solution that are suggested in other posts at stackoverflow but cannot find a solution.

 <?php
$PDO= new PDO('mysql:host= 127.0.0.1; dbname = social_network; charset= utf8', 'root', '' );
$PDO-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>

The error i am having is as follows:

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2019] Unknown character set in C:\xampp\htdocs\social_network\create_account.php:2 Stack trace: #0 C:\xampp\htdocs\social_network\create_account.php(2): PDO->__construct('mysql:host= 127...', 'root', '') #1 {main} thrown in C:\xampp\htdocs\social_network\create_account.php on line 2

I appreciate your quick asnwer.

Body:
$host = '127.0.0.1';
$database = 'social_network';
$user = 'root';
$password = '';
$charset = 'utf8';
$options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false
    ];
$dsn = "mysql:host=$host;dbname=$database;charset=$charset";
$db = new PDO($dsn, $user, $password, $options);

This should work! Check this url (https://phpdelusions.net/pdo) PDO is better explained there! Your issus is about the charset


问:
html-webpack-plugin not writing to index.html
I'm trying to use html-webpack-plugin to inject my dependencies into my global html template, but so far every time I build, it comes back blank, like so:

Child html-webpack-plugin for "index.html":

Not sure what's going wrong here, can anyone help? I'm using Gulp with Webpack and Angular2.

```<code>import HtmlWebpack from 'html-webpack-plugin'

const frontendLoader = {
    preloaders: {
        test: /\.ts$/,
        loader: 'tslint'
    },
    loaders: [{
        test: /\.ts$/,
        exclude: /node_modules/,
        loader: 'ts'
    }, {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel'
    }, {
        test: /\.html$/,
        loader: 'raw'
    }]
}
module.exports = {
    frontendConfig: {
        debug: true,
        entry: {
            initial: ['./src/js/initial/initial.js'],
            vendor: ['./src/js/app/vendor'],
            app: ['./src/js/app/index']
        },
        resolve: {
            extensions: ['', '.ts', '.js']
        },
        devtool: 'source-map',
        output: {
            filename: '[name].bundle.js'
        },
        plugins: [
            new HtmlWebpack({
                inject: 'head',
                template: './public/views/index.html'
            })
        ],
        module: frontendLoader
    }
}
</code>```

答:
As I see it, you are trying to include the content of your index.html to the head of the HTML file generated by the HTMLWebpackPlugin. However, I guess what you actually want is to insert the content into the body part.

Instead of

```<code>plugins: [
            new HtmlWebpack({
                inject: 'head',
                template: './public/views/index.html'
            })
        ]
</code>```

try

```<code>plugins: [
            new HtmlWebpack({
                inject: 'body',
                template: './public/views/index.html'
            })
        ]
</code>```

Body:
I'm trying to use html-webpack-plugin to inject my dependencies into my global html template, but so far every time I build, it comes back blank, like so:

Child html-webpack-plugin for "index.html":

Not sure what's going wrong here, can anyone help? I'm using Gulp with Webpack and Angular2.

import HtmlWebpack from 'html-webpack-plugin'

const frontendLoader = {
    preloaders: {
        test: /\.ts$/,
        loader: 'tslint'
    },
    loaders: [{
        test: /\.ts$/,
        exclude: /node_modules/,
        loader: 'ts'
    }, {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel'
    }, {
        test: /\.html$/,
        loader: 'raw'
    }]
}
module.exports = {
    frontendConfig: {
        debug: true,
        entry: {
            initial: ['./src/js/initial/initial.js'],
            vendor: ['./src/js/app/vendor'],
            app: ['./src/js/app/index']
        },
        resolve: {
            extensions: ['', '.ts', '.js']
        },
        devtool: 'source-map',
        output: {
            filename: '[name].bundle.js'
        },
        plugins: [
            new HtmlWebpack({
                inject: 'head',
                template: './public/views/index.html'
            })
        ],
        module: frontendLoader
    }
}

Body:
As I see it, you are trying to include the content of your index.html to the head of the HTML file generated by the HTMLWebpackPlugin. However, I guess what you actually want is to insert the content into the body part.

Instead of

plugins: [
            new HtmlWebpack({
                inject: 'head',
                template: './public/views/index.html'
            })
        ]

try

plugins: [
            new HtmlWebpack({
                inject: 'body',
                template: './public/views/index.html'
            })
        ]


问:
Java Keystore: Command "openssl" not found
I'm using Windows 7 64 bit and I'm trying to export the base64 encoded sha-hash of my Key with this command:

```<code>keytool -exportcert -alias [alias] -keystore [keystore]
| openssl sha1 -binary
| openssl base64
</code>```

Unfortunatly I get the error

```<code>command "openssl" not found
</code>```

I also tried to use other commands, that were shown on this website: http://www.startux.de/index.php/java/44-dealing-with-java-keystores
But I always get the error, that openssl cannot be found. What am I missing?

Solution

I was missing openssl. And I downloaded it here: deanlee.cn/programming/openssl-for-windows

答: Is this on Windows or Linux? These looks like a typical Linux command line and I am pretty sure openssl comes by default on most systems. On windows you may need to look at alternative commands to run or install Cygwin.</p>

Body:
I'm using Windows 7 64 bit and I'm trying to export the base64 encoded sha-hash of my Key with this command:

keytool -exportcert -alias [alias] -keystore [keystore]
| openssl sha1 -binary
| openssl base64

Unfortunatly I get the error

command "openssl" not found

I also tried to use other commands, that were shown on this website: http://www.startux.de/index.php/java/44-dealing-with-java-keystores
But I always get the error, that openssl cannot be found. What am I missing?

Solution

I was missing openssl. And I downloaded it here: deanlee.cn/programming/openssl-for-windows


问:
Present VC modally above other VC - both touchable
I want to show a VC above another VC but want both to be clickable and responsible.

I have a textfield which prints out the string behind each @-sign.

When a @ is written I have a VC which pops up with a small tableview above the first VC which should later represent the users who have a name containing the printed out string.

I need the first vc to still be responsible, because currently I can't click buttons and textfields on the first VC when the second one pops up even though I can see everything ( set the background to clear).

```<code>        if commentTextField.text!.contains("@"){
        print("changed textField")
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "suggestedUsersViewController") as  UIViewController!
        vc?.modalPresentationStyle = .overCurrentContext
        vc?.view.backgroundColor = .clear

        present(vc!, animated: true, completion: nil)

    }
</code>```

How I get the post behind the @- sign

```<code>        let caption = commentTextField.text

    let words = caption?.components(separatedBy: CharacterSet.whitespacesAndNewlines)
    for var word in words! {
            if word.hasPrefix("@") {
                word = word.trimmingCharacters(in: CharacterSet.punctuationCharacters)

                print("wort ist", word)
            }
    }
</code>```

Currently it just pops over the first vc and then its no longer clickable and I cannot change the textfield

Pictures

答:
present function will make the second view controller cover the whole page and you will no longer have access from screen to the view controller below the top one.

To accomplish your goal, you need to put a UITableView on a view, then keep showing or hiding the view. If you really want another view controller, you can create a containing view and have a embed segue to another view controller, like this

Body:
I want to show a VC above another VC but want both to be clickable and responsible.

I have a textfield which prints out the string behind each @-sign.

When a @ is written I have a VC which pops up with a small tableview above the first VC which should later represent the users who have a name containing the printed out string.

I need the first vc to still be responsible, because currently I can't click buttons and textfields on the first VC when the second one pops up even though I can see everything ( set the background to clear).

        if commentTextField.text!.contains("@"){
        print("changed textField")
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "suggestedUsersViewController") as  UIViewController!
        vc?.modalPresentationStyle = .overCurrentContext
        vc?.view.backgroundColor = .clear

        present(vc!, animated: true, completion: nil)

    }

How I get the post behind the @- sign

        let caption = commentTextField.text

    let words = caption?.components(separatedBy: CharacterSet.whitespacesAndNewlines)
    for var word in words! {
            if word.hasPrefix("@") {
                word = word.trimmingCharacters(in: CharacterSet.punctuationCharacters)

                print("wort ist", word)
            }
    }

Currently it just pops over the first vc and then its no longer clickable and I cannot change the textfield

Pictures


问:
MySQL 'Order By' - sorting alphanumeric correctly
I want to sort the following data items in the order they are presented below (numbers 1-12):

```
1
2
3
4
5
6
7
8
9
10
11
12```

However, my query - using order by xxxxx asc sorts by the first digit above all else:

```
1
10
11
12
2
3
4
5
6
7
8
9```

Any tricks to make it sort more properly?

Further, in the interest of full disclosure, this could be a mix of letters and numbers (although right now it is not), e.g.:

```
A1
534G
G46A
100B
100A
100JE
```

etc....

Thanks!

update: people asking for query

```<code>select * from table order by name asc
</code>```

答:
This should sort alphanumeric field like:
1/ Number only, order by 1,2,3,4,5,6,7,8,9,10,11 etc...
2/ Then field with text like: 1foo, 2bar, aaa11aa, aaa22aa, b5452 etc...

```<code>SELECT  MyField
FROM MyTable
order by
    IF( MyField REGEXP '^-?[0-9]+$' = 0,
    9999999999 ,
    CAST(MyField AS DECIMAL)
    ), MyField
</code>```

The query check if the data is a number, if not put it to 9999999999 , then order first on this column, then order on data with text

Good luck!

ContentLicense: CC BY-SA 4.0

Body:
I want to sort the following data items in the order they are presented below (numbers 1-12):

1
2
3
4
5
6
7
8
9
10
11
12

However, my query - using order by xxxxx asc sorts by the first digit above all else:

1
10
11
12
2
3
4
5
6
7
8
9

Any tricks to make it sort more properly?

Further, in the interest of full disclosure, this could be a mix of letters and numbers (although right now it is not), e.g.:

A1
534G
G46A
100B
100A
100JE

etc....

Thanks!

update: people asking for query

select * from table order by name asc

Body:
This should sort alphanumeric field like:
1/ Number only, order by 1,2,3,4,5,6,7,8,9,10,11 etc...
2/ Then field with text like: 1foo, 2bar, aaa11aa, aaa22aa, b5452 etc...

SELECT  MyField
FROM MyTable
order by
    IF( MyField REGEXP '^-?[0-9]+$' = 0,
    9999999999 ,
    CAST(MyField AS DECIMAL)
    ), MyField

The query check if the data is a number, if not put it to 9999999999 , then order first on this column, then order on data with text

Good luck!


问:
Normalize a vector where the dot product equals 1 in Python?
I already know, and understand how I can normalize an array in Python, but I am trying to create a random array.  I want the dot product of the array (when I dot it with itself) to equal a value of one.  I have been looking for a way to do this for over twelve hours now, and can not find a way.  Any help or ideas would be great.  Thank you. </p>

答:
This will do the job:

```<code>import numpy as  np
x=np.random.randn(5)
x=x/np.linalg.norm(x)
</code>```

Then np.dot(x,x) is 1.0

Body:
This will do the job:

import numpy as  np
x=np.random.randn(5)
x=x/np.linalg.norm(x)

Then np.dot(x,x) is 1.0


问:
How to get User Followers in Instagram API?
I am using instagram API(oauth) and I able to get the access token and user information using

https://api.instagram.com/oauth/authorize/client_id='.$client_id.'&redirect_uri='.$redirect_url .'&response_type=code'

and https://api.instagram.com/oauth/access_token by passing client id, secret and redirect_uri.

when I make the first call
(https://api.instagram.com/oauth/authorize/client_id='.$client_id.'&redirect_uri='.$redirect_url .'&response_type=code') it gives me the array of access_token and user.

My question is what should I do to get the followers of the user ?

I know I have to use https://api.instagram.com/v1/users/{user-id}/follows?access_token=ACCESS-TOKEN but for some reason I am getting the error message

```<code>{
 "code": 400,
 "error_type": "OAuthException",
 "error_message": "Only response type \"code\" and \"token\" is allowed"
}
</code>```

Please help!!!

答:
As per new update you have to use access token instead of client_id

this is my response
{"data": {"id": "1829538552", "username": "mypageusername", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11084945_1580533368872297_743341297_a.jpg", "full_name": "pagename Nation", "bio": "For Business/Ads\add@gmail.com\nKik: @test", "website": "https://carsmydrug.myshopify.com/", "counts": {"media": 371, "follows": 6464, "followed_by": 171599}}, "meta": {"code": 200}}

this is url to get above response
https://api.instagram.com/v1/users/1829538552/?access_token=1829538552.81758e8.5d303d9dd94543efb17684dee425cb5a

You have to get access token and you can only check follower list of user that accepted your of sandbox user

Body:
I am using instagram API(oauth) and I able to get the access token and user information using

https://api.instagram.com/oauth/authorize/client_id='.$client_id.'&redirect_uri='.$redirect_url .'&response_type=code'

and https://api.instagram.com/oauth/access_token by passing client id, secret and redirect_uri.

when I make the first call
(https://api.instagram.com/oauth/authorize/client_id='.$client_id.'&redirect_uri='.$redirect_url .'&response_type=code') it gives me the array of access_token and user.

My question is what should I do to get the followers of the user ?

I know I have to use https://api.instagram.com/v1/users/{user-id}/follows?access_token=ACCESS-TOKEN but for some reason I am getting the error message

{
 "code": 400,
 "error_type": "OAuthException",
 "error_message": "Only response type \"code\" and \"token\" is allowed"
}

Please help!!!


问:
Swift: How do I add an image/text on top of my AVPlayerLayer for it to be a part of the video?
I am really struggling with getting an image or text to actually be a part of my video, similar to Snapchats add text/stickers feature. I don't want it to just sit on top of my video but actually be on the video itself so when it is saved, it shows. Any help would be highly appreciated and marked as answer. Thanks guys. Code is below...</p>

```<code>import UIKit
import AVFoundation
import AVKit
import Photos

class VideoViewController: UIViewController {

    override var prefersStatusBarHidden: Bool { return true }

    var videoURL: URL
    var player: AVPlayer?
    var playerLayer: AVPlayerLayer?

    init(videoURL: URL) {
        self.videoURL = videoURL
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        UIApplication.shared.keyWindow?.backgroundColor = .black
        self.view.backgroundColor = .black

        self.player = AVPlayer(url: videoURL)
        self.playerLayer = AVPlayerLayer(player: self.player)
        self.playerLayer?.frame = self.view.frame
        self.playerLayer?.backgroundColor = UIColor.black.cgColor
        self.view.layer.addSublayer(playerLayer!)

        guard player != nil else { return }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        player?.play()
    }
</code>```

答:
For preview you can just add CALayers or UIViews on the top of AVPlayerLayer, if You have CAAnimations on that layers You can use AVSynchronizedLayer. See docs for more info

For export you need to use AVVideoCompositionCoreAnimationTool. See docs for more info.

Here You can find a tutorial about usage of AVVideoCompositionCoreAnimationTool. (its in Objective-C, but I think it wouldn't be hard to translate it to swift)

Body:
I am really struggling with getting an image or text to actually be a part of my video, similar to Snapchats add text/stickers feature. I don't want it to just sit on top of my video but actually be on the video itself so when it is saved, it shows. Any help would be highly appreciated and marked as answer. Thanks guys. Code is below...

import UIKit
import AVFoundation
import AVKit
import Photos

class VideoViewController: UIViewController {

    override var prefersStatusBarHidden: Bool { return true }

    var videoURL: URL
    var player: AVPlayer?
    var playerLayer: AVPlayerLayer?

    init(videoURL: URL) {
        self.videoURL = videoURL
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        UIApplication.shared.keyWindow?.backgroundColor = .black
        self.view.backgroundColor = .black

        self.player = AVPlayer(url: videoURL)
        self.playerLayer = AVPlayerLayer(player: self.player)
        self.playerLayer?.frame = self.view.frame
        self.playerLayer?.backgroundColor = UIColor.black.cgColor
        self.view.layer.addSublayer(playerLayer!)

        guard player != nil else { return }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        player?.play()
    }


问:
Send Post Request over Cordova InAppBrowser
I am developing a cordova hybrid app (currently for android) and using the InAppBrowswer-Plugin.

I want to open a web page and login there using a post request (as it is currently done via Java in an actual Android application).

Somehow this does not work though and I cannot figure out why. This is the code I am using:

```<code>var ref = cordova.InAppBrowser.open("www.thesite.dummy", "_blank", "location=yes");

var postAsString = 'var xhttp = new XMLHttpRequest();'+
    'xhttp.open("POST", "'+url+'", true);'+
    'xhttp.onreadystatechange = function() {if (xhttp.readyState == 4 && xhttp.status == 200) {alert("it worked")}};'+
    'xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");'+
    'xhttp.send("username=dummyUser&password=dummyPW")'
console.log(postAsString);

ref.executeScript({"code":postAsString});
</code>```

As you can see I also console.log my "postAsString". If I copy this string and execute it in the console of www.thesite.dummy it actually works, but not in the InAppBrwoser

答:
Just to help anyone who find this question through Google, the solution is described at that answer as said in the question comments.

The code, changing values for the specific context is below:

```<code>var pageContent = '<html><head></head><body><form id="loginForm" action="www.thesite.dummy" method="post">' +
'<input type="hidden" name="username" value="dummyUser">' +
'<input type="hidden" name="password" value="dummyPW">' +
'</form> <script type="text/javascript">document.getElementById("loginForm").submit();</script></body></html>';
var pageContentUrl = 'data:text/html;base64,' + btoa(pageContent);

var browserRef = window.cordova.InAppBrowser.open(
    pageContentUrl ,
    "_blank",
    "hidden=no,location=no,clearsessioncache=yes,clearcache=yes"
);
</code>```

Body:
I am developing a cordova hybrid app (currently for android) and using the InAppBrowswer-Plugin.

I want to open a web page and login there using a post request (as it is currently done via Java in an actual Android application).

Somehow this does not work though and I cannot figure out why. This is the code I am using:

var ref = cordova.InAppBrowser.open("www.thesite.dummy", "_blank", "location=yes");

var postAsString = 'var xhttp = new XMLHttpRequest();'+
    'xhttp.open("POST", "'+url+'", true);'+
    'xhttp.onreadystatechange = function() {if (xhttp.readyState == 4 && xhttp.status == 200) {alert("it worked")}};'+
    'xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");'+
    'xhttp.send("username=dummyUser&password=dummyPW")'
console.log(postAsString);

ref.executeScript({"code":postAsString});

As you can see I also console.log my "postAsString". If I copy this string and execute it in the console of www.thesite.dummy it actually works, but not in the InAppBrwoser

Body:
Just to help anyone who find this question through Google, the solution is described at that answer as said in the question comments.

The code, changing values for the specific context is below:

var pageContent = '<html><head></head><body><form id="loginForm" action="www.thesite.dummy" method="post">' +
'<input type="hidden" name="username" value="dummyUser">' +
'<input type="hidden" name="password" value="dummyPW">' +
'</form> <script type="text/javascript">document.getElementById("loginForm").submit();</script></body></html>';
var pageContentUrl = 'data:text/html;base64,' + btoa(pageContent);

var browserRef = window.cordova.InAppBrowser.open(
    pageContentUrl ,
    "_blank",
    "hidden=no,location=no,clearsessioncache=yes,clearcache=yes"
);


问:
Pattern to initialize a function when angular component launch
Recently I had initialize a function when the angular component launch.

I had seen this comment and I'd like to know if is it a good pattern or could be better declare the function and call it after such the code below:

angular.module('app').controller('control',[...,
  function(){
    ...
    var init = function () {
      //what i wish run on launch
    };

    // function call to launch
    init();

  }
)
```

<p>or as mentioned in comment:</p>

<pre class="lang-js prettyprint-override"><code>(function(){
    //code to run
}());
</code>```

What do you have been used or even are there known problems when use this last approach?

答:
Till angular 1.4.x john Papa style guides preferred to use 1st approach to call init function at the end by ensuring everything got initialize before. I recommend the same.

You can't consider a second option here. It's an IIFE, its more likely to define your function in isolated scope instead of declaring them in global.

Apart from that these days if you're specifically talking about component then you should use $onInit angular component lifecycle hook to call initialisation code.

```<code>angular.module('app').controller('control',[...,
  function(){
    var vm = this;
    vm.$onInit = $onInit;

    function $onInit() {
      //what i wish run on launch
    };
  }
)
.component('myComponent', {
  controller: 'control',
  templateUrl: 'sometemplate.html'
})
</code>```

Body:
Recently I had initialize a function when the angular component launch.

I had seen this comment and I'd like to know if is it a good pattern or could be better declare the function and call it after such the code below:

angular.module('app').controller('control',[...,
  function(){
    ...
    var init = function () {
      //what i wish run on launch
    };

    // function call to launch
    init();

  }
)

or as mentioned in comment:

(function(){
    //code to run
}());

What do you have been used or even are there known problems when use this last approach?

Body:
Till angular 1.4.x john Papa style guides preferred to use 1st approach to call init function at the end by ensuring everything got initialize before. I recommend the same.

You can't consider a second option here. It's an IIFE, its more likely to define your function in isolated scope instead of declaring them in global.

Apart from that these days if you're specifically talking about component then you should use $onInit angular component lifecycle hook to call initialisation code.

angular.module('app').controller('control',[...,
  function(){
    var vm = this;
    vm.$onInit = $onInit;

    function $onInit() {
      //what i wish run on launch
    };
  }
)
.component('myComponent', {
  controller: 'control',
  templateUrl: 'sometemplate.html'
})


问:
Design of a Decentralized Twitter
Twitter is a popular social networking service where users can write short messages in a one-to-many fashion (you can read more about it at Wikipedia). I've been reading an interesting article by Alex Payne (former API Lead at Twitter), The Very Last Thing I’ll Write About Twitter, where he argues for a decentralized one-to-many communications mechanism...

From a programming perspective, how would this service be designed? I imagine it could be similar to email, where anyone can set up a mail server. However, one of the major motivations is to resist censorship; can the architecture be fully decentralized? It would involve a similar protocol to the open standards-based protocols behind email and IM; does such a protocol already exist? Should the design include aspects of an anonymity network such as Tor? Has an open-source initiative already begun for this?

I'm making this a community wiki, as these are rather open-ended questions about the design of a decentralized one-to-many communication service.

答: It's like email but with more of a graph-processing stack (following).</p>

Title: Design of a Decentralized Twitter