问:
Django bootstrap files not found
I have set up Django with bootstrap following some tutorials but even when I am doing the same as in the tutorials Django doesn't find the static files.

My Project has the following structure:

```<code>webshop
    shop
        migrations
        templates
        ...
    static
        css
            bootstrap.min.css
        ...
    webshop
        ...
    db.sqlite3
    manage.py
</code>```

In the data settings.py I have added

```<code>STATIC_URL = '/static/'
</code>```

And in the Index.html I load the static files with following code:

```<code><head>
        <title>Webshop</title>
        {% load staticfiles %}
        <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"/>
</head>
</code>```

But Django can't find the data bootstrap.min.css.

答:
in your HTML code add

```<code>{% load static %}
</code>```

and your setting.py add

```<code>STATIC_URL = "/static/"
STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
)
</code>```

Title: Django bootstrap files not found

Body:
I have set up Django with bootstrap following some tutorials but even when I am doing the same as in the tutorials Django doesn't find the static files.

My Project has the following structure:

webshop
    shop
        migrations
        templates
        ...
    static
        css
            bootstrap.min.css
        ...
    webshop
        ...
    db.sqlite3
    manage.py

In the data settings.py I have added

STATIC_URL = '/static/'

And in the Index.html I load the static files with following code:

        <title>Webshop</title>
        {% load staticfiles %}
        <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"/>

But Django can't find the data bootstrap.min.css.

Body:
in your HTML code add

{% load static %}

and your setting.py add

STATIC_URL = "/static/"
STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
)


来源: stackexchange

问:
Access Violation Exception in Unmanaged Code when using OdbcDataAdapter.Fill in Background Thread
I am experimenting with Threads to try and learn a bit about them. I wrote a little WPF app that starts uses a background Thread to poll an ODBC source on an interval, retrieving the data into a DataTable via OdbcDataAdapter.Fill and writing it to a CSV file.

Every so often, the app encounters an AccessViolationException. The timing varies, sometimes it can run for a few days before encountering it, other times just a day. So far it has not ever happened as a result of UI interaction.

The Thread (LoggingThread in the stack trace) is to have MainWindow control it via calls to MyApp which manages LoggingThread via ManualResetEvents and CancellationTokenSource. LoggingThread itself is runs a continuous loop managed by the aforementioned ManualResetEvents.

I've used DataAdapter successfully in other single-threaded projects before, so I guess it could be something about how I'm handling LoggingThread that's setting up conditions for this exception to occur, because the polling code is quite simple:

if (!this._cancelToken.IsCancellationRequested)
{
    using (OdbcConnection conn = new OdbcConnection(this.connStr))
    {
        using (var adapter = new OdbcDataAdapter(this.sql, conn))
        {
            try
            {
            int rows = adapter.Fill(table);
            }
            catch() { // log Exception(s) }
            finally
            {
                adapter.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }
        conn.Close();
    }
}
```

<p>What could cause this? Is there some mitigating action that I can take to avoid it? </p>

<p>Let me know if you need other code snippets to more fully understand this.</p>

<p>The exception details:</p>

```Exception Info: System.AccessViolationException
Stack:
   at System.Data.Common.UnsafeNativeMethods.SQLMoreResults(System.Data.Odbc.OdbcStatementHandle)
   at System.Data.Odbc.OdbcStatementHandle.MoreResults()
   at System.Data.Odbc.OdbcDataReader.NextResult(Boolean, Boolean)
   at System.Data.Odbc.OdbcDataReader.Close(Boolean)
   at System.Data.Odbc.OdbcDataReader.Dispose(Boolean)
   at System.Data.Common.DbDataReader.Dispose()
   at System.Data.Common.DbDataAdapter.FillInternal(System.Data.DataSet, System.Data.DataTable[], Int32, Int32, System.String, System.Data.IDbCommand, System.Data.CommandBehavior)
   at System.Data.Common.DbDataAdapter.Fill(System.Data.DataTable[], Int32, Int32, System.Data.IDbCommand, System.Data.CommandBehavior)
   at System.Data.Common.DbDataAdapter.Fill(System.Data.DataTable)
   at MyApp.LoggingThread.PollServer(System.Data.DataTable)
   at MyApp.LoggingThread.LoggingHandler()
   at MyApp.MyApp.<StartProcessing>b__0()
   at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
   at System.Threading.ExecutionContext.runTryCode(System.Object)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()
```

<p><strong>EDIT:</strong></p>

<p>Here is the LoggingHandler() method referenced in the stack trace, maybe it'll help.</p>

<pre class="lang-cs prettyprint-override"><code>DataTable table = new DataTable();
while (true)
{

   this.pauseEvent.WaitOne(Timeout.Infinite);
    if (this.stopEvent.WaitOne(0))
    {
        break;
    }

    PollServer(table);

    if (table != null && table.Rows.Count > 0)
    {
         WriteData(table);
         table.Clear();
    }
    else
    {
         table = new DataTable();
    }

    if (!this._cancelToken.IsCancellationRequested)
    {
        this.loopingEvent.WaitOne(this.delaySpan);
    }
}
</code>```

答:
I had the same issue, I was using "using" and still failed.  I realized that it was the following line,

```<code>Using cmd As System.Data.Odbc.OdbcCommand = objConn.CreateCommand()
End Using
</code>```

My issue was because I was passing the connection object through, to keep the connection open and I was creating lots of ObdcCommand objects...

ContentLicense: CC BY-SA 3.0

Body:
I am experimenting with Threads to try and learn a bit about them. I wrote a little WPF app that starts uses a background Thread to poll an ODBC source on an interval, retrieving the data into a DataTable via OdbcDataAdapter.Fill and writing it to a CSV file.

Every so often, the app encounters an AccessViolationException. The timing varies, sometimes it can run for a few days before encountering it, other times just a day. So far it has not ever happened as a result of UI interaction.

The Thread (LoggingThread in the stack trace) is to have MainWindow control it via calls to MyApp which manages LoggingThread via ManualResetEvents and CancellationTokenSource. LoggingThread itself is runs a continuous loop managed by the aforementioned ManualResetEvents.

I've used DataAdapter successfully in other single-threaded projects before, so I guess it could be something about how I'm handling LoggingThread that's setting up conditions for this exception to occur, because the polling code is quite simple:

if (!this._cancelToken.IsCancellationRequested)
{
    using (OdbcConnection conn = new OdbcConnection(this.connStr))
    {
        using (var adapter = new OdbcDataAdapter(this.sql, conn))
        {
            try
            {
            int rows = adapter.Fill(table);
            }
            catch() { // log Exception(s) }
            finally
            {
                adapter.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }
        conn.Close();
    }
}

What could cause this? Is there some mitigating action that I can take to avoid it?

Let me know if you need other code snippets to more fully understand this.

The exception details:

Exception Info: System.AccessViolationException
Stack:
   at System.Data.Common.UnsafeNativeMethods.SQLMoreResults(System.Data.Odbc.OdbcStatementHandle)
   at System.Data.Odbc.OdbcStatementHandle.MoreResults()
   at System.Data.Odbc.OdbcDataReader.NextResult(Boolean, Boolean)
   at System.Data.Odbc.OdbcDataReader.Close(Boolean)
   at System.Data.Odbc.OdbcDataReader.Dispose(Boolean)
   at System.Data.Common.DbDataReader.Dispose()
   at System.Data.Common.DbDataAdapter.FillInternal(System.Data.DataSet, System.Data.DataTable[], Int32, Int32, System.String, System.Data.IDbCommand, System.Data.CommandBehavior)
   at System.Data.Common.DbDataAdapter.Fill(System.Data.DataTable[], Int32, Int32, System.Data.IDbCommand, System.Data.CommandBehavior)
   at System.Data.Common.DbDataAdapter.Fill(System.Data.DataTable)
   at MyApp.LoggingThread.PollServer(System.Data.DataTable)
   at MyApp.LoggingThread.LoggingHandler()
   at MyApp.MyApp.<StartProcessing>b__0()
   at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
   at System.Threading.ExecutionContext.runTryCode(System.Object)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()

EDIT:

Here is the LoggingHandler() method referenced in the stack trace, maybe it'll help.

DataTable table = new DataTable();
while (true)
{

   this.pauseEvent.WaitOne(Timeout.Infinite);
    if (this.stopEvent.WaitOne(0))
    {
        break;
    }

    PollServer(table);

    if (table != null && table.Rows.Count > 0)
    {
         WriteData(table);
         table.Clear();
    }
    else
    {
         table = new DataTable();
    }

    if (!this._cancelToken.IsCancellationRequested)
    {
        this.loopingEvent.WaitOne(this.delaySpan);
    }
}

Body:
I had the same issue, I was using "using" and still failed.  I realized that it was the following line,

Using cmd As System.Data.Odbc.OdbcCommand = objConn.CreateCommand()
End Using

My issue was because I was passing the connection object through, to keep the connection open and I was creating lots of ObdcCommand objects...

ContentLicense: CC BY-SA 4.0


问:
Create third column from 2 columns in SQL Server
How can I show a column where the values from the first column completes the missing values of the second column?

I want this result (red marked column):

答:
```<code>Select Column1, Column2, Coalesce(column2, Column1)
</code>```

That's assuming ALL you care about is column2 UNLESS there's a value in column1, at which point you want column1.

Your question's not overtly clear.

Body:
Select Column1, Column2, Coalesce(column2, Column1)

That's assuming ALL you care about is column2 UNLESS there's a value in column1, at which point you want column1.

Your question's not overtly clear.


问:
Finding the complexity - Swift
What would the complexity (Big-O notation) for the following function:

```<code>func sortList(_ thresholdValue: Int) -> [Int] {
    var currentValue = thresholdValue
    //Values is an array of integers - [Int]
    var valArr = values.sorted { $0 > $1 } //should be a merge sort O(nlogn)

    for i in 0...valArr.count-1 {
        if valArr[i] < currentValue {
            currentValue = currentValue - valArr[i]

        } else {
            let tempArr = filter(valArr[0...i-1], currentValue) // O(n) - array splicing

            if tempArr.count > 0, let updatedValue = tempArr.first {
                currentValue = currentValue - updatedValue

                valArr = updateArr(array: valArr, fromIndex: valArr.index(of: updatedValue)!, toIndex: i)

                currentValue = thresholdValue

            } else {
                currentValue = thresholdValue - valArr[i]

            }
        }
    }

    return valArr
}

func updateArr<T>(array: Array<T>, fromIndex: Int, toIndex: Int) -> Array<T>{
    var arr = array
    let element = arr.remove(at: fromIndex) // O(n)
    arr.insert(element, at: toIndex) // O(n)

    return arr
}

func filter(_ tempArr:ArraySlice<Int>,_ currentValue : Int) -> [Int]{
    for value in tempArr { // O(n)
        if let index = values.index(of: value) {
            tempArr.remove(at: index) // O(n)
        }
    }

    return tempArr.filter { $0 <= currentValue }.sorted { $0 > $1 } //O(n) O(mlogm)
}
</code>```

The above function tries to rearrange an of integers such that the sequence (not a subarray) of elements sum up to a value less than or equal to k. Once the sequence completes, a new sequence (in the same array) sums to a value less than or equal to k.   I have added the possible complexity for each execution possible (not O(1)).

答:
I believe the structure of your code can be viewed more simply like this:

```<code>sort values (O(nlogn) operation)
loop over values (O(n) operation)
  if some condition is satisfied
     perform O(1) operation
  else
     perform O(n) operation
     if some condition is satisfied
       perform O(n) operation (updateArr)
     else
       perform O(1) operation
</code>```

First you perform a sort, then you loop over your input and perform O(n) operations in that loop based on some conditions. The worst case in this situation is if you perform any number of the O(n) operations inside your loop a number of times related to your input size. Your loop's time complexity in this case would be O(n * (n-m)) where m is a non-constant number related to your input size which is the number of times you do not perform the O(n) operations in your loop. This simplifies to O(n^2 - n*m), which is O(n^2). Your loop's complexity is larger than that of your sort, so your final complexity is O(n^2).

Title: Finding the complexity - Swift

Body:
What would the complexity (Big-O notation) for the following function:

func sortList(_ thresholdValue: Int) -> [Int] {
    var currentValue = thresholdValue
    //Values is an array of integers - [Int]
    var valArr = values.sorted { $0 > $1 } //should be a merge sort O(nlogn)

    for i in 0...valArr.count-1 {
        if valArr[i] < currentValue {
            currentValue = currentValue - valArr[i]

        } else {
            let tempArr = filter(valArr[0...i-1], currentValue) // O(n) - array splicing

            if tempArr.count > 0, let updatedValue = tempArr.first {
                currentValue = currentValue - updatedValue

                valArr = updateArr(array: valArr, fromIndex: valArr.index(of: updatedValue)!, toIndex: i)

                currentValue = thresholdValue

            } else {
                currentValue = thresholdValue - valArr[i]

            }
        }
    }

    return valArr
}

func updateArr<T>(array: Array<T>, fromIndex: Int, toIndex: Int) -> Array<T>{
    var arr = array
    let element = arr.remove(at: fromIndex) // O(n)
    arr.insert(element, at: toIndex) // O(n)

    return arr
}

func filter(_ tempArr:ArraySlice<Int>,_ currentValue : Int) -> [Int]{
    for value in tempArr { // O(n)
        if let index = values.index(of: value) {
            tempArr.remove(at: index) // O(n)
        }
    }

    return tempArr.filter { $0 <= currentValue }.sorted { $0 > $1 } //O(n) O(mlogm)
}

The above function tries to rearrange an of integers such that the sequence (not a subarray) of elements sum up to a value less than or equal to k. Once the sequence completes, a new sequence (in the same array) sums to a value less than or equal to k.   I have added the possible complexity for each execution possible (not O(1)).

Body:
I believe the structure of your code can be viewed more simply like this:

sort values (O(nlogn) operation)
loop over values (O(n) operation)
  if some condition is satisfied
     perform O(1) operation
  else
     perform O(n) operation
     if some condition is satisfied
       perform O(n) operation (updateArr)
     else
       perform O(1) operation

First you perform a sort, then you loop over your input and perform O(n) operations in that loop based on some conditions. The worst case in this situation is if you perform any number of the O(n) operations inside your loop a number of times related to your input size. Your loop's time complexity in this case would be O(n * (n-m)) where m is a non-constant number related to your input size which is the number of times you do not perform the O(n) operations in your loop. This simplifies to O(n^2 - n*m), which is O(n^2). Your loop's complexity is larger than that of your sort, so your final complexity is O(n^2).


问:
Angular - Apply style to element depending on sibling RouterLinkActive?
I do not have only one menu bar on my app that I need to be painted when the user navigates, I have another components too that needs to be painted as well. Can I achieve this just using routerLinkActive?

menu.html

```<code><menu>
  <a routerLink="page1" routerLinkActive="active">
      option1
  </a>
  <a routerLink="page2" routerLinkActive="active">
      option2
  </a>
</menu>
</code>```

This menu works great. But what I'm asking is how can I take advantage of routerLinkActive property placed in other HTML Tag. like:

main.html

```<code><main>
    <span class="title" routerLinkActive="active">My sub child part</span>
</main>
</code>```

答:
You could bind the state of the routerLinkActive directive to whether or not a class is applied to an element as follows:

```<code><a routerLink="page1" routerLinkActive="active" #rla="routerLinkActive"/>
<span [class.active-span]="rla.isActive"></span>

.active-span {
 background-color: red;
}
</code>```

#rla is a template variable
You can find more info about this use case of the RouterLinkActive directive in the docs

Body:
I do not have only one menu bar on my app that I need to be painted when the user navigates, I have another components too that needs to be painted as well. Can I achieve this just using routerLinkActive?

menu.html

<menu>

      option1

      option2

</menu>

This menu works great. But what I'm asking is how can I take advantage of routerLinkActive property placed in other HTML Tag. like:

main.html

    My sub child part

Body:
You could bind the state of the routerLinkActive directive to whether or not a class is applied to an element as follows:

<a routerLink="page1" routerLinkActive="active" #rla="routerLinkActive"/>
<span [class.active-span]="rla.isActive"></span>

.active-span {
 background-color: red;
}

#rla is a template variable
You can find more info about this use case of the RouterLinkActive directive in the docs


问:
maven include main project into test-jar
I have already created a test-jar with the maven-jar-plugin

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <goals>
                <goal>test-jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

But the test-jar needs the main classes to work, so how can I include them in the test-jar (creating something like a uber-test-jar)?

答:
Usually I import the dependency twice:

The regular one;

Test jar with scope = test.

So that you don't have problems with missing classes. However, if you don't need main sources(the first dependency) in your application and they are used only for tests, you can also switch scope of it to test.

```<code><scope>test</scope>
</code>```

Body:
I have already created a test-jar with the maven-jar-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <goals>
                <goal>test-jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

But the test-jar needs the main classes to work, so how can I include them in the test-jar (creating something like a uber-test-jar)?

Body:
Usually I import the dependency twice:

The regular one;

Test jar with scope = test.

So that you don't have problems with missing classes. However, if you don't need main sources(the first dependency) in your application and they are used only for tests, you can also switch scope of it to test.

<scope>test</scope>


问:
Power BI Visualization
Is it possible to create Power BI plots and data visualisations from data sets programmatically? I am wanting to use a csv file and create a chart on the fly. I couldn't really find much information online about doing this.

Thanks!

答:
Power BI supports R integration for data science and prediction. You may create a data frame and use csv data to do your analysis.

https://powerbi.microsoft.com/en-us/documentation/powerbi-desktop-r-scripts/

http://www.r-tutor.com/r-introduction/data-frame/data-import

Title: Power BI Visualization


问:
Firebase get all key
HI everyone I want to catch all the keys on my firebase database:

```<code>    Users-
         26dfg678-
                 Name: jack
                 Job: Farmer

         43jkhjh4-
                 Name: bill
                 Job: ICT
</code>```

I want to catch the id: 26dfg678 and 43jkhjh4 and put them in an array. This is my code:

```<code>    final DatabaseReference database_nomi = firebaseDatabase.getReference().child("Users");
            database_nomi.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                //here
                **name[0] = dataSnapshot.getKey();
                    Provee.setText(name[0]);**

                }
                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
</code>```

if i do this it takes only the last but i want all..

答:
To do this you need to read through your Firebase snapshot using a ValueEventListener (and addListenerForSingleValueEvent).

```<code>databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            int i = 0;
            for(DataSnapshot d : dataSnapshot.getChildren()) {
                name[i] = d.getKey();
                i++;
            }
        }
    }//onDataChange

    @Override
    public void onCancelled(DatabaseError error) {

    }//onCancelled
});
</code>```

This code uses a foreach to read all dataSnapshot children, saving its key in an array at each iteration.

Title: Firebase get all key

Body:
HI everyone I want to catch all the keys on my firebase database:

    Users-
         26dfg678-
                 Name: jack
                 Job: Farmer

         43jkhjh4-
                 Name: bill
                 Job: ICT

I want to catch the id: 26dfg678 and 43jkhjh4 and put them in an array. This is my code:

    final DatabaseReference database_nomi = firebaseDatabase.getReference().child("Users");
            database_nomi.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                //here
                **name[0] = dataSnapshot.getKey();
                    Provee.setText(name[0]);**

                }
                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

if i do this it takes only the last but i want all..

Body:
To do this you need to read through your Firebase snapshot using a ValueEventListener (and addListenerForSingleValueEvent).

databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            int i = 0;
            for(DataSnapshot d : dataSnapshot.getChildren()) {
                name[i] = d.getKey();
                i++;
            }
        }
    }//onDataChange

    @Override
    public void onCancelled(DatabaseError error) {

    }//onCancelled
});

This code uses a foreach to read all dataSnapshot children, saving its key in an array at each iteration.


答:
As per Django documentation you should specify the folder when the static file is not tied to a specific app:

```<code>STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',
]
</code>```

https://docs.djangoproject.com/en/1.11/howto/static-files/

In your case it could be:

```<code>STATIC_URL = '/static'/
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/path/to/webshop/static',
]
</code>```

Also please pay attention in the @kiran.koduru comment above regarding {% load static %}. This is the right way to load static files in Django templates.

Title: Django bootstrap files not found

Body:
As per Django documentation you should specify the folder when the static file is not tied to a specific app:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',
]

https://docs.djangoproject.com/en/1.11/howto/static-files/

In your case it could be:

STATIC_URL = '/static'/
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/path/to/webshop/static',
]

Also please pay attention in the @kiran.koduru comment above regarding {% load static %}. This is the right way to load static files in Django templates.


问:
What is the right way to include Qt headers?
So far I know several ways to #include Qt classes:

#include <QtModule>

This brings all classes of a specific module, for example QDomDocument, QDomElement, QDomNode and numerous others from #include <QtXml>.

#include <QClassName>

This adds declaration of a specific class one may want to use, e.g. QEvent, QStringList, QFile.

#include <qcstyleheader.h>

This has effect of the previous method, except for differently looking header name.

So I wonder, are there any other ways to #include Qt classes? Are they equivalent, or are some of them preferred to others because of some reasons? Does this depend on #include-ing inside a .cpp or a .h file? Does this influence compilation speed and size of the executable?

In short, what is the best way to go?

答: This seams to be a general include question. And the answer is simple : include only what you must. Otherwise you are slowing down the compilation. In the header, try to forward declare. If that is not enough, then include the header declaring the class.</p>

ContentLicense: CC BY-SA 2.5


答:
you can use case as below:

```<code>Select *, ThirdColumn = Case when SecondColumn is null then FirstColumn else SecondColumn End
   FourthColumn = Row_Number() over(partition by coalesce(SecondColumn,FirstColumn) order by Id)
   from yourtable
</code>```

or with coalesce

```<code>Select *, ThirdColumn = coalesce(SecondColumn,FirstColumn)
   FourthColumn = Row_Number() over(partition by coalesce(SecondColumn,FirstColumn) order by Id)
   from yourtable
</code>```

Title: Create third column from 2 columns in SQL Server

Body:
How can I show a column where the values from the first column completes the missing values of the second column?

I want this result (red marked column):

Body:
you can use case as below:

Select *, ThirdColumn = Case when SecondColumn is null then FirstColumn else SecondColumn End
   FourthColumn = Row_Number() over(partition by coalesce(SecondColumn,FirstColumn) order by Id)
   from yourtable

or with coalesce

Select *, ThirdColumn = coalesce(SecondColumn,FirstColumn)
   FourthColumn = Row_Number() over(partition by coalesce(SecondColumn,FirstColumn) order by Id)
   from yourtable


问:
Checking absence of attribute with cts:query
I have an XML fragment where I want to have different queries based in the existence of the id attribute:

```<code><author order="1"
        id="99999999"
        initials="A."
        given-names="Able"
        surname="Baker"
        fullname="Able Baker"/>
</code>```

I have tried:

```<code>let $first-query := if ($first)
                then cts:or-query((
                    cts:element-attribute-word-match(xs:QName("author"), xs:QName("given-names"), $first || "*", ("collation=http://marklogic.com/collation/codepoint")),
                    cts:element-attribute-word-match(xs:QName("author"), xs:QName("initials"), $first || "*", ("collation=http://marklogic.com/collation/codepoint"))
                     ))
                else ()

let $last-query := if ($last)
               then cts:element-attribute-word-match(xs:QName("author"), xs:QName("surname"), $last || "*", ("collation=http://marklogic.com/collation/codepoint"))
               else ()

let $author-no-id-query :=
    cts:and-query((
        cts:not-query(
            cts:element-attribute-value-query(xs:QName("author"), xs:QName("id"), "*")
        ),
        $first-query,
        $last-query
    ))

let $query :=    cts:element-query(xs:QName("author"),
                 cts:or-query(($author-no-id-query, $author-id-query
                    )))
</code>```

If the id exists, then a different query takes place and a match against the id occurs.  How do I detect an absence of an attribute in MarkLogic?

答:
I have inserted two test documents into the database:

```<code>xdmp:document-insert('/example.xml', <author order="1"
        id="99999999"
        initials="A."
        given-names="Able"
        surname="Baker"
        fullname="Able Baker"/>)

xdmp:document-insert('/example2.xml', <author order="1"
        initials="A."
        given-names="Able"
        surname="Baker"
        fullname="Able Baker"/>)
</code>```

And run the following query against these documents:

```<code>cts:search(fn:doc(),
cts:element-query(xs:QName('author'), cts:and-query((
  cts:not-query(cts:element-attribute-value-query(xs:QName('author'), xs:QName('id'), '*', ("wildcarded")))
 )
)))
</code>```

This search only matches the document where the ID attribute does not exist.

Body:
I have an XML fragment where I want to have different queries based in the existence of the id attribute:

<author order="1"
        id="99999999"
        initials="A."
        given-names="Able"
        surname="Baker"
        fullname="Able Baker"/>

I have tried:

let $first-query := if ($first)
                then cts:or-query((
                    cts:element-attribute-word-match(xs:QName("author"), xs:QName("given-names"), $first || "*", ("collation=http://marklogic.com/collation/codepoint")),
                    cts:element-attribute-word-match(xs:QName("author"), xs:QName("initials"), $first || "*", ("collation=http://marklogic.com/collation/codepoint"))
                     ))
                else ()

let $last-query := if ($last)
               then cts:element-attribute-word-match(xs:QName("author"), xs:QName("surname"), $last || "*", ("collation=http://marklogic.com/collation/codepoint"))
               else ()

let $author-no-id-query :=
    cts:and-query((
        cts:not-query(
            cts:element-attribute-value-query(xs:QName("author"), xs:QName("id"), "*")
        ),
        $first-query,
        $last-query
    ))

let $query :=    cts:element-query(xs:QName("author"),
                 cts:or-query(($author-no-id-query, $author-id-query
                    )))

If the id exists, then a different query takes place and a match against the id occurs.  How do I detect an absence of an attribute in MarkLogic?

Body:
I have inserted two test documents into the database:

xdmp:document-insert('/example.xml', <author order="1"
        id="99999999"
        initials="A."
        given-names="Able"
        surname="Baker"
        fullname="Able Baker"/>)

xdmp:document-insert('/example2.xml', <author order="1"
        initials="A."
        given-names="Able"
        surname="Baker"
        fullname="Able Baker"/>)

And run the following query against these documents:

cts:search(fn:doc(),
cts:element-query(xs:QName('author'), cts:and-query((
  cts:not-query(cts:element-attribute-value-query(xs:QName('author'), xs:QName('id'), '*', ("wildcarded")))
 )
)))

This search only matches the document where the ID attribute does not exist.


答:
Using CASE:

```<code>SELECT COL1 , COL2 , COL3 = CASE WHEN COL1 IS NOT NULL THEN COL1 ELSE COL2 END
FROM YOURTABLE;
</code>```

Using coalesce :

```<code>SELECT * ,coalesce(COL1,COL2) AS COL3
FROM YOURTABLE;
</code>```

Body:
Using CASE:

SELECT COL1 , COL2 , COL3 = CASE WHEN COL1 IS NOT NULL THEN COL1 ELSE COL2 END
FROM YOURTABLE;

Using coalesce :

SELECT * ,coalesce(COL1,COL2) AS COL3
FROM YOURTABLE;


问:
Prolog - count occurrence of number
I want to write predicate which can count all encountered number:

```<code>count(1, [1,0,0,1,0], X).
X = 2.
</code>```

I tried to write it like:

```<code>count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.
</code>```

Why doesn't work it?

答:
I solved it myself:</p>

```<code>count(_, [], 0).
count(Num, [H|T], X) :- Num \= H, count(Num, T, X).
count(Num, [H|T], X) :- Num = H, count(Num, T, X1), X is X1 + 1.
</code>```

Title: Prolog - count occurrence of number

Body:
I want to write predicate which can count all encountered number:

count(1, [1,0,0,1,0], X).
X = 2.

I tried to write it like:

count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.

Why doesn't work it?

Body:
I solved it myself:

count(_, [], 0).
count(Num, [H|T], X) :- Num \= H, count(Num, T, X).
count(Num, [H|T], X) :- Num = H, count(Num, T, X1), X is X1 + 1.


问:
Sleep in JQuery?
greetings all
i want to make JQuery sleep/wait for a second between two functions

```<code>$('#div1').hide();
//sleep or wait or for a sec
$("#div2").show();
</code>```

how to do so ?

答:
The following should do what you want:</p>

```<code>$("#div1").hide();
$("#div2").delay(1000).show(0);
</code>```

Title: Sleep in JQuery?

Body:
greetings all
i want to make JQuery sleep/wait for a second between two functions

$('#div1').hide();
//sleep or wait or for a sec
$("#div2").show();

how to do so ?

Body:
The following should do what you want:

$("#div1").hide();
$("#div2").delay(1000).show(0);


问:
Docusign API server templates local docs and tabs
I'm working on a DocuSign integration. I have the basics functional but can't seem to figure out how to merge a local document (PDF) with a server template such that tabs configured on the server template get used or overlaid on the passed document.

My template is defined on the server and I can use it directly from the web UI without issue (it's a W4 form). The template has three tabs (SSN, Sign here, and date) as you can see below. Accessing this template via it's ID using the API Explorer yields the following json

```<code>{
    "envelopeTemplateDefinition": {
        "templateId": "_redacted_",
        "name": "W4 3/13/2017",
        "shared": "true",
        "password": "",
        "description": "",
        "lastModified": "2017-06-05T18:45:28.4470000Z",
        "lastModifiedBy": {
            "userName": "Andrew",
            "userId": "_redacted_",
            "email": "my_email_address",
            "uri": "/users/_redacted_
        },
        "pageCount": 2,
        "uri": "/templates/_redacted_",
        "folderName": "Templates",
        "folderId": "_redacted_",
        "folderUri": "/folders/_redacted_",
        "owner": {
            "userName": "Andrew",
            "userId": "_redacted_",
            "email": "my_email_address"
        }
    },
    "documents": [
        {
            "documentId": "46677269",
            "uri": "/envelopes/_redacted_/documents/46677269",
            "name": "W4.pdf",
            "order": "1",
            "pages": "2",
            "display": "inline",
            "includeInDownload": "true",
            "signerMustAcknowledge": "no_interaction",
            "templateLocked": "false",
            "templateRequired": "false",
            "documentGroup": "content"
        }
    ],
    "emailSubject": "Please DocuSign: W4.pdf",
    "emailBlurb": "",
    "signingLocation": "online",
    "autoNavigation": "true",
    "envelopeIdStamping": "true",
    "authoritativeCopy": "false",
    "notification": {
        "reminders": {
            "reminderEnabled": "false",
            "reminderDelay": "0",
            "reminderFrequency": "0"
        },
        "expirations": {
            "expireEnabled": "true",
            "expireAfter": "120",
            "expireWarn": "0"
        }
    },
    "enforceSignerVisibility": "false",
    "enableWetSign": "true",
    "allowMarkup": "false",
    "allowReassign": "true",
    "recipients": {
        "signers": [
            {
                "defaultRecipient": "false",
                "tabs": {
                    "signHereTabs": [
                        {
                            "stampType": "signature",
                            "name": "SignHere",
                            "tabLabel": "Signature _redacted_",
                            "scaleValue": 1.0,
                            "optional": "false",
                            "documentId": "46677269",
                            "recipientId": "94043042",
                            "pageNumber": "1",
                            "xPosition": "193",
                            "yPosition": "682",
                            "tabId": "_redacted_",
                            "templateLocked": "false",
                            "templateRequired": "false"
                        }
                    ],
                    "dateSignedTabs": [
                        {
                            "name": "DateSigned",
                            "value": "",
                            "tabLabel": "Date Signed _redacted_",
                            "font": "lucidaconsole",
                            "fontColor": "black",
                            "fontSize": "size9",
                            "documentId": "46677269",
                            "recipientId": "94043042",
                            "pageNumber": "1",
                            "xPosition": "480",
                            "yPosition": "713",
                            "tabId": "_redacted_",
                            "templateLocked": "false",
                            "templateRequired": "false"
                        }
                    ],
                    "ssnTabs": [
                        {
                            "validationPattern": "",
                            "validationMessage": "",
                            "shared": "false",
                            "requireInitialOnSharedChange": "false",
                            "requireAll": "false",
                            "value": "",
                            "width": 144,
                            "required": "true",
                            "locked": "false",
                            "concealValueOnDocument": "true",
                            "disableAutoSize": "false",
                            "maxLength": 4000,
                            "tabLabel": "Text _redacted_",
                            "font": "lucidaconsole",
                            "fontColor": "black",
                            "fontSize": "size9",
                            "documentId": "46677269",
                            "recipientId": "94043042",
                            "pageNumber": "1",
                            "xPosition": "442",
                            "yPosition": "563",
                            "tabId": "_redacted_",
                            "templateLocked": "false",
                            "templateRequired": "false"
                        }
                    ]
                },
                "signInEachLocation": "false",
                "name": "",
                "email": "",
                "recipientId": "94043042",
                "accessCode": "",
                "requireIdLookup": "false",
                "routingOrder": "1",
                "note": "",
                "roleName": "New Employee",
                "deliveryMethod": "email",
                "templateLocked": "false",
                "templateRequired": "false",
                "inheritEmailNotificationConfiguration": "false"
            }
        ],
        "agents": [ ],
        "editors": [ ],
        "intermediaries": [ ],
        "carbonCopies": [ ],
        "certifiedDeliveries": [ ],
        "inPersonSigners": [ ],
        "recipientCount": "1"
    }
}
</code>```

What I want to do is apply this template to a PDF that's already partially filled out such that when the signer get's it the tabs defined in the server template are used for the sining.

As it stands now, there's nothing. Just the partially filled out PDF I passed in below as base64 data, with none of the server template tabs to fill out or sign. Here's my json for the API call (in PHP).

```<code>  $data = array (
        "emailBlurb" => "Test Email Body",
        "emailSubject" => "Test Email Subject",
        "status" => "sent",
        "compositeTemplates" => array(array(
            "document" => array(
                "documentId" => 46677269,
                "name" => $documentName,
                "documentBase64" => $document
            ),
            "serverTemplates" => array(array(

                "sequence" => 1,
                "templateId" => "_redacted_"
            )),
            "inlineTemplates" => array(array(
                "sequence" => 2,
                "recipients" => array(
                    "signers" => array(array(
                        "email" => $recipientEmail,
                        "name" => $recipientName,
                        "recipientId" => $recipientID,
                        "roleName" => "New Employee"
                    ))
                )
            ))
        ))
  ); //$data = array...
</code>```

I suspect that I'm simply missing some appropriate reference to the tabs defined in the server template. But documentation is atrocious and I've already spent several hours combing the web. Any help would be much appreciated.

UPDATE1

As requested, here's the code that generates the envelope successfully:

```<code>function c_requestSignature($templateID, $recipientName, $recipientEmail, $recipientID, $document){
  //function sets up the passed document for signing using the specified template
  $documentName = "W4"; //FIXME fetch document name using templateID
  $baseURL = c_docusignBaseURL();
  $accountId = c_docusignAccountId();
  $header = c_docusignHeader();
  $data = array (
        "emailSubject" => "Please sign " . $documentName,
        //"emailBlurb" => "Test Email Body",
        "status" => "sent",
        "compositeTemplates" => array(
            "compositeTemplate" => array(
                "serverTemplates" => array(
                    "serverTemplate" => array(
                        "sequence" => "1",
                        "templateId" => "_redacted_"
                    )
                ),
                "inlineTemplates" => array(
                    "inlineTemplate" => array(
                        "sequence" => "2",
                        "recipients" => array(
                            "signers" => array(
                                "signer" => array(
                                    "name" => $recipientName,
                                    "email" => $recipientEmail,
                                    "roleName" => "NewHire"
                                )
                            )
                        )
                    )
                ),
                "document" => array(
                    "documentId" => "1",
                    "name" => $documentName,
                    "fileExtension" => "pdf",
                    "documentBase64" => $document
                )
            )
        )
  );

  // Send to the /envelopes end point, which is relative to the baseUrl received above.
  $curl = curl_init($baseURL . "/envelopes" );
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string),
    "X-DocuSign-Authentication: $header" )
  );

  $json_response = curl_exec($curl); // Do it!

  $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  if ( $status != 201 ) {
    echo "Error calling DocuSign, status is:" . $status . "\nerror text: ";
    print_r($json_response); echo "\n";
    exit(-1);
  }

  $response = json_decode($json_response, true);
  $envelopeId = $response["envelopeId"];

  error_log ("successfully created envelope: $envelopeId");
  $url = getSignatureURL($envelopeId, $recipientName, $recipientEmail, $recipientID);
  return $url;
}//c_requestSignature()...
</code>```

The function getSignatureURL() has code as follows:

```<code>function getSignatureURL($envelopeId, $recipientName, $recipientEmail, $recipientID){
  //function retrieves the signing ceremony UX URL from DocuSign
  $baseURL = c_docusignBaseURL();
  $accountId = c_docusignAccountId();
  $header = c_docusignHeader();
  //set up the data we'll send to the Docusign server
  $data = array("returnUrl" => "http://_redacted_",
    "authenticationMethod" => "none",
    "email" => $recipientEmail,
    "name" => $recipientName,
    "recipientId" => $recipientID,
    //"recipientId" => "1",
    //"clientUserId" => $recipientID,
    "userName" => $recipientName
  );
  $data_string = json_encode($data);
  //set up curl
  $curl = curl_init($baseURL . "/envelopes/$envelopeId/views/recipient" );
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string),
    "X-DocuSign-Authentication: $header" )
  );
  //make the API call
  $json_response = curl_exec($curl);
  $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  if ( $status != 201 ) {
    echo "error calling webservice, status is:" . $status . "\nerror text is --> ";
    print_r($json_response); echo "\n";
    exit(-1);
  }
  //retrieve and process the response
  $response = json_decode($json_response, true);
  return $response["url"];
}
</code>```

UPDATE 2

Here's the raw json as requested...

```<code>{
  "emailSubject": "some subject",
  "status": "sent",
  "compositeTemplates": [
    {
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "_redacted_"
        }
      ],
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "name": "Andrew Tester1",
                "email": "my_email_address",
                "roleName": "NewHire",
                "recipientId": "1234",
                "clientUserId": "1234"
              }
            ]
          }
        }
      ],
      "document": {
        "documentId": "1",
        "name": "W4",
        "fileExtension": "pdf",
        "documentBase64": "_redacted_"
      }
    }
  ]
}
</code>```

Update 3

I had a problem which was preventing me from seeing the proper output of the above json. With that fixed, now I'm getting the following error:

Error calling DocuSign, status is:400 error text: { "errorCode":
  "TAB_REFERS_TO_MISSING_DOCUMENT", "message": "The DocumentId specified
  in the tab element does not refer to a document in this envelope. Tab
  refers to DocumentId 46677269 which is not present." }

If I change the document stanza above as follows:

```<code>      "document": {
        "documentId": "46677269",
        "name": "W4",
        "fileExtension": "pdf",
        "documentBase64": "_redacted_"
      }
</code>```

The error goes away, but I still get a signing ceremony with no tabs.

答:
The following request can be used to create an envelope from the Server Template. The server templates document will be replaced with the new document that is specified in the request.</p>

```<code>{
    "emailSubject": "Test Email Subject",
    "emailBlurb" :  "Test Email Body",
    "status": "sent",
    "compositeTemplates": [
        {
            "serverTemplates": [
                {
                    "sequence": "1",
                    "templateId": "86841739-f12d-460e-9807-23a9b90cff6b"
                }
            ],
            "inlineTemplates": [
                {
                    "sequence": "1",
                    "recipients": {
                        "signers": [
                            {
                                "name": "Jane Doe",
                                "email": "janedoe@acme.com",
                                "roleName": "New Employee"
                            }
                        ]
                    }
                }
            ],
            "document": {
                "documentId": "1",
                "name": "Your Doc Name",
                "fileExtension": "pdf",
                "documentBase64": ""
            }
        }
    ]
}
</code>```

Body:
I'm working on a DocuSign integration. I have the basics functional but can't seem to figure out how to merge a local document (PDF) with a server template such that tabs configured on the server template get used or overlaid on the passed document.

My template is defined on the server and I can use it directly from the web UI without issue (it's a W4 form). The template has three tabs (SSN, Sign here, and date) as you can see below. Accessing this template via it's ID using the API Explorer yields the following json

{
    "envelopeTemplateDefinition": {
        "templateId": "_redacted_",
        "name": "W4 3/13/2017",
        "shared": "true",
        "password": "",
        "description": "",
        "lastModified": "2017-06-05T18:45:28.4470000Z",
        "lastModifiedBy": {
            "userName": "Andrew",
            "userId": "_redacted_",
            "email": "my_email_address",
            "uri": "/users/_redacted_
        },
        "pageCount": 2,
        "uri": "/templates/_redacted_",
        "folderName": "Templates",
        "folderId": "_redacted_",
        "folderUri": "/folders/_redacted_",
        "owner": {
            "userName": "Andrew",
            "userId": "_redacted_",
            "email": "my_email_address"
        }
    },
    "documents": [
        {
            "documentId": "46677269",
            "uri": "/envelopes/_redacted_/documents/46677269",
            "name": "W4.pdf",
            "order": "1",
            "pages": "2",
            "display": "inline",
            "includeInDownload": "true",
            "signerMustAcknowledge": "no_interaction",
            "templateLocked": "false",
            "templateRequired": "false",
            "documentGroup": "content"
        }
    ],
    "emailSubject": "Please DocuSign: W4.pdf",
    "emailBlurb": "",
    "signingLocation": "online",
    "autoNavigation": "true",
    "envelopeIdStamping": "true",
    "authoritativeCopy": "false",
    "notification": {
        "reminders": {
            "reminderEnabled": "false",
            "reminderDelay": "0",
            "reminderFrequency": "0"
        },
        "expirations": {
            "expireEnabled": "true",
            "expireAfter": "120",
            "expireWarn": "0"
        }
    },
    "enforceSignerVisibility": "false",
    "enableWetSign": "true",
    "allowMarkup": "false",
    "allowReassign": "true",
    "recipients": {
        "signers": [
            {
                "defaultRecipient": "false",
                "tabs": {
                    "signHereTabs": [
                        {
                            "stampType": "signature",
                            "name": "SignHere",
                            "tabLabel": "Signature _redacted_",
                            "scaleValue": 1.0,
                            "optional": "false",
                            "documentId": "46677269",
                            "recipientId": "94043042",
                            "pageNumber": "1",
                            "xPosition": "193",
                            "yPosition": "682",
                            "tabId": "_redacted_",
                            "templateLocked": "false",
                            "templateRequired": "false"
                        }
                    ],
                    "dateSignedTabs": [
                        {
                            "name": "DateSigned",
                            "value": "",
                            "tabLabel": "Date Signed _redacted_",
                            "font": "lucidaconsole",
                            "fontColor": "black",
                            "fontSize": "size9",
                            "documentId": "46677269",
                            "recipientId": "94043042",
                            "pageNumber": "1",
                            "xPosition": "480",
                            "yPosition": "713",
                            "tabId": "_redacted_",
                            "templateLocked": "false",
                            "templateRequired": "false"
                        }
                    ],
                    "ssnTabs": [
                        {
                            "validationPattern": "",
                            "validationMessage": "",
                            "shared": "false",
                            "requireInitialOnSharedChange": "false",
                            "requireAll": "false",
                            "value": "",
                            "width": 144,
                            "required": "true",
                            "locked": "false",
                            "concealValueOnDocument": "true",
                            "disableAutoSize": "false",
                            "maxLength": 4000,
                            "tabLabel": "Text _redacted_",
                            "font": "lucidaconsole",
                            "fontColor": "black",
                            "fontSize": "size9",
                            "documentId": "46677269",
                            "recipientId": "94043042",
                            "pageNumber": "1",
                            "xPosition": "442",
                            "yPosition": "563",
                            "tabId": "_redacted_",
                            "templateLocked": "false",
                            "templateRequired": "false"
                        }
                    ]
                },
                "signInEachLocation": "false",
                "name": "",
                "email": "",
                "recipientId": "94043042",
                "accessCode": "",
                "requireIdLookup": "false",
                "routingOrder": "1",
                "note": "",
                "roleName": "New Employee",
                "deliveryMethod": "email",
                "templateLocked": "false",
                "templateRequired": "false",
                "inheritEmailNotificationConfiguration": "false"
            }
        ],
        "agents": [ ],
        "editors": [ ],
        "intermediaries": [ ],
        "carbonCopies": [ ],
        "certifiedDeliveries": [ ],
        "inPersonSigners": [ ],
        "recipientCount": "1"
    }
}

What I want to do is apply this template to a PDF that's already partially filled out such that when the signer get's it the tabs defined in the server template are used for the sining.

As it stands now, there's nothing. Just the partially filled out PDF I passed in below as base64 data, with none of the server template tabs to fill out or sign. Here's my json for the API call (in PHP).

  $data = array (
        "emailBlurb" => "Test Email Body",
        "emailSubject" => "Test Email Subject",
        "status" => "sent",
        "compositeTemplates" => array(array(
            "document" => array(
                "documentId" => 46677269,
                "name" => $documentName,
                "documentBase64" => $document
            ),
            "serverTemplates" => array(array(

                "sequence" => 1,
                "templateId" => "_redacted_"
            )),
            "inlineTemplates" => array(array(
                "sequence" => 2,
                "recipients" => array(
                    "signers" => array(array(
                        "email" => $recipientEmail,
                        "name" => $recipientName,
                        "recipientId" => $recipientID,
                        "roleName" => "New Employee"
                    ))
                )
            ))
        ))
  ); //$data = array...

I suspect that I'm simply missing some appropriate reference to the tabs defined in the server template. But documentation is atrocious and I've already spent several hours combing the web. Any help would be much appreciated.

UPDATE1

As requested, here's the code that generates the envelope successfully:

function c_requestSignature($templateID, $recipientName, $recipientEmail, $recipientID, $document){
  //function sets up the passed document for signing using the specified template
  $documentName = "W4"; //FIXME fetch document name using templateID
  $baseURL = c_docusignBaseURL();
  $accountId = c_docusignAccountId();
  $header = c_docusignHeader();
  $data = array (
        "emailSubject" => "Please sign " . $documentName,
        //"emailBlurb" => "Test Email Body",
        "status" => "sent",
        "compositeTemplates" => array(
            "compositeTemplate" => array(
                "serverTemplates" => array(
                    "serverTemplate" => array(
                        "sequence" => "1",
                        "templateId" => "_redacted_"
                    )
                ),
                "inlineTemplates" => array(
                    "inlineTemplate" => array(
                        "sequence" => "2",
                        "recipients" => array(
                            "signers" => array(
                                "signer" => array(
                                    "name" => $recipientName,
                                    "email" => $recipientEmail,
                                    "roleName" => "NewHire"
                                )
                            )
                        )
                    )
                ),
                "document" => array(
                    "documentId" => "1",
                    "name" => $documentName,
                    "fileExtension" => "pdf",
                    "documentBase64" => $document
                )
            )
        )
  );

  // Send to the /envelopes end point, which is relative to the baseUrl received above.
  $curl = curl_init($baseURL . "/envelopes" );
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string),
    "X-DocuSign-Authentication: $header" )
  );

  $json_response = curl_exec($curl); // Do it!

  $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  if ( $status != 201 ) {
    echo "Error calling DocuSign, status is:" . $status . "\nerror text: ";
    print_r($json_response); echo "\n";
    exit(-1);
  }

  $response = json_decode($json_response, true);
  $envelopeId = $response["envelopeId"];

  error_log ("successfully created envelope: $envelopeId");
  $url = getSignatureURL($envelopeId, $recipientName, $recipientEmail, $recipientID);
  return $url;
}//c_requestSignature()...

The function getSignatureURL() has code as follows:

function getSignatureURL($envelopeId, $recipientName, $recipientEmail, $recipientID){
  //function retrieves the signing ceremony UX URL from DocuSign
  $baseURL = c_docusignBaseURL();
  $accountId = c_docusignAccountId();
  $header = c_docusignHeader();
  //set up the data we'll send to the Docusign server
  $data = array("returnUrl" => "http://_redacted_",
    "authenticationMethod" => "none",
    "email" => $recipientEmail,
    "name" => $recipientName,
    "recipientId" => $recipientID,
    //"recipientId" => "1",
    //"clientUserId" => $recipientID,
    "userName" => $recipientName
  );
  $data_string = json_encode($data);
  //set up curl
  $curl = curl_init($baseURL . "/envelopes/$envelopeId/views/recipient" );
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string),
    "X-DocuSign-Authentication: $header" )
  );
  //make the API call
  $json_response = curl_exec($curl);
  $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  if ( $status != 201 ) {
    echo "error calling webservice, status is:" . $status . "\nerror text is --> ";
    print_r($json_response); echo "\n";
    exit(-1);
  }
  //retrieve and process the response
  $response = json_decode($json_response, true);
  return $response["url"];
}

UPDATE 2

Here's the raw json as requested...

{
  "emailSubject": "some subject",
  "status": "sent",
  "compositeTemplates": [
    {
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "_redacted_"
        }
      ],
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "name": "Andrew Tester1",
                "email": "my_email_address",
                "roleName": "NewHire",
                "recipientId": "1234",
                "clientUserId": "1234"
              }
            ]
          }
        }
      ],
      "document": {
        "documentId": "1",
        "name": "W4",
        "fileExtension": "pdf",
        "documentBase64": "_redacted_"
      }
    }
  ]
}

Update 3

I had a problem which was preventing me from seeing the proper output of the above json. With that fixed, now I'm getting the following error:

Error calling DocuSign, status is:400 error text: { "errorCode":
  "TAB_REFERS_TO_MISSING_DOCUMENT", "message": "The DocumentId specified
  in the tab element does not refer to a document in this envelope. Tab
  refers to DocumentId 46677269 which is not present." }

If I change the document stanza above as follows:

      "document": {
        "documentId": "46677269",
        "name": "W4",
        "fileExtension": "pdf",
        "documentBase64": "_redacted_"
      }

The error goes away, but I still get a signing ceremony with no tabs.

Body:
The following request can be used to create an envelope from the Server Template. The server templates document will be replaced with the new document that is specified in the request.

{
    "emailSubject": "Test Email Subject",
    "emailBlurb" :  "Test Email Body",
    "status": "sent",
    "compositeTemplates": [
        {
            "serverTemplates": [
                {
                    "sequence": "1",
                    "templateId": "86841739-f12d-460e-9807-23a9b90cff6b"
                }
            ],
            "inlineTemplates": [
                {
                    "sequence": "1",
                    "recipients": {
                        "signers": [
                            {
                                "name": "Jane Doe",
                                "email": "janedoe@acme.com",
                                "roleName": "New Employee"
                            }
                        ]
                    }
                }
            ],
            "document": {
                "documentId": "1",
                "name": "Your Doc Name",
                "fileExtension": "pdf",
                "documentBase64": ""
            }
        }
    ]
}


问:
Errors deploy Spring webapp to Google Appengine
Firstly, I'm sorry for my bad English.
I have a Springboot webapp project, which i wanna deploy to appengine platform. The problem is when i run this project locally in appengine port 8080 using command mvn spring-boot:run it works perfectly. But then, when i using command mvn appengine:deploy the errors comes out

```<code>[INFO] GCLOUD: ERROR: (gcloud.app.deploy) Error Response: [9]
[INFO] GCLOUD: Application startup error:
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor       /lang/tt.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/pt-br.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/no.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/nl.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/zh-cn.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/en-gb.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/CHANGES.md
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/css/style.css
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/css/bootstrap.min.css
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/static/client_secret.json
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/dao/NewsRepository.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/service/NewsService.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/controller/SampleRestController.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/controller/MainController.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/UploadFile.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/models/News.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/Application.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/.application.properties.swp
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/application.properties
.................................................................
[INFO] GCLOUD: -XX:InitialHeapSize=514850816
-XX:MaxHeapSize=514850816 -XX:+ParallelRefProcEnabled  -XX:+PrintCommandLineFlags    -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseG1GC
[INFO] GCLOUD: openjdk version "1.8.0_121"
[INFO] GCLOUD: OpenJDK Runtime Environment (build 1.8.0_121-8u121-b13-1~bpo8+1-b13)
[INFO] GCLOUD: OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)
[INFO] GCLOUD:
[INFO] GCLOUD: 2017-05-30 02:17:21.237:INFO::main: Logging initialized @1794ms to org.eclipse.jetty.util.log.StdErrLog
[INFO] GCLOUD: 2017-05-30 02:17:22.251:INFO:oejs.SetUIDListener:main: Setting umask=02
[INFO] GCLOUD: 2017-05-30 02:17:22.292:INFO:oejs.SetUIDListener:main: Opened ServerConnector@29774679{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
[INFO] GCLOUD: 2017-05-30 02:17:22.294:INFO:oejs.SetUIDListener:main: Setting GID=999
[INFO] GCLOUD: 2017-05-30 02:17:22.299:INFO:oejs.SetUIDListener:main: Setting UID=999
[INFO] GCLOUD: 2017-05-30 02:17:22.309:INFO:oejs.Server:main: jetty-9.4.3.v20170317
[INFO] GCLOUD: 2017-05-30 02:17:22.496:INFO:oejdp.ScanningAppProvider:main: Deployment monitor      [file:///var/lib/jetty/webapps/] at interval 0
[INFO] GCLOUD:
[INFO]   ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 06:43 min
[INFO] Finished at: 2017-05-30T09:20:05+07:00
[INFO] Final Memory: 22M/54M
[INFO] ------------------------------------------------------------------------
</code>```

My project's github link here
My pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.hhoang.articleweb</groupId>
<artifactId>articleweb</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>articleweb Maven Webapp</name>
<url>http://maven.apache.org</url>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>persistence-api</artifactId>
        <version>1.0.2</version>
    </dependency>
    <dependency>
        <groupId>com.google.api-client</groupId>
        <artifactId>google-api-client</artifactId>
        <version>1.22.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-jetty</artifactId>
        <version>1.22.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-drive</artifactId>
        <version>v3-rev59-1.20.0</version>
    </dependency>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk</artifactId>
        <version>1.11.132</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.google.cloud.tools</groupId>
            <artifactId>appengine-maven-plugin</artifactId>
            <version>1.2.1</version>
        </plugin>
    </plugins>
    <finalName>articleweb</finalName>
</build>
</code>```

I have no ideal with this errors. Also, i'm not familiar with jetty. Hope someone help me. Thank you so much for spend time reading my post.

答:
Give this a try to deploy using a jar file.

Use this plugin:

```<code>  <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.3.RELEASE</version>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</code>```

Include any static resource if you have HTML, etc.

```<code><resources>
        <resource>
         <!-- Must include this for static pages -->
            <directory>src/main/webapp</directory>
        </resource>
         <resource>
         <!-- Must include this for properties file -->
            <directory>src/main/resources</directory>
        </resource>
</code>```

Execute command

mvn clean package spring-boot:repackage

Body:
Firstly, I'm sorry for my bad English.
I have a Springboot webapp project, which i wanna deploy to appengine platform. The problem is when i run this project locally in appengine port 8080 using command mvn spring-boot:run it works perfectly. But then, when i using command mvn appengine:deploy the errors comes out

[INFO] GCLOUD: ERROR: (gcloud.app.deploy) Error Response: [9]
[INFO] GCLOUD: Application startup error:
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor       /lang/tt.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/pt-br.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/no.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/nl.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/zh-cn.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/lang/en-gb.js
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/ckeditor/CHANGES.md
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/css/style.css
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/static/css/bootstrap.min.css
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/static/client_secret.json
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/dao/NewsRepository.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/service/NewsService.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/controller/SampleRestController.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/controller/MainController.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/UploadFile.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/models/News.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/articleweb/Application.class
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/.application.properties.swp
[INFO] GCLOUD:   inflating: /var/lib/jetty/webapps/root/WEB-INF/classes/application.properties
.................................................................
[INFO] GCLOUD: -XX:InitialHeapSize=514850816
-XX:MaxHeapSize=514850816 -XX:+ParallelRefProcEnabled  -XX:+PrintCommandLineFlags    -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseG1GC
[INFO] GCLOUD: openjdk version "1.8.0_121"
[INFO] GCLOUD: OpenJDK Runtime Environment (build 1.8.0_121-8u121-b13-1~bpo8+1-b13)
[INFO] GCLOUD: OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)
[INFO] GCLOUD:
[INFO] GCLOUD: 2017-05-30 02:17:21.237:INFO::main: Logging initialized @1794ms to org.eclipse.jetty.util.log.StdErrLog
[INFO] GCLOUD: 2017-05-30 02:17:22.251:INFO:oejs.SetUIDListener:main: Setting umask=02
[INFO] GCLOUD: 2017-05-30 02:17:22.292:INFO:oejs.SetUIDListener:main: Opened ServerConnector@29774679{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
[INFO] GCLOUD: 2017-05-30 02:17:22.294:INFO:oejs.SetUIDListener:main: Setting GID=999
[INFO] GCLOUD: 2017-05-30 02:17:22.299:INFO:oejs.SetUIDListener:main: Setting UID=999
[INFO] GCLOUD: 2017-05-30 02:17:22.309:INFO:oejs.Server:main: jetty-9.4.3.v20170317
[INFO] GCLOUD: 2017-05-30 02:17:22.496:INFO:oejdp.ScanningAppProvider:main: Deployment monitor      [file:///var/lib/jetty/webapps/] at interval 0
[INFO] GCLOUD:
[INFO]   ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 06:43 min
[INFO] Finished at: 2017-05-30T09:20:05+07:00
[INFO] Final Memory: 22M/54M
[INFO] ------------------------------------------------------------------------

My project's github link here
My pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.hhoang.articleweb</groupId>
<artifactId>articleweb</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>articleweb Maven Webapp</name>
<url>http://maven.apache.org</url>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>persistence-api</artifactId>
        <version>1.0.2</version>
    </dependency>
    <dependency>
        <groupId>com.google.api-client</groupId>
        <artifactId>google-api-client</artifactId>
        <version>1.22.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-jetty</artifactId>
        <version>1.22.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-drive</artifactId>
        <version>v3-rev59-1.20.0</version>
    </dependency>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk</artifactId>
        <version>1.11.132</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.google.cloud.tools</groupId>
            <artifactId>appengine-maven-plugin</artifactId>
            <version>1.2.1</version>
        </plugin>
    </plugins>
    <finalName>articleweb</finalName>
</build>

I have no ideal with this errors. Also, i'm not familiar with jetty. Hope someone help me. Thank you so much for spend time reading my post.

Body:
Give this a try to deploy using a jar file.

Use this plugin:

  <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.3.RELEASE</version>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

Include any static resource if you have HTML, etc.

<resources>
        <resource>
         <!-- Must include this for static pages -->
            <directory>src/main/webapp</directory>
        </resource>
         <resource>
         <!-- Must include this for properties file -->
            <directory>src/main/resources</directory>
        </resource>

Execute command

mvn clean package spring-boot:repackage


问:
Without using for each loop container in ssis , I have to dump one folder that contains several files in it
There is one folder that contains 4 csv files , I have to dump it to sql server without using foreach loop container. How to do that?</p>

答:
You can do it with a Script task.

The script task would use the file system object to loop through the files in the folder, read them row by row, and insert the rows into the database.


问:
What is the best pattern for two way communication between classes?
I have classes that need to communicate with each other. The problem is that if you make one contain the other (a child parent relationship) then things get tricky. You either need to pass an instance of the parent into the child, (then which one do you create first if you are using dependency injection) or you can use delegates/events. But I want to enforce the fact that the parent must be able to handle the event that the child raises. Not too sure how to do that. I also don't want multiple subscribers to the event.

The parent-child relationship just feels wrong for two way communication. Unfortunately it is not a case that one of the objects always initiates and the other responds. Either can initiate and the other should respond.

Is there another pattern that I am missing?

UPDATE:
Sorry this is quite hard to explain. I forgot to add that when one class sends a message to another class it is not expecting the response immediately. The response comes in asynchronously which is why you either need an instance of the parent to call the right method or a delegate/event. Sorry the example below is pseudo code. Hopefully it is enough to get the idea. Should I look at the mediator pattern.

```<code>public class Foo
    {
        public void SendMessageAToBar()
        {
            MessageA msg = new MessageA();
            Bar.ReceiveMessageAFromFoo(msg);
        }

        public void ReceiveMessageARespFromBar(MessageAResp msgResp)
        {
            //Got a response do something
        }

        public void ReceiveMessageBFromBar(MessageB msg)
        {
            //Do something msg
            MessageBResp msgBResp = new MessageBResp();
            Bar.ReceiveMessageBRespFromFoo()
        }
    }

    public class Bar
    {

        public void ReceiveMessageAFromFoo(MessageA msg)
        {
            //DO something.
            MessageAResp resp = new MessageAResp();
            Foo.ReceiveMessageARespFromBar(resp);
        }

        public void SendMessageBToFoo()
        {
            MessageB msg = new MessageB();
            Foo.ReceiveMessageBFromBar(msg);
        }

        public void ReceiveMessageBRespFromFoo(MessageBResp msgResp)
        {
            //Got a response do something
        }
    }
</code>```

答: Make an intermediate object that contains communication details and inject it both in A and B?</p>

Body:
I have classes that need to communicate with each other. The problem is that if you make one contain the other (a child parent relationship) then things get tricky. You either need to pass an instance of the parent into the child, (then which one do you create first if you are using dependency injection) or you can use delegates/events. But I want to enforce the fact that the parent must be able to handle the event that the child raises. Not too sure how to do that. I also don't want multiple subscribers to the event.

The parent-child relationship just feels wrong for two way communication. Unfortunately it is not a case that one of the objects always initiates and the other responds. Either can initiate and the other should respond.

Is there another pattern that I am missing?

UPDATE:
Sorry this is quite hard to explain. I forgot to add that when one class sends a message to another class it is not expecting the response immediately. The response comes in asynchronously which is why you either need an instance of the parent to call the right method or a delegate/event. Sorry the example below is pseudo code. Hopefully it is enough to get the idea. Should I look at the mediator pattern.

public class Foo
    {
        public void SendMessageAToBar()
        {
            MessageA msg = new MessageA();
            Bar.ReceiveMessageAFromFoo(msg);
        }

        public void ReceiveMessageARespFromBar(MessageAResp msgResp)
        {
            //Got a response do something
        }

        public void ReceiveMessageBFromBar(MessageB msg)
        {
            //Do something msg
            MessageBResp msgBResp = new MessageBResp();
            Bar.ReceiveMessageBRespFromFoo()
        }
    }

    public class Bar
    {

        public void ReceiveMessageAFromFoo(MessageA msg)
        {
            //DO something.
            MessageAResp resp = new MessageAResp();
            Foo.ReceiveMessageARespFromBar(resp);
        }

        public void SendMessageBToFoo()
        {
            MessageB msg = new MessageB();
            Foo.ReceiveMessageBFromBar(msg);
        }

        public void ReceiveMessageBRespFromFoo(MessageBResp msgResp)
        {
            //Got a response do something
        }
    }


问:
While loops in Python 3
I'm having some problems with some code for a menu system. What I have so far isn't completed but I'm having a problem with it. It works fine with the account.leeman' but I can never get 'administrator' to work, and it always rolls back to the beginning. I've looked at the code for a while now but I can't figure out why this is and why it doesn't ever continue. The 'add' part of the code can be ignored as it isn't a problem yet, although if you can see any way in improving it, please let me know

So this is what I have:

```<code>usernames=["m.leeman","administrator"]
passwords=["pA55w0rd","password"]
while True:
    count=0
    add_or_enter=input("Would you like to Enter a username or Add a new one?: ").lower()
    if add_or_enter=="enter":
        username=input("Please enter username: ")
        while (count+1)!=(len(usernames)):
            #problem somewhere here
            if username==usernames[count]:
                print("Username accepted")
                password=input("Please enter password: ")
                if password==passwords[count]:
                    print("Welcome "+str(username))
                    print("Continue here")
                else:
                    print("Incorrect password")
            else:
                count+=1
                if count==len(usernames):
                    print("User does not exit")
                else:
                    ()
                    #should run again after this
    elif add_or_enter=="add":
        new_user=input("Enter a new username: ")
        if (new_user=="add") or (new_user==usernames[count]):
            print("Username unavailiable")
        else:
            count=+1
            if count==len(usernames)-1:
                usernames.append(new_user)
                new_password=input("Enter a password for this user: ")
                passwords.append(new_password)
                print("User "+new_user+" successfully created")
</code>```

Any replies will be very helpful. Thanks.

答: you never get to administrator because you are double incrementing count. you have count being incremented in the condition and then in the else statement when it doesn't = m.leeman so take out the count+=1 after the else statement. </p>

Title: While loops in Python 3

Body:
I'm having some problems with some code for a menu system. What I have so far isn't completed but I'm having a problem with it. It works fine with the account.leeman' but I can never get 'administrator' to work, and it always rolls back to the beginning. I've looked at the code for a while now but I can't figure out why this is and why it doesn't ever continue. The 'add' part of the code can be ignored as it isn't a problem yet, although if you can see any way in improving it, please let me know

So this is what I have:

usernames=["m.leeman","administrator"]
passwords=["pA55w0rd","password"]
while True:
    count=0
    add_or_enter=input("Would you like to Enter a username or Add a new one?: ").lower()
    if add_or_enter=="enter":
        username=input("Please enter username: ")
        while (count+1)!=(len(usernames)):
            #problem somewhere here
            if username==usernames[count]:
                print("Username accepted")
                password=input("Please enter password: ")
                if password==passwords[count]:
                    print("Welcome "+str(username))
                    print("Continue here")
                else:
                    print("Incorrect password")
            else:
                count+=1
                if count==len(usernames):
                    print("User does not exit")
                else:
                    ()
                    #should run again after this
    elif add_or_enter=="add":
        new_user=input("Enter a new username: ")
        if (new_user=="add") or (new_user==usernames[count]):
            print("Username unavailiable")
        else:
            count=+1
            if count==len(usernames)-1:
                usernames.append(new_user)
                new_password=input("Enter a password for this user: ")
                passwords.append(new_password)
                print("User "+new_user+" successfully created")

Any replies will be very helpful. Thanks.


问:
OpenCV-Python installation (missing ffmpeg) - Windows
I managed to install OpenCV 3.1 using conda and Python 3.5 and everything seems to work fine.

However, when trying to import a video file via ffmpeg I get this:

```<code>import numpy as np
import cv2

cap = cv2.VideoCapture('data\vtest.avi')
cap.read()

#(False, None)
</code>```

When using still images or my laptop webcam it works (notice that the VideCapture returns None). Obviously, something is wrong with ffmpeg.

I have tried a couple of things:

Install ffmpeg binaries in my environment/PATH (works fine separately
but apparently OpenCV cannot call it since it looks for specific dlls).

Move to the bin folder (which is in my path as well) the
dlls from the compiled version in
sourceforge:

opencv_ffmpeg310_64.dll

opencv_ffmpeg310.dll

Neither of the two options worked. Any ideas?

答: The conda version of OpenCV is not compiled with ffmpeg. I too have struggled with this problem endlessly. The pip version is not compiled with ffmpeg either. The best advice I have is to compile OpenCV with ffmpeg yourself, that is the only painless and stable way that I have found.</p>

Body:
I managed to install OpenCV 3.1 using conda and Python 3.5 and everything seems to work fine.

However, when trying to import a video file via ffmpeg I get this:

import numpy as np
import cv2

cap = cv2.VideoCapture('data\vtest.avi')
cap.read()

#(False, None)

When using still images or my laptop webcam it works (notice that the VideCapture returns None). Obviously, something is wrong with ffmpeg.

I have tried a couple of things:

Install ffmpeg binaries in my environment/PATH (works fine separately
but apparently OpenCV cannot call it since it looks for specific dlls).

Move to the bin folder (which is in my path as well) the
dlls from the compiled version in
sourceforge:

opencv_ffmpeg310_64.dll

opencv_ffmpeg310.dll

Neither of the two options worked. Any ideas?


问:
multiple string functions in one line
I know how to solve this problem using multiple lines but in the spirit of clean code is there a way to run multiple string functions in the same line?

Essentially I'm returning a string using

```<code>''.join(string.title())
</code>```

after I need to remove whitespaces from the new modified string:

```<code>string.replace(" ", '')
</code>```

The whitespace is important at the beginning as it allows me to use the title function so the order shouldn't change.

答:
You can add together string functions like this:

''.join(string.title()).replace(" ", '')

Hope this helps you.

Title: multiple string functions in one line

Body:
I know how to solve this problem using multiple lines but in the spirit of clean code is there a way to run multiple string functions in the same line?

Essentially I'm returning a string using

''.join(string.title())

after I need to remove whitespaces from the new modified string:

string.replace(" ", '')

The whitespace is important at the beginning as it allows me to use the title function so the order shouldn't change.


问:
systemd unit file never finishes when using a shell command with pipes
I'm trying to execute a shell script with systemd.

If I run my script from the bash everything works fine. But if I run the same script via systemd it never finishes. The command where it seems to hang is:

```<code>random="$(LC_ALL=C tr -cd '[:alnum:]' < /dev/urandom | fold -w128 | head -n1)"
</code>```

If I'm replacing this line with random="1234" it also runs with systemd. I guess the 'hanging' command is the tr - its process never finishes.

And this is the systemd unit file I'm using:

```<code>[Unit]
Description=my script

[Service]
Type=forking
Restart=on-failure
ExecStart=/mypath/script.sh start
ExecStop=/bin/kill $MAINPID
ExecStopPost=/bin/rm -f /mypath/RUNNING_PID

[Install]
WantedBy=multi-user.target
</code>```

答:
Edit: Made the explanation clearer and added new information.

Short answer: systemd is filtering SIGPIPEs, so
set IgnoreSIGPIPE=false under [Service] in the .service file. From the systemd.exec manual:

```<code>   IgnoreSIGPIPE=
       Takes a boolean argument. If true, causes
       SIGPIPE to be ignored in the executed process.
       Defaults to true because SIGPIPE generally is
       useful only in shell pipelines.
</code>```

Long explanation:

random="$(LC_ALL=C tr -cd '[:alnum:]' < /dev/urandom | fold -w128 |
head -n1)"

When the head command exits after the first newline received from fold, its open file descriptors are closed.
Thus when the fold command later tries to write to the pipe, it will receive a SIGPIPE signal (as described in pipe(7)).
The default action for this signal is a termination of the process.
That mechanism repeats towards the start of the pipeline, so the fold command would be terminated next, and eventually the tr command.

However, when the pipeline is run under systemd, systemd sets the default action for SIGPIPE to SIG_IGN, which makes the processes in the pipeline ignore the signal.

When fold (and the other components of the pipeline) inherits that signal handler, it won't be notified (killed) via SIGPIPE when writing to the now closed output pipe (Instead each write to the pipe will return an EPIPE error).

As fold command does not check the return value of those write calls (at least not in coreutils-8.26), this makes fold continue reading from the pipe (stdin) and to write to the closed pipe (stdout), even though an error is reported each time.
So fold keeps its input pipe from tr open, and tr will happily write to the output pipe feeding fold forever.

Body:
I'm trying to execute a shell script with systemd.

If I run my script from the bash everything works fine. But if I run the same script via systemd it never finishes. The command where it seems to hang is:

random="$(LC_ALL=C tr -cd '[:alnum:]' < /dev/urandom | fold -w128 | head -n1)"

If I'm replacing this line with random="1234" it also runs with systemd. I guess the 'hanging' command is the tr - its process never finishes.

And this is the systemd unit file I'm using:

[Unit]
Description=my script

[Service]
Type=forking
Restart=on-failure
ExecStart=/mypath/script.sh start
ExecStop=/bin/kill $MAINPID
ExecStopPost=/bin/rm -f /mypath/RUNNING_PID

[Install]
WantedBy=multi-user.target

Body:
Edit: Made the explanation clearer and added new information.

Short answer: systemd is filtering SIGPIPEs, so
set IgnoreSIGPIPE=false under [Service] in the .service file. From the systemd.exec manual:

   IgnoreSIGPIPE=
       Takes a boolean argument. If true, causes
       SIGPIPE to be ignored in the executed process.
       Defaults to true because SIGPIPE generally is
       useful only in shell pipelines.

Long explanation:

random="$(LC_ALL=C tr -cd '[:alnum:]' < /dev/urandom | fold -w128 |
head -n1)"

When the head command exits after the first newline received from fold, its open file descriptors are closed.
Thus when the fold command later tries to write to the pipe, it will receive a SIGPIPE signal (as described in pipe(7)).
The default action for this signal is a termination of the process.
That mechanism repeats towards the start of the pipeline, so the fold command would be terminated next, and eventually the tr command.

However, when the pipeline is run under systemd, systemd sets the default action for SIGPIPE to SIG_IGN, which makes the processes in the pipeline ignore the signal.

When fold (and the other components of the pipeline) inherits that signal handler, it won't be notified (killed) via SIGPIPE when writing to the now closed output pipe (Instead each write to the pipe will return an EPIPE error).

As fold command does not check the return value of those write calls (at least not in coreutils-8.26), this makes fold continue reading from the pipe (stdin) and to write to the closed pipe (stdout), even though an error is reported each time.
So fold keeps its input pipe from tr open, and tr will happily write to the output pipe feeding fold forever.