问:
HOW To manipulate an ALREADY open word document from excel vba
I am new to VBA and obviously I am missing something. My code works for opening a word doc and sending data to it BUT does NOT for an ALREADY OPEN word doc. I keep searching for an answer on how to send info from Excel to an OPEN Word doc/Bookmark and nothing works.

I hope it is okay that I added all the code and the functions called. I really appreciate your help!

What I have so far

```<code>Sub ExcelNamesToWordBookmarks()
On Error GoTo ErrorHandler

Dim wrdApp As Object 'Word.Application
Dim wrdDoc As Object 'Word.Document
Dim xlName As Excel.Name
Dim ws As Worksheet
Dim str As String 'cell/name value
Dim cell As Range
Dim celldata As Variant 'added to use in the test
Dim theformat As Variant 'added
Dim BMRange As Object
Dim strPath As String
Dim strFile As String
Dim strPathFile As String

Set wb = ActiveWorkbook
strPath = wb.Path
If strPath = "" Then
  MsgBox "Please save your Excel Spreadsheet & try again."
  GoTo ErrorExit
End If

'GET FILE & path of Word Doc/Dot
strPathFile = strOpenFilePath 'call a function in MOD1

If strPathFile = "" Then
  MsgBox "Please choose a Word Document (DOC*) or Template (DOT*) & try again." 'strPath = Application.TemplatesPath
  GoTo ErrorExit
End If

    If FileLocked(strPathFile) Then 'Err.Number = 70 if open
    'read / write file in use 'do something
    'NONE OF THESE WORK
        Set wrdApp = GetObject(strPathFile, "Word.Application")
        'Set wrdApp = Word.Documents("This is a test doc 2.docx")
    'Set wrdApp = GetObject(strPathFile).Application
    Else
    'all ok 'Create a new Word Session
            Set wrdApp = CreateObject("Word.Application")
            wrdApp.Visible = True
            wrdApp.Activate 'bring word visiable so erros do not get hidden.
    'Open document in word
            Set wrdDoc = wrdApp.Documents.Open(Filename:=strPathFile) 'Open vs wrdApp.Documents.Add(strPathFile)<=>create new Document1 doc
    End If

'Loop through names in the activeworkbook
    For Each xlName In wb.Names

            If Range(xlName).Cells.Count = 1 Then
                  celldata = Range(xlName.Value)
                  'do nothing
               Else
                  For Each cell In Range(xlName)
                     If str = "" Then
                        str = cell.Value
                     Else
                        str = str & vbCrLf & cell.Value
                     End If
                  Next cell
                  'MsgBox str
                  celldata = str
               End If

'Get format and strip away the spacing, negative color etc etc
'I know this is not right... it works but not best
            theformat = Application.Range(xlName).DisplayFormat.NumberFormat
            If Len(theformat) > 8 Then
                theformat = Left(theformat, 5) 'was 8 but dont need cents
            Else
                'do nothing for now
            End If

        If wrdDoc.Bookmarks.Exists(xlName.Name) Then
            'Copy the Bookmark's Range.
            Set BMRange = wrdDoc.Bookmarks(xlName.Name).Range.Duplicate
            BMRange.Text = Format(celldata, theformat)
            'Re-insert the bookmark
            wrdDoc.Bookmarks.Add xlName.Name, BMRange
        End If

    Next xlName

'Activate word and display document
  With wrdApp
      .Selection.Goto What:=1, Which:=2, Name:=1  'PageNumber
      .Visible = True
      .ActiveWindow.WindowState = wdWindowStateMaximize 'WAS 0 is this needed???
      .Activate
  End With
  GoTo WeAreDone

'Release the Word object to save memory and exit macro
ErrorExit:
    MsgBox "Thank you! Bye."
    Set wrdDoc = Nothing
    Set wrdApp = Nothing
   Exit Sub

'Error Handling routine
ErrorHandler:
   If Err Then
      MsgBox "Error No: " & Err.Number & "; There is a problem"
      If Not wrdApp Is Nothing Then
        wrdApp.Quit False
      End If
      Resume ErrorExit
   End If

WeAreDone:
Set wrdDoc = Nothing
Set wrdApp = Nothing

End Sub
</code>```

file picking:

```<code>Function strOpenFilePath() As String
Dim intChoice As Integer
Dim iFileSelect As FileDialog 'B

Set iFileSelect = Application.FileDialog(msoFileDialogOpen)

With iFileSelect
    .AllowMultiSelect = False 'only allow the user to select one file
    .Title = "Please... Select MS-WORD Doc*/Dot* Files"
    .Filters.Clear
    .Filters.Add "MS-WORD Doc*/Dot*  Files", "*.do*"
    .InitialView = msoFileDialogViewDetails
End With

'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'get the file path selected by the user
    strOpenFilePath = Application.FileDialog( _
    msoFileDialogOpen).SelectedItems(1)
Else
    'nothing yet
End If

End Function
</code>```

checking if file is open...

```<code>Function FileLocked(strFileName As String) As Boolean
   On Error Resume Next
   ' If the file is already opened by another process,
   ' and the specified type of access is not allowed,
   ' the Open operation fails and an error occurs.
   Open strFileName For Binary Access Read Write Lock Read Write As #1
   Close #1
   ' If an error occurs, the document is currently open.
   If Err.Number <> 0 Then
      ' Display the error number and description.
      MsgBox "Function FileLocked Error #" & str(Err.Number) & " - " & Err.Description
      FileLocked = True
      Err.Clear
   End If
End Function
</code>```

答:
This should get you the object you need.</p>

```<code>Dim WRDFile As Word.Application
Set WRDFile = GetObject(strPathFile)
</code>```

Body:
I am new to VBA and obviously I am missing something. My code works for opening a word doc and sending data to it BUT does NOT for an ALREADY OPEN word doc. I keep searching for an answer on how to send info from Excel to an OPEN Word doc/Bookmark and nothing works.

I hope it is okay that I added all the code and the functions called. I really appreciate your help!

What I have so far

Sub ExcelNamesToWordBookmarks()
On Error GoTo ErrorHandler

Dim wrdApp As Object 'Word.Application
Dim wrdDoc As Object 'Word.Document
Dim xlName As Excel.Name
Dim ws As Worksheet
Dim str As String 'cell/name value
Dim cell As Range
Dim celldata As Variant 'added to use in the test
Dim theformat As Variant 'added
Dim BMRange As Object
Dim strPath As String
Dim strFile As String
Dim strPathFile As String

Set wb = ActiveWorkbook
strPath = wb.Path
If strPath = "" Then
  MsgBox "Please save your Excel Spreadsheet & try again."
  GoTo ErrorExit
End If

'GET FILE & path of Word Doc/Dot
strPathFile = strOpenFilePath 'call a function in MOD1

If strPathFile = "" Then
  MsgBox "Please choose a Word Document (DOC*) or Template (DOT*) & try again." 'strPath = Application.TemplatesPath
  GoTo ErrorExit
End If

    If FileLocked(strPathFile) Then 'Err.Number = 70 if open
    'read / write file in use 'do something
    'NONE OF THESE WORK
        Set wrdApp = GetObject(strPathFile, "Word.Application")
        'Set wrdApp = Word.Documents("This is a test doc 2.docx")
    'Set wrdApp = GetObject(strPathFile).Application
    Else
    'all ok 'Create a new Word Session
            Set wrdApp = CreateObject("Word.Application")
            wrdApp.Visible = True
            wrdApp.Activate 'bring word visiable so erros do not get hidden.
    'Open document in word
            Set wrdDoc = wrdApp.Documents.Open(Filename:=strPathFile) 'Open vs wrdApp.Documents.Add(strPathFile)<=>create new Document1 doc
    End If

'Loop through names in the activeworkbook
    For Each xlName In wb.Names

            If Range(xlName).Cells.Count = 1 Then
                  celldata = Range(xlName.Value)
                  'do nothing
               Else
                  For Each cell In Range(xlName)
                     If str = "" Then
                        str = cell.Value
                     Else
                        str = str & vbCrLf & cell.Value
                     End If
                  Next cell
                  'MsgBox str
                  celldata = str
               End If

'Get format and strip away the spacing, negative color etc etc
'I know this is not right... it works but not best
            theformat = Application.Range(xlName).DisplayFormat.NumberFormat
            If Len(theformat) > 8 Then
                theformat = Left(theformat, 5) 'was 8 but dont need cents
            Else
                'do nothing for now
            End If

        If wrdDoc.Bookmarks.Exists(xlName.Name) Then
            'Copy the Bookmark's Range.
            Set BMRange = wrdDoc.Bookmarks(xlName.Name).Range.Duplicate
            BMRange.Text = Format(celldata, theformat)
            'Re-insert the bookmark
            wrdDoc.Bookmarks.Add xlName.Name, BMRange
        End If

    Next xlName

'Activate word and display document
  With wrdApp
      .Selection.Goto What:=1, Which:=2, Name:=1  'PageNumber
      .Visible = True
      .ActiveWindow.WindowState = wdWindowStateMaximize 'WAS 0 is this needed???
      .Activate
  End With
  GoTo WeAreDone

'Release the Word object to save memory and exit macro
ErrorExit:
    MsgBox "Thank you! Bye."
    Set wrdDoc = Nothing
    Set wrdApp = Nothing
   Exit Sub

'Error Handling routine
ErrorHandler:
   If Err Then
      MsgBox "Error No: " & Err.Number & "; There is a problem"
      If Not wrdApp Is Nothing Then
        wrdApp.Quit False
      End If
      Resume ErrorExit
   End If

WeAreDone:
Set wrdDoc = Nothing
Set wrdApp = Nothing

End Sub

file picking:

Function strOpenFilePath() As String
Dim intChoice As Integer
Dim iFileSelect As FileDialog 'B

Set iFileSelect = Application.FileDialog(msoFileDialogOpen)

With iFileSelect
    .AllowMultiSelect = False 'only allow the user to select one file
    .Title = "Please... Select MS-WORD Doc*/Dot* Files"
    .Filters.Clear
    .Filters.Add "MS-WORD Doc*/Dot*  Files", "*.do*"
    .InitialView = msoFileDialogViewDetails
End With

'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'get the file path selected by the user
    strOpenFilePath = Application.FileDialog( _
    msoFileDialogOpen).SelectedItems(1)
Else
    'nothing yet
End If

End Function

checking if file is open...

Function FileLocked(strFileName As String) As Boolean
   On Error Resume Next
   ' If the file is already opened by another process,
   ' and the specified type of access is not allowed,
   ' the Open operation fails and an error occurs.
   Open strFileName For Binary Access Read Write Lock Read Write As #1
   Close #1
   ' If an error occurs, the document is currently open.
   If Err.Number <> 0 Then
      ' Display the error number and description.
      MsgBox "Function FileLocked Error #" & str(Err.Number) & " - " & Err.Description
      FileLocked = True
      Err.Clear
   End If
End Function

Body:
This should get you the object you need.

Dim WRDFile As Word.Application
Set WRDFile = GetObject(strPathFile)


来源: stackexchange

问:
Android - Problem with AsyncTask
I needs to make a call to a webservice for 5 times(as there are 5 different parameters) one by one or all at once. Once a particular call completed, in background a textview should be updated with text as: "1st completed", "2nd Completed" and so on.

TextView value should be updated in background.

What should i do ? I am knowing the concept of AsyncTask, but i am confused that should i write 5 AsyncTask and then for each i write execute() method to execute the AsyncTask?

I am successful for only 1 one call, as i set "1st completed" in postExecute() method. But confused for the 5 times call.

Please suggest me a better way or exact solution.

答:
You only need 1 AsyncTask, you have to do all 5 calls in the doInBackground() and everytime you complete one call the publishProgress passing for example the number of the completed call, then, at the end do whatever you need in onPostExecute.

A simple approach:

```<code>private class ServiceCallTask extends AsyncTask<String, Integer, Void> {

    protected void onPreExecute() {
        //prepare whatever you need
        myTextField.setText("starting calls");
    }

    protected Void doInBackground(String... params) {
        //process params as you need and make the calls
        doCall1();
        publishProgress(1); //this calls onProgressUpdate(1)
        doCall2();
        publishProgress(2);
        doCall3();
        publishProgress(3);
        doCall4();
        publishProgress(4);
        doCall5();
        publishProgress(5);
        return;
    }

    protected void onProgressUpdate(Integer... progress) {
        //this runs in UI thread so its safe to modify the UI
        myTextField.append("finished call " + progress);
    }

     protected void onPostExecute(Void unused) {
        myTextField.append("all calls finished");
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Android - Problem with AsyncTask

Body:
You only need 1 AsyncTask, you have to do all 5 calls in the doInBackground() and everytime you complete one call the publishProgress passing for example the number of the completed call, then, at the end do whatever you need in onPostExecute.

A simple approach:

private class ServiceCallTask extends AsyncTask<String, Integer, Void> {

    protected void onPreExecute() {
        //prepare whatever you need
        myTextField.setText("starting calls");
    }

    protected Void doInBackground(String... params) {
        //process params as you need and make the calls
        doCall1();
        publishProgress(1); //this calls onProgressUpdate(1)
        doCall2();
        publishProgress(2);
        doCall3();
        publishProgress(3);
        doCall4();
        publishProgress(4);
        doCall5();
        publishProgress(5);
        return;
    }

    protected void onProgressUpdate(Integer... progress) {
        //this runs in UI thread so its safe to modify the UI
        myTextField.append("finished call " + progress);
    }

     protected void onPostExecute(Void unused) {
        myTextField.append("all calls finished");
    }
}


问:
AkkaHttp: Process incoming requests in parallel with multiple processes
Using AkkaHttp with Scala, the following code provides an endpoint for /api/endpoint/{DoubleNumber}. Querying this endpoint triggers a heavy computation and then returns the result as application/json.

```<code>import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer

object Run {
  def main(args: Array[String]) = {
    implicit val system = ActorSystem("myApi")
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    val e = get {
      path("api/endpoint" / DoubleNumber) {
        case (myNumberArgument) {
          val result = someHeavyComputation(myNumberArgument)
          complete(HttpEntity(ContentTypes.`application/json`, result.toString))
        }
      }
    }
  }
}
</code>```

If one sends several concurrent requests from, say, a browser's console, the above code will wait for each request to be completed (and the response returned) before starting to handle the next one.

How to fix the above code to make it work in parallel, in other words launch an additional process for each incoming request, if previous requests are still being processed?

答:
Looks like I came to an answer.

If you have the same problem, simply call someHeavyComputation from inside the complete() block, not before:

```<code>val e = get {
  path("api/endpoint" / DoubleNumber) {
    case (myNumberArgument) {
      complete {
        val result = someHeavyComputation(myNumberArgument)
        HttpEntity(ContentTypes.`application/json`, result.toString)
      }
    }
  }
}
</code>```

New processes will be launched as necessary.

ContentLicense: CC BY-SA 3.0

Body:
Using AkkaHttp with Scala, the following code provides an endpoint for /api/endpoint/{DoubleNumber}. Querying this endpoint triggers a heavy computation and then returns the result as application/json.

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer

object Run {
  def main(args: Array[String]) = {
    implicit val system = ActorSystem("myApi")
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    val e = get {
      path("api/endpoint" / DoubleNumber) {
        case (myNumberArgument) {
          val result = someHeavyComputation(myNumberArgument)
          complete(HttpEntity(ContentTypes.`application/json`, result.toString))
        }
      }
    }
  }
}

If one sends several concurrent requests from, say, a browser's console, the above code will wait for each request to be completed (and the response returned) before starting to handle the next one.

How to fix the above code to make it work in parallel, in other words launch an additional process for each incoming request, if previous requests are still being processed?

Body:
Looks like I came to an answer.

If you have the same problem, simply call someHeavyComputation from inside the complete() block, not before:

val e = get {
  path("api/endpoint" / DoubleNumber) {
    case (myNumberArgument) {
      complete {
        val result = someHeavyComputation(myNumberArgument)
        HttpEntity(ContentTypes.`application/json`, result.toString)
      }
    }
  }
}

New processes will be launched as necessary.


问:
SSIS user variable not updating after project is deployed to the catalog
I have a control flow that sets a user variable with an Execute SQL task. Everything works fine in Visual Studio but once I deploy it to the SSIS catalog the variable doesn't seem to get assigned. I'm executing it against the exact same data sources.

I'll explain exactly what is going on...

The first task in the sequence container reads the last LSN recorded for the table from a state table. If there is no entry for the table then it follows path 1 in the diagram above.

At step 2 it reads the minimum LSN for the table using the CDC functions on the source database. It then stores the LSN and the datetime for that LSN in two user variables. This is the "window start" for the data replication.

Step 3 reads the maximum change date from the destination table.

Step 4 branches if the window start is before the latest change date because this will cause duplicate data to be imported into the destination table. (Suffice to say there are reasons I can't deduplicate before loading into the destination table...)

When I run the project in Visual Studio everything works fine. It moves through steps 1-3 and then goes on to the DFT because the minimum LSN for the table is after the maximum change date in the destination table. I've used break points to ensure that the variables are actually getting set correctly.

Once I deploy the project to an SSIS catalog it follows down step 4 and records the error row. It doesn't seem to set the variable or the constraint expressions aren't using the correct value. I've tried setting the variables with the result set and as output parameters in the Execute SQL task. I can see from the log message that the maximum change date from the source table is correct.

One odd thing is that the value of the variable in the log message isn't the same as the design time value. The design time value is "1899-12-25 14:20:00' but the log message shows '1899-12-30 00:00:00'. But this may be down to me using the wrong conversion method or something... I haven't looked into it much because it should still not follow path 4.

The fact that it runs as expected in Visual Studio but has a different behaviour on he server is very confusing to me. I cannot think of what could cause that.

The packages are created using BIML but I don't think that actually has any connection. The full solution replicates over 100 tables with one package per table. The problem persists even when I try a debug deployment of only a single package.

答:
Verify the account running the SSIS has permissions to query the source tables. SSIS doesn't always error out in the way you'd expect with regard to insufficient permissions.

My favorite is a Foreach File loop always returning an empty file list with a little warning of "couldn't find the path"

I'm guessing there's a nuance to reading the LSN from CDC functions at play here


问:
Why to upload file to AWS by writing to disk first?
This example uses a file which most likely resides not in RAM:

http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpJava.html

but I already got a buffered file from a certain client request and in the code below, this file gets written to disk, but why ? it makes the whole process slow by writing to disk, can't I avoid it?

EDIT (Below is explanation of what I am trying to achieve):

A user's image is uploaded then scaled by the server and then saved on the server's disk and only then this scaled image is sent to AWS, afterwards the user gets an aws link where the image resides on the amazon server.

```<code>public void transferToS3(String region, String bucket, String entity, String resolution, String filename, BufferedImage bufferedImage) {
    if (bufferedImage != null) {
        String objectpath = "/" + "images" + "/" + entity + "/" + resolution + "/" + filename + "." + "png";

        Path tmpFile = null;
        try {
            tmpFile = Files.createTempFile(imagesPath, "tmp_", ".png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        tmpFile.toFile().deleteOnExit();

        try {
            ImageIO.write(bufferedImage, "png", tmpFile.toFile());
            S3AsyncClient client = S3AsyncClient.builder().region(Region.of(region)).build();
            CompletableFuture<PutObjectResponse> future =
                    client.putObject(PutObjectRequest.builder()
                    .bucket(bucket)
                    .key(objectpath)
                    .contentType("image/png")
                    .build(),
                    AsyncRequestProvider.fromFile(tmpFile.toAbsolutePath()));

            Path finalTmpFile = tmpFile;
            future.whenComplete((resp, err) -> {
                try {
                    if (resp != null) {
                        logger.debug(resp.toString());
                    } else {
                        logger.error(err.toString());
                    }
                    Files.deleteIfExists(finalTmpFile.toAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    FunctionalUtils.invokeSafely(client::close);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

Scaling routine returns a scaled BufferedImage which is then used in the transferToS3 method.

```<code>public BufferedImage scale(int width, int height, BufferedImage bufferedImage) {
    BufferedImage scaledBufferedImage = null;
    if (bufferedImage != null) {
        Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        scaledBufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        scaledBufferedImage.getGraphics().drawImage(image, 0, 0, null);
    }
    return scaledBufferedImage;
}
</code>```

The 2 above together:

```<code>BufferedImage scaledBufferedImage = imageService.scale(width, height finalBufferedImage);
imageService.transferToS3(region, bucket, name, k, file, scaledBufferedImage);
</code>```

答:
You can do whatever you wish with the data stream from the request. Feel free to scale the image in memory and send it back in the response. The example you linked writes the file to disk because this is by far the most common scenario. It also allows the author to focus on the details of uploading a file without polluting the example with unrelated code.

Note that bufferedImage is not a file. It is a stream. I suspect the author saved the image to disk in order to avoid assuming anything about the size of the image. If the image is too large to fit in RAM, then you will have difficulties doing the scaling in memory.

Body:
This example uses a file which most likely resides not in RAM:

http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpJava.html

but I already got a buffered file from a certain client request and in the code below, this file gets written to disk, but why ? it makes the whole process slow by writing to disk, can't I avoid it?

EDIT (Below is explanation of what I am trying to achieve):

A user's image is uploaded then scaled by the server and then saved on the server's disk and only then this scaled image is sent to AWS, afterwards the user gets an aws link where the image resides on the amazon server.

public void transferToS3(String region, String bucket, String entity, String resolution, String filename, BufferedImage bufferedImage) {
    if (bufferedImage != null) {
        String objectpath = "/" + "images" + "/" + entity + "/" + resolution + "/" + filename + "." + "png";

        Path tmpFile = null;
        try {
            tmpFile = Files.createTempFile(imagesPath, "tmp_", ".png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        tmpFile.toFile().deleteOnExit();

        try {
            ImageIO.write(bufferedImage, "png", tmpFile.toFile());
            S3AsyncClient client = S3AsyncClient.builder().region(Region.of(region)).build();
            CompletableFuture<PutObjectResponse> future =
                    client.putObject(PutObjectRequest.builder()
                    .bucket(bucket)
                    .key(objectpath)
                    .contentType("image/png")
                    .build(),
                    AsyncRequestProvider.fromFile(tmpFile.toAbsolutePath()));

            Path finalTmpFile = tmpFile;
            future.whenComplete((resp, err) -> {
                try {
                    if (resp != null) {
                        logger.debug(resp.toString());
                    } else {
                        logger.error(err.toString());
                    }
                    Files.deleteIfExists(finalTmpFile.toAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    FunctionalUtils.invokeSafely(client::close);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Scaling routine returns a scaled BufferedImage which is then used in the transferToS3 method.

public BufferedImage scale(int width, int height, BufferedImage bufferedImage) {
    BufferedImage scaledBufferedImage = null;
    if (bufferedImage != null) {
        Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        scaledBufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        scaledBufferedImage.getGraphics().drawImage(image, 0, 0, null);
    }
    return scaledBufferedImage;
}

The 2 above together:

BufferedImage scaledBufferedImage = imageService.scale(width, height finalBufferedImage);
imageService.transferToS3(region, bucket, name, k, file, scaledBufferedImage);


问:
Is it possible to fetch and use a file from cloud storage at when deploying a cloud function
I have a firebase function that makes use of a SQLite database (read-only) which is currently uploaded along with the function.

The problem is that the db file is quite large and gets uploaded every time the function is changed. Is there a way to fetch this file from cloud storage during the installation process (during firebase deploy) - without hard-coding the URL in the source files?

答:
What you're trying to do is problematic because your code running in Cloud Functions may actually be running on any number of server instances, determined by the load on your project.  As such, downloading a file once at the time of deployment isn't going to naturally affect all the instances that maybe created or destroyed at any given moment.

It's far better to keep doing what you're doing, and include your extra data during deployment.  When a new instance is spun up to handle events for your function, the file will be immediately ready to help service requests.


问:
PHP Display as long as field is unique
In my MySQL table, there are several rows which share the same "case number". I want to display the case numbers on a page but do not want cases which have multiple rows to be displayed more than once. This is basically the code I am using:

```<code>//select all records
$query="SELECT * FROM cases ";
$rt=mysql_query($query);
echo mysql_error();

while($nt=mysql_fetch_array($rt)){

echo $nt['case'];
echo $nt['date_created'];

}
</code>```

Any ideas?

答: Use an array in which the current case numbers are present. Loop through the list every time to prevent duplicates.

Title: PHP Display as long as field is unique

Body:
In my MySQL table, there are several rows which share the same "case number". I want to display the case numbers on a page but do not want cases which have multiple rows to be displayed more than once. This is basically the code I am using:

//select all records
$query="SELECT * FROM cases ";
$rt=mysql_query($query);
echo mysql_error();

while($nt=mysql_fetch_array($rt)){

echo $nt['case'];
echo $nt['date_created'];

}

Any ideas?


问:
Using property() on classmethods
I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable.  I tried to use the property() function with these, but it results in an error.  I was able to reproduce the error with the following in the interpreter:

```<code>class Foo(object):
    _var = 5
    @classmethod
    def getvar(cls):
        return cls._var
    @classmethod
    def setvar(cls, value):
        cls._var = value
    var = property(getvar, setvar)
</code>```

I can demonstrate the class methods, but they don't work as properties:

```<code>>>> f = Foo()
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
</code>```

Is it possible to use the property() function with @classmethod decorated functions?

答:
Python 3!

See @Amit Portnoy's answer for an even cleaner method in python >= 3.9

Old question, lots of views, sorely in need of a one-true Python 3 way.

Luckily, it's easy with the metaclass kwarg:

```<code>class FooProperties(type):

    @property
    def var(cls):
        return cls._var

class Foo(object, metaclass=FooProperties):
    _var = 'FOO!'
</code>```

Then, >>> Foo.var

'FOO!'

OwnerDisplayName: Mark Roddy

ContentLicense: CC BY-SA 4.0

Title: Using property() on classmethods

Body:
I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable.  I tried to use the property() function with these, but it results in an error.  I was able to reproduce the error with the following in the interpreter:

class Foo(object):
    _var = 5
    @classmethod
    def getvar(cls):
        return cls._var
    @classmethod
    def setvar(cls, value):
        cls._var = value
    var = property(getvar, setvar)

I can demonstrate the class methods, but they don't work as properties:

>>> f = Foo()
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable

Is it possible to use the property() function with @classmethod decorated functions?

LastEditorDisplayName: Mark Roddy

Body:
Python 3!

See @Amit Portnoy's answer for an even cleaner method in python >= 3.9

Old question, lots of views, sorely in need of a one-true Python 3 way.

Luckily, it's easy with the metaclass kwarg:

class FooProperties(type):

    @property
    def var(cls):
        return cls._var

class Foo(object, metaclass=FooProperties):
    _var = 'FOO!'

Then, >>> Foo.var

'FOO!'


问:
Mongodb search data except ranges
I have one collection and here is documents. Each document have own unique number, which increases:

```<code>{
    code: 1
}, {
    code: 2
}, {
    code: 3
}, {
    code: 4
}, {
    code: 5
}, {
    code: 6
}, {
    code: 7
}, {
    code: 8
}, {
    code: 9
}, {
    code: 10
}
</code>```

Now what I have to do, to get only documents which is not in range of (2, 5) and (7, 9)?

Result must be:

```<code>{
    code: 1
}, {
    code: 6
}, {
    code: 10
}
</code>```

So, I want to make this on big collection, for example collection which have 3000 document and "Except ranges" will be 4 - 5.

I tried some queries, but it's not working properly:

```<code>{ "course": ObjectId("123"), "code": { $gt: NumberInt(300) }, "code": { $lt: NumberInt(400) }, "code": { $gt: NumberInt(500) }, "code": { $lt: NumberInt(800) } }
</code>```

答:
The first solution is to use the $nor operator:

```<code>{
    $nor: [
        {"code": {$gte: 2, $lte: 5}},
        {"code": {$gte: 7, $lte: 9}}
    ]
}
</code>```

The second solution would be to use $or operator:

```<code>{
    $or: [
        {"code": {$lt: 2}},
        {"code": {$gt: 5, $lt: 7}},
        {"code": {$gt: 9}}
    ]
}
</code>```

Title: Mongodb search data except ranges

Body:
I have one collection and here is documents. Each document have own unique number, which increases:

{
    code: 1
}, {
    code: 2
}, {
    code: 3
}, {
    code: 4
}, {
    code: 5
}, {
    code: 6
}, {
    code: 7
}, {
    code: 8
}, {
    code: 9
}, {
    code: 10
}

Now what I have to do, to get only documents which is not in range of (2, 5) and (7, 9)?

Result must be:

{
    code: 1
}, {
    code: 6
}, {
    code: 10
}

So, I want to make this on big collection, for example collection which have 3000 document and "Except ranges" will be 4 - 5.

I tried some queries, but it's not working properly:

{ "course": ObjectId("123"), "code": { $gt: NumberInt(300) }, "code": { $lt: NumberInt(400) }, "code": { $gt: NumberInt(500) }, "code": { $lt: NumberInt(800) } }

Body:
The first solution is to use the $nor operator:

{
    $nor: [
        {"code": {$gte: 2, $lte: 5}},
        {"code": {$gte: 7, $lte: 9}}
    ]
}

The second solution would be to use $or operator:

{
    $or: [
        {"code": {$lt: 2}},
        {"code": {$gt: 5, $lt: 7}},
        {"code": {$gt: 9}}
    ]
}


问:
Error %d format , not list
any help please

I have this code (odoo 10)

```<code>email_from_ids = self.env['ir.config_parameter'].search(self, [('key', '=', 'auto_backup_from_email_Id')])
</code>```

I have  this error

```<code>TypeError: %d format: a number is required, not list
</code>```

I d'ont understand what mean

答:
You could try:

```<code>email_from_ids = self.env['ir.config_parameter'].search([('key', '=', 'auto_backup_from_email_Id')])
</code>```

without the self varibale in the search method. I hope this help you.

Title: Error %d format , not list

Body:
any help please

I have this code (odoo 10)

email_from_ids = self.env['ir.config_parameter'].search(self, [('key', '=', 'auto_backup_from_email_Id')])

I have  this error

TypeError: %d format: a number is required, not list

I d'ont understand what mean

Body:
You could try:

email_from_ids = self.env['ir.config_parameter'].search([('key', '=', 'auto_backup_from_email_Id')])

without the self varibale in the search method. I hope this help you.


问:
DI: How much to inject?
I'm writing my second real life application, which uses DI. Overall I think it have let to a better design. But there are some code smells, that I don't know how to solve.

I prefer to use constructor injection and have often observed that I need about 5 or more objects to be injected in the constructor. It seems to be too many, maybe it's a design problem, not getting the SRP right. But I think that my use of DI also is to be blamed.

I'm looking for "best practices" or "rule of thumb", in general I seem to inject everything, that isn't in the .Net framework, is that overdoing it?

To get things started, here are two examples of objects that I inject, but am uncertain about.

Objects that are true singletons like application configuration or those small util classes, do you inject them?
They seems to be injected very often, the only reason to inject them seems to be allow to change the value for testing, but Ayende seems to have solved the problem in another way: http://ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx.

Common objects such as logging, that are used in almost every object, should they be injected?

答:
My personal rule of thumb is this:

inject it if you want it to be immutable

inject it if you want to be able to substitute it for testing purposes

Things like services can meet both of those criteria - the consumer should never change it, and you want to be able to substitute it come testing time. With the immutable items, you would still possibly have a property on the consuming object, but that property would only have a getter, not a setter. If you wanted to change the value you have to create a new instance of the object.

Should loggers be injected?

There is no reason to. Loggers are typically exposed via a static class, and are new'ed up from configuration entries, so even for testing purposes there is no need to inject them.

Should true singletons like application configuration be injected?

Once again, it is a globally accessible object which is easily modified for test purposes, so no need to inject. The only time i would inject this is if the consumer was 'disconnected'; i.e. created via reflection or called as a web service or remote object.

While DI is a nice pattern, too much of a good thing can still be unhealthy. If you sense a growing code smell, then examine each item you are injecting and ask yourself the question: Do i NEED to inject this parameter?

Title: DI: How much to inject?


问:
Checking value in an array from another array
So I wanted to see if it was possible to find values of two array's that are equal to each other but I am unsure how to do that.
This is what I have so far:

```<code>unusedArray = ["AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH", "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC"]
</code>```

value10 = ["10S", "10C", "10H", "10D"]

```<code>x = 0

for value10 in unusedArray:
   print(x)
   x += 1
</code>```

The printing of x is just to see how many times the for loop is running. Instead of the loop only running 4 times it runs 52(amount of values in the unusedArray)

Body:
So I wanted to see if it was possible to find values of two array's that are equal to each other but I am unsure how to do that.
This is what I have so far:

unusedArray = ["AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH", "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC"]

value10 = ["10S", "10C", "10H", "10D"]

x = 0

for value10 in unusedArray:
   print(x)
   x += 1

The printing of x is just to see how many times the for loop is running. Instead of the loop only running 4 times it runs 52(amount of values in the unusedArray)

Body:
You can use list comprehension:

unusedArray = ["AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH", "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC"]

value10 = ["10S", "10C", "10H", "10D"]
final_List = [i for i in unusedArray if i in value10]

Output:

['10S', '10D', '10H', '10C']


问:
Adding a table tag via JavaScript with a dashed parameter
I am trying to add a Bootstrap Table table tag with Javascript. One of the parameters for the table tag is data-pagination. This method of adding it, is failing due to the -.

How can I work around this?

Desired Output:

```<code><table id="mytable" data-pagination="true" class="table table-striped"></table>
</code>```

My code:

```<code>var table_div = document.createElement('table');
table_div.id = 'mytable';
table_div.className = "table table-striped";
table_div.data-pagination = "true";
document.body.appendChild(table_div);
</code>```

答:
You could use the dataset in this case like :

```<code>table_div.dataset.pagination = true;
</code>```

Hope this helps.

var table_div = document.createElement('table');
table_div.id = 'mytable';
table_div.className = "table table-striped";
table_div.dataset.pagination = "true";
document.body.appendChild(table_div);

console.log(document.body.innerHTML)```

Body:
I am trying to add a Bootstrap Table table tag with Javascript. One of the parameters for the table tag is data-pagination. This method of adding it, is failing due to the -.

How can I work around this?

Desired Output:

My code:

var table_div = document.createElement('table');
table_div.id = 'mytable';
table_div.className = "table table-striped";
table_div.data-pagination = "true";
document.body.appendChild(table_div);

Body:
You could use the dataset in this case like :

table_div.dataset.pagination = true;

Hope this helps.

var table_div = document.createElement('table');
table_div.id = 'mytable';
table_div.className = "table table-striped";
table_div.dataset.pagination = "true";
document.body.appendChild(table_div);

console.log(document.body.innerHTML)


问:
Python/pygame Button functionality
I'm creating a quiz based game, I currently have a main menu form called Quiz.py as shown below in the code, this is simply to build my main menu. This is then imported into another file called Maths.py which is currently one of the 3 tests I will be building.

My questions is, how can I code the buttons in my Maths.py file so that when the maths button is clicked by the user they start a cycle of randomly generated maths question.

Here is the code in my quiz file

```<code>import random
import time # these are importing everything I will need for my program.
import pygame
pygame.init() # Initiates pygame so it runs.
display_width = 1600 # This sets the boundaries of the pygame screen
display_height = 800
gamedisplay = pygame.display.set_mode((display_width,display_height))
white = (255,255,255)
black = (000,000,000)
grey = (169,169,169)
clock = pygame.time.Clock()
buttonheight = 100
buttonwidth = 250
class Button:
    x=0
    y=0
    height=100
    width=250

    body = None
    text="Maths"

    def __init__(self):
        self.body = pygame.Rect(self.x, self.y, self.width, self.height)

    def setText(self, textOfButton):
        self.text = textOfButton

    def clicked(self):
        print("test")

    def checkClicked(self):
        click = pygame.mouse.get_pressed()
        x, y = 0,1
        click = 0
        if pygame.mouse.get_pos()[x] > self.x and pygame.mouse.get_pos()[x] < self.x + self.width:
            if pygame.mouse.get_pos()[y] > self.y and pygame.mouse.get_pos()[y] < self.y + self.height:
                self.clicked()

    def draw(self):
        smallText = pygame.font.Font ('RINGM___.ttf',20, )
        TextSurf, TextRect = text_objectsW(self.text,smallText)
        TextRect.center = ( (self.x+(self.width/2)), (self.y+(self.height/2)))

        pygame.draw.rect(gamedisplay, black, self.body)
        gamedisplay.blit(TextSurf, TextRect)

        #gamedisplay.blit(smallText.render(self.text, False, white), TextRect)

class mathsButton(Button):
    def __init__(self):
        self.x = 95
        self.y = 400
        self.text = "Maths"
        super().__init__()

class historyButton(Button):
    def __init__(self):
        self.x=690
        self.y=400
        self.text = "History"
        super().__init__()

class englishButton (Button):
    def __init__(self):
        self.x=1255
        self.y=400
        self.text="English"
        super().__init__()

def text_objectsB (text, font): # These 2 functions are the same with the colour of the text being the exception.  its renders the text and its colour
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()
def text_objectsW (text, font):
    textSurface = font.render(text, True, white)
    return textSurface, textSurface.get_rect()

my_image = pygame.image.load('Background2.jpg').convert()
gamedisplay.blit(my_image, [0,0])
intro = True
btnMaths = mathsButton()
btnHistory = historyButton()
btnEnglish = englishButton()

def main_menu():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                btnMaths.checkClicked()
                btnHistory.checkClicked()
                btnEnglish.checkClicked()
        largetext = pygame.font.Font('RINGM___.ttf',80)
        TextSurf, TextRect = text_objectsB("Are you smarter than a 13 year old?", largetext)
        TextRect.center = ((display_width/2),(display_height/6))
        gamedisplay.blit(TextSurf, TextRect)
        #button("Maths Quiz",95,400,black,grey,"Maths")
        #button("English Quiz",675,400,black,grey,"English")
        #button("History Quiz",1255,400,black,grey,"History")
        btnMaths.draw()
        btnHistory.draw()
        btnEnglish.draw()
        pygame.display.update()
        clock.tick(60)
</code>```

And here is the code for my Maths file

```<code>import pygame
import random, time
import Quiz
t0 = time.time()
while True:
    Quiz.main_menu()
    if time.time() - t0 > 5:
        Quiz.btnMaths.setText("New Text") # This code is proof on concept that I can change the text in this box
</code>```

Thanks for any help you can provide.

答:
I would say return a boolean in the checkClicked function.

```<code>def checkClicked(self):
    click = pygame.mouse.get_pressed()
    x, y = 0,1
    click = 0
    if pygame.mouse.get_pos()[x] > self.x and pygame.mouse.get_pos()[x] < self.x + self.width:
        if pygame.mouse.get_pos()[y] > self.y and pygame.mouse.get_pos()[y] < self.y + self.height:
            return True
        else:
            return False
</code>```

and then an if statement in the program loop

```<code>if checkClicked() == True:
    StartQuestions()
</code>```

Title: Python/pygame Button functionality

Body:
I'm creating a quiz based game, I currently have a main menu form called Quiz.py as shown below in the code, this is simply to build my main menu. This is then imported into another file called Maths.py which is currently one of the 3 tests I will be building.

My questions is, how can I code the buttons in my Maths.py file so that when the maths button is clicked by the user they start a cycle of randomly generated maths question.

Here is the code in my quiz file

import random
import time # these are importing everything I will need for my program.
import pygame
pygame.init() # Initiates pygame so it runs.
display_width = 1600 # This sets the boundaries of the pygame screen
display_height = 800
gamedisplay = pygame.display.set_mode((display_width,display_height))
white = (255,255,255)
black = (000,000,000)
grey = (169,169,169)
clock = pygame.time.Clock()
buttonheight = 100
buttonwidth = 250
class Button:
    x=0
    y=0
    height=100
    width=250

    body = None
    text="Maths"

    def __init__(self):
        self.body = pygame.Rect(self.x, self.y, self.width, self.height)

    def setText(self, textOfButton):
        self.text = textOfButton

    def clicked(self):
        print("test")

    def checkClicked(self):
        click = pygame.mouse.get_pressed()
        x, y = 0,1
        click = 0
        if pygame.mouse.get_pos()[x] > self.x and pygame.mouse.get_pos()[x] < self.x + self.width:
            if pygame.mouse.get_pos()[y] > self.y and pygame.mouse.get_pos()[y] < self.y + self.height:
                self.clicked()

    def draw(self):
        smallText = pygame.font.Font ('RINGM___.ttf',20, )
        TextSurf, TextRect = text_objectsW(self.text,smallText)
        TextRect.center = ( (self.x+(self.width/2)), (self.y+(self.height/2)))

        pygame.draw.rect(gamedisplay, black, self.body)
        gamedisplay.blit(TextSurf, TextRect)

        #gamedisplay.blit(smallText.render(self.text, False, white), TextRect)

class mathsButton(Button):
    def __init__(self):
        self.x = 95
        self.y = 400
        self.text = "Maths"
        super().__init__()

class historyButton(Button):
    def __init__(self):
        self.x=690
        self.y=400
        self.text = "History"
        super().__init__()

class englishButton (Button):
    def __init__(self):
        self.x=1255
        self.y=400
        self.text="English"
        super().__init__()

def text_objectsB (text, font): # These 2 functions are the same with the colour of the text being the exception.  its renders the text and its colour
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()
def text_objectsW (text, font):
    textSurface = font.render(text, True, white)
    return textSurface, textSurface.get_rect()

my_image = pygame.image.load('Background2.jpg').convert()
gamedisplay.blit(my_image, [0,0])
intro = True
btnMaths = mathsButton()
btnHistory = historyButton()
btnEnglish = englishButton()

def main_menu():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                btnMaths.checkClicked()
                btnHistory.checkClicked()
                btnEnglish.checkClicked()
        largetext = pygame.font.Font('RINGM___.ttf',80)
        TextSurf, TextRect = text_objectsB("Are you smarter than a 13 year old?", largetext)
        TextRect.center = ((display_width/2),(display_height/6))
        gamedisplay.blit(TextSurf, TextRect)
        #button("Maths Quiz",95,400,black,grey,"Maths")
        #button("English Quiz",675,400,black,grey,"English")
        #button("History Quiz",1255,400,black,grey,"History")
        btnMaths.draw()
        btnHistory.draw()
        btnEnglish.draw()
        pygame.display.update()
        clock.tick(60)

And here is the code for my Maths file

import pygame
import random, time
import Quiz
t0 = time.time()
while True:
    Quiz.main_menu()
    if time.time() - t0 > 5:
        Quiz.btnMaths.setText("New Text") # This code is proof on concept that I can change the text in this box

Thanks for any help you can provide.

Body:
I would say return a boolean in the checkClicked function.

def checkClicked(self):
    click = pygame.mouse.get_pressed()
    x, y = 0,1
    click = 0
    if pygame.mouse.get_pos()[x] > self.x and pygame.mouse.get_pos()[x] < self.x + self.width:
        if pygame.mouse.get_pos()[y] > self.y and pygame.mouse.get_pos()[y] < self.y + self.height:
            return True
        else:
            return False

and then an if statement in the program loop

if checkClicked() == True:
    StartQuestions()


问:
Format Array to feed into Smash Table Widget
I am creating a Smashing Dashboard that is required to feed information from an xlsx file into a table on the dashboard. This system is running on a Raspberry Pi.

I am able to read from the spreadsheet using the roo gem, this works fine. However the table widget only accepts data in the form

```<code>[
    {:cols=>[
        {:class=>"left", :value=>"Office", :style=>"color: #FFFFFF"},
        {:class=>"left", :value=>"Aberdeen"},
        {:class=>"left", :value=>"Australia"},
        {:class=>"left", :value=>"Eurocentral"},

        ]
    },
    {:cols=>[{:class=>"left", :value=>"Number", :style=>"color: #FFFFFF"},
        {:value=>"1234"},
        {:value=>"5454"},
        {:value=>"9999"}
        ]
    }
]
</code>```

I am uncertain on how to go about forming an array in this format. I have attempted to loop through the cells in a column and put these into an array then to push these column arrays into a rows array. Below is the code I've written which is far off.

```<code>i = 0
    maxRows = is.last_row
    maxCols = is.last_column

    rows = []

    #Loop from the first row to the last
    loop do

        #Break out of the loop if we're done
        if (i > maxRows)
            break
        end

         #Put the row into the array as a new row

        j = 0
        cols = []
        loop do
            cols[j] = "{:value=> #{is.cell(i,j)}}"
            j +=1

            if (j > maxRows)
                break
            end

        end

        #rows.push(cols)

    end
</code>```

I'd appreciate any help on the matter. Resources I need to read, procedures I'm clearly unaware of or anything like this.

答:
It was quite a pain to get this working but I eventually got there.

Just incase anyone comes across this via google.

The desired format is an Array containing a new hash at each index, with each hash having a cols key which contains an array where each index is a column in the table. These are further contained within a hash which includes the various keys that are used to render the table.

Body:
I am creating a Smashing Dashboard that is required to feed information from an xlsx file into a table on the dashboard. This system is running on a Raspberry Pi.

I am able to read from the spreadsheet using the roo gem, this works fine. However the table widget only accepts data in the form

[
    {:cols=>[
        {:class=>"left", :value=>"Office", :style=>"color: #FFFFFF"},
        {:class=>"left", :value=>"Aberdeen"},
        {:class=>"left", :value=>"Australia"},
        {:class=>"left", :value=>"Eurocentral"},

        ]
    },
    {:cols=>[{:class=>"left", :value=>"Number", :style=>"color: #FFFFFF"},
        {:value=>"1234"},
        {:value=>"5454"},
        {:value=>"9999"}
        ]
    }
]

I am uncertain on how to go about forming an array in this format. I have attempted to loop through the cells in a column and put these into an array then to push these column arrays into a rows array. Below is the code I've written which is far off.

i = 0
    maxRows = is.last_row
    maxCols = is.last_column

    rows = []

    #Loop from the first row to the last
    loop do

        #Break out of the loop if we're done
        if (i > maxRows)
            break
        end

         #Put the row into the array as a new row

        j = 0
        cols = []
        loop do
            cols[j] = "{:value=> #{is.cell(i,j)}}"
            j +=1

            if (j > maxRows)
                break
            end

        end

        #rows.push(cols)

    end

I'd appreciate any help on the matter. Resources I need to read, procedures I'm clearly unaware of or anything like this.


问:
How to Listen for Events in children components in React Native?
I want to implement an event listener from parents to children components in my React Native app, I'm using a StackNavigator as a router.

How can I listen for events occurred in the top/parent components?

答:
I've been researching in how to emit and listen events from a Parent component to a Child component in React Native, after trying different ways I think that it could be good to share how I have got it working.

In your parent component (App.js in my case), import the EventEmitter lib:

```<code>import EventEmitter from 'EventEmitter';
</code>```

Create a variable instance of the Event Emitter:

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

...

  componentWillMount() {
    this.eventEmitter = new EventEmitter();
  }

...

}
</code>```

Then, when something happens emit the event:

```<code>this.eventEmitter.emit('Event-Name', {args});
</code>```

As I'm using a StackNavigator as a router I have to pass my eventEmitter variable to the children views:

```<code>const routes = {
  ChildView1: {
    screen: ChildComponent1
  },
  ChildView2: {
    screen: ChildComponent2
  },
  ...
};

const AppNavigator = StackNavigator(
  {
    ...routes,
  },
  {
    initialRouteName: 'ChildView1',
    headerMode: 'none',
  /*
   * Use modal on iOS because the card mode comes from the right,
   * which conflicts with the drawer example gesture
   */
    mode: Platform.OS === 'ios' ? 'modal' : 'card',
  }
);

/* Here is the magic for the children views */

render(){
  return (
    <AppNavigator screenProps={this.eventEmitter} />
  );
}
</code>```

Ok, now we have available our event listener for the children views, let's make a call in one of our children components:

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

  ComponentWillMount(){

    this.eventEmitter = this.props.screenProps;

    this.eventEmitter.addListener('Event-Name', ()=>{

      // Do something

    });

  }

  ...

}
</code>```

This is how I have done my event listener for child component, I hope it helps someone else. If you have a better implementation please share/comment it.

Body:
I've been researching in how to emit and listen events from a Parent component to a Child component in React Native, after trying different ways I think that it could be good to share how I have got it working.

In your parent component (App.js in my case), import the EventEmitter lib:

import EventEmitter from 'EventEmitter';

Create a variable instance of the Event Emitter:

export default class App extends Component {

...

  componentWillMount() {
    this.eventEmitter = new EventEmitter();
  }

...

}

Then, when something happens emit the event:

this.eventEmitter.emit('Event-Name', {args});

As I'm using a StackNavigator as a router I have to pass my eventEmitter variable to the children views:

const routes = {
  ChildView1: {
    screen: ChildComponent1
  },
  ChildView2: {
    screen: ChildComponent2
  },
  ...
};

const AppNavigator = StackNavigator(
  {
    ...routes,
  },
  {
    initialRouteName: 'ChildView1',
    headerMode: 'none',
  /*
   * Use modal on iOS because the card mode comes from the right,
   * which conflicts with the drawer example gesture
   */
    mode: Platform.OS === 'ios' ? 'modal' : 'card',
  }
);

/* Here is the magic for the children views */

render(){
  return (
    <AppNavigator screenProps={this.eventEmitter} />
  );
}

Ok, now we have available our event listener for the children views, let's make a call in one of our children components:

export default class ChildComponent1 extends Component {

  ComponentWillMount(){

    this.eventEmitter = this.props.screenProps;

    this.eventEmitter.addListener('Event-Name', ()=>{

      // Do something

    });

  }

  ...

}

This is how I have done my event listener for child component, I hope it helps someone else. If you have a better implementation please share/comment it.


问:
JSDoc3 does not generate hyperlinks to namespaces in NodeJS
I bet this is a stupid question but I somehow can't find the reason for this in any document I have found since this morning.

I am experienced in using JavaDoc but somehow even though the syntax of @link is the same, JSDoc3 simply does not generate hrefs to the related elements. I have tried out every possible way for the namespaces to link (also obviously wrong ones), but non of them changes the result a bit. I expected to receive a link by writing {@link #myFunction} or at least {@link MyClass#myFunction}, but neither of this created a hyperlink. Here is the code I have tested this with:

```<code>/**
 * See {@link myOtherFunction} and [MyClass's foo property]{@link MyClass#foo}.
 * Or look at {@link https://github.com GitHub}
 */
function myFunction(){};

/**
 * See {@link #myFunction} or maybe {@link #myFunction()}
 */
function myOtherFunction() {};
</code>```

I am generating it with ./node_modules/.bin/jsdoc ./* --configure ./conf.json and my default config file is:

```<code>{
    "tags": {
        "allowUnknownTags": true
    },
    "source": {
        "includePattern": ".+\\.js(doc|x)?$",
        "excludePattern": "(^|\\/|\\\\)_"
    },
    "plugins": [],
    "templates": {
        "cleverLinks": true,
        "monospaceLinks": false,
        "default": {
            "outputSourceFiles": true
        }
    }
}
</code>```

(it makes no difference if I write "cleverLinks": false,)

This is how my output looks like:

So as one can see the URL is generated properly but the namespaces are not.

I am just badly confused since I can nowhere find a description that something must be done in order to generate hrefs to my namespaces. Additionally jsdoc says:

The  {@link} inline tag creates a link to the namepath or URL that you specify. When you use the {@link} tag, you can also provide link text, using one of several different formats. If you don't provide any link text, JSDoc uses the namepath or URL as the link text.

which does not sound like there needs to be done anything in order to generate links to the namepaths.

And it also defines the syntax to be:

{@link namepathOrURL}

  [link text]{@link namepathOrURL}

  {@link namepathOrURL|link text}

  {@link namepathOrURL link text (after the first space)}

My namepaths are okay as well since webstorm is able to resolve them directly.

What am I missing so badly?

Best regards,
Vegaaaa

答:
I have found out my issue was related to the usage of JSDoc with CommonJS (NodeJS). After several hours of googling and trial and error I have managed to end up with how it working differently in NodeJS. I might play around with @inner and @instance but this resolves the question why JSDoc did not want to generate links for my NodeJS Code.

It is due to the fact that CommonJS's scope works differently to client side JS, which has one reason in the definition of NodeJS modules. Thus one need to tell JSDoc how to resolve a variable by adding the @module tag for a module and referencing to members of a module by resolving its relationship like {@link module:MODULE_NAME~instanceName}.

Here is an example with the corresponding generated html. Hope this helps someone running in the same issues like me.

Best regards,

Vegaaaa

```<code>/**
 * @module lib
 */

/**
 * @constructor
 */
var SomeClass = function () {

};

/**
 * Some doc...
 */
var moduleFunction = function () {

  /**
   * @type {number}
   */
  var innerVar = 0;

  /**
   * @type {number}
   */
  this.instanceVar = 0;

  /**
   * @memberOf module:lib~moduleFunction
   */
  function staticVar() {
    console.log(0)
  }
}

/**
 * Link to this module (identified by @module lib in the beginning): {@link module:lib} <br/>
 * Link to my constructor: {@link module:lib~SomeClass} <br/>
 * Link to a module function: {@link module:lib~moduleFunction} <br/>
 * Link to an instance variable of a module function: {@link module:lib~moduleFunction#instanceVar} <br/>
 * Link to a inner variable within a module function: {@link module:lib~moduleFunction~innerVar} <br/>
 * Link to a static variable within a module function: {@link module:lib~moduleFunction.staticVar} <br/>
 */
function documentedFunction(){}
</code>```

Body:
I bet this is a stupid question but I somehow can't find the reason for this in any document I have found since this morning.

I am experienced in using JavaDoc but somehow even though the syntax of @link is the same, JSDoc3 simply does not generate hrefs to the related elements. I have tried out every possible way for the namespaces to link (also obviously wrong ones), but non of them changes the result a bit. I expected to receive a link by writing {@link #myFunction} or at least {@link MyClass#myFunction}, but neither of this created a hyperlink. Here is the code I have tested this with:

/**
 * See {@link myOtherFunction} and [MyClass's foo property]{@link MyClass#foo}.
 * Or look at {@link https://github.com GitHub}
 */
function myFunction(){};

/**
 * See {@link #myFunction} or maybe {@link #myFunction()}
 */
function myOtherFunction() {};

I am generating it with ./node_modules/.bin/jsdoc ./* --configure ./conf.json and my default config file is:

{
    "tags": {
        "allowUnknownTags": true
    },
    "source": {
        "includePattern": ".+\\.js(doc|x)?$",
        "excludePattern": "(^|\\/|\\\\)_"
    },
    "plugins": [],
    "templates": {
        "cleverLinks": true,
        "monospaceLinks": false,
        "default": {
            "outputSourceFiles": true
        }
    }
}

(it makes no difference if I write "cleverLinks": false,)

This is how my output looks like:

So as one can see the URL is generated properly but the namespaces are not.

I am just badly confused since I can nowhere find a description that something must be done in order to generate hrefs to my namespaces. Additionally jsdoc says:

The  {@link} inline tag creates a link to the namepath or URL that you specify. When you use the {@link} tag, you can also provide link text, using one of several different formats. If you don't provide any link text, JSDoc uses the namepath or URL as the link text.

which does not sound like there needs to be done anything in order to generate links to the namepaths.

And it also defines the syntax to be:

{@link namepathOrURL}

  [link text]{@link namepathOrURL}

  {@link namepathOrURL|link text}

  {@link namepathOrURL link text (after the first space)}

My namepaths are okay as well since webstorm is able to resolve them directly.

What am I missing so badly?

Best regards,
Vegaaaa

Body:
I have found out my issue was related to the usage of JSDoc with CommonJS (NodeJS). After several hours of googling and trial and error I have managed to end up with how it working differently in NodeJS. I might play around with @inner and @instance but this resolves the question why JSDoc did not want to generate links for my NodeJS Code.

It is due to the fact that CommonJS's scope works differently to client side JS, which has one reason in the definition of NodeJS modules. Thus one need to tell JSDoc how to resolve a variable by adding the @module tag for a module and referencing to members of a module by resolving its relationship like {@link module:MODULE_NAME~instanceName}.

Here is an example with the corresponding generated html. Hope this helps someone running in the same issues like me.

Best regards,

Vegaaaa

/**
 * @module lib
 */

/**
 * @constructor
 */
var SomeClass = function () {

};

/**
 * Some doc...
 */
var moduleFunction = function () {

  /**
   * @type {number}
   */
  var innerVar = 0;

  /**
   * @type {number}
   */
  this.instanceVar = 0;

  /**
   * @memberOf module:lib~moduleFunction
   */
  function staticVar() {
    console.log(0)
  }
}

/**
 * Link to this module (identified by @module lib in the beginning): {@link module:lib} <br/>
 * Link to my constructor: {@link module:lib~SomeClass} <br/>
 * Link to a module function: {@link module:lib~moduleFunction} <br/>
 * Link to an instance variable of a module function: {@link module:lib~moduleFunction#instanceVar} <br/>
 * Link to a inner variable within a module function: {@link module:lib~moduleFunction~innerVar} <br/>
 * Link to a static variable within a module function: {@link module:lib~moduleFunction.staticVar} <br/>
 */
function documentedFunction(){}


问:
This application has no explicit mapping for /error
I used maven to do the tutorial https://spring.io/guides/gs/uploading-files/

All the codes I used was copied.

The Application can run, but I get the error:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.
  Tue Jun 30 17:24:02 CST 2015 There was an unexpected error (type=Not Found, status=404).
  No message available

How can I fix it?

答: Change @Controller to @RestController in your controller class and everything should go smoothly.


问:
How can I access the response code in Ajax requests?
As I ask in the title, how can I access the status code of the response in the done callback of an Ajax request?

```<code>var isUsernameGood = new Promise(
        function(resolve, reject) {
            console.log("Starting username check");
            $.ajax({
                       type: "POST",
                       url: '/username',
                       contentType:'application/json',
                       data: JSON.stringify({username: document.getElementById("username").value})
            })
            .done(function(data, textStatus, xhr){
                console.log("done");
                console.log(data); console.log(textStatus); console.log (xhr);
                resolve(xhr.status);
            })
            .fail(function(data, textStatus, xhr){
                console.log("fail");
                console.log(data); console.log(textStatus); console.log (xhr);
                reject(xhr.status);
            });
        }
    );
</code>```

EDIT: The log prints "fail" and then "Object { readyState: 4, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), catch: catch(), … }", then "error" and "unknown" althought in the Network tab of the inspect feature of the browser I see the request and also the response with its status code.

I'm noticing that in the Object corresponding to printing "data" in fail callback there are these fields:

i.e. it seems strangely that the status code is inside the "state" field rather than statusCode one. Do I have to access it from "state"?

答:
There are several ways to access the response from an ajax call, see for example:
Get Http Status Code from an ajax response with jquery
Hope this helps!</p>

Body:
As I ask in the title, how can I access the status code of the response in the done callback of an Ajax request?

var isUsernameGood = new Promise(
        function(resolve, reject) {
            console.log("Starting username check");
            $.ajax({
                       type: "POST",
                       url: '/username',
                       contentType:'application/json',
                       data: JSON.stringify({username: document.getElementById("username").value})
            })
            .done(function(data, textStatus, xhr){
                console.log("done");
                console.log(data); console.log(textStatus); console.log (xhr);
                resolve(xhr.status);
            })
            .fail(function(data, textStatus, xhr){
                console.log("fail");
                console.log(data); console.log(textStatus); console.log (xhr);
                reject(xhr.status);
            });
        }
    );

EDIT: The log prints "fail" and then "Object { readyState: 4, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), catch: catch(), … }", then "error" and "unknown" althought in the Network tab of the inspect feature of the browser I see the request and also the response with its status code.

I'm noticing that in the Object corresponding to printing "data" in fail callback there are these fields:

i.e. it seems strangely that the status code is inside the "state" field rather than statusCode one. Do I have to access it from "state"?


问:
Mutating variadic arguments
I want a function/define taking variadic argument pack which expands mutating each of the arguments in some pattern, like:

```<code>foo(1,2,3);
foo(1,2,3,4,5);
</code>```

should expand to

```<code>bar(modifier_1,modifier_2,modifier_3);
bar(modifier_1,modifier_2,modifier_3,modifier_4,modifier_5);
</code>```

can this be achieved? If so, how?

答:
Using boost preprocessor you could do something like this:

```<code>#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/tuple/size.hpp>
#include <boost/preprocessor/repetition/enum.hpp>

#define PREFIX_TUPLE_HELPER(z,n,data) \
   BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(0,data),\
                BOOST_PP_TUPLE_ELEM(n,BOOST_PP_TUPLE_ELEM(1,data)))

#define PREFIX_TUPLE(PREFIX_,TUPLE_) BOOST_PP_ENUM \
   ( BOOST_PP_TUPLE_SIZE(TUPLE_), \
     PREFIX_TUPLE_HELPER, \
     (PREFIX_,TUPLE_))

#define foo(...) bar(PREFIX_TUPLE(modifier_,(__VA_ARGS__)))
</code>```

Online demo here.

There's not much to explain.  PREFIX_TUPLE uses BOOST_PP_ENUM to produce the comma delimited list.  The helper macro just needs the data to do the work; to that end, we just give it a two-tuple of the prefix and the tuple of elements to paste to.

Title: Mutating variadic arguments

Body:
I want a function/define taking variadic argument pack which expands mutating each of the arguments in some pattern, like:

foo(1,2,3);
foo(1,2,3,4,5);

should expand to

bar(modifier_1,modifier_2,modifier_3);
bar(modifier_1,modifier_2,modifier_3,modifier_4,modifier_5);

can this be achieved? If so, how?

Body:
Using boost preprocessor you could do something like this:

#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/tuple/size.hpp>
#include <boost/preprocessor/repetition/enum.hpp>

#define PREFIX_TUPLE_HELPER(z,n,data) \
   BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(0,data),\
                BOOST_PP_TUPLE_ELEM(n,BOOST_PP_TUPLE_ELEM(1,data)))

#define PREFIX_TUPLE(PREFIX_,TUPLE_) BOOST_PP_ENUM \
   ( BOOST_PP_TUPLE_SIZE(TUPLE_), \
     PREFIX_TUPLE_HELPER, \
     (PREFIX_,TUPLE_))

#define foo(...) bar(PREFIX_TUPLE(modifier_,(__VA_ARGS__)))

Online demo here.

There's not much to explain.  PREFIX_TUPLE uses BOOST_PP_ENUM to produce the comma delimited list.  The helper macro just needs the data to do the work; to that end, we just give it a two-tuple of the prefix and the tuple of elements to paste to.


答:
using distinct like</p>

```<code>SELECT distinct(case) ,date_created FROM cases
</code>```

Title: PHP Display as long as field is unique

Body:
In my MySQL table, there are several rows which share the same "case number". I want to display the case numbers on a page but do not want cases which have multiple rows to be displayed more than once. This is basically the code I am using:

//select all records
$query="SELECT * FROM cases ";
$rt=mysql_query($query);
echo mysql_error();

while($nt=mysql_fetch_array($rt)){

echo $nt['case'];
echo $nt['date_created'];

}

Any ideas?

Body:
using distinct like

SELECT distinct(case) ,date_created FROM cases


问:
How to add all the values of a map without using recurrsion or var
I want to add all the values in a map without using var or any mutable structures. I have tried to do something like this but it doens't work:

```<code>val mymap = ("a" -> 1, "b" -> 2)
    val sum_of_alcohol_consumption =
    for ((k,v) <- mymap ) yield (sum_of_alcohol_consumption += v)
</code>```

I have been told that I can use .sum on a list
Please help

Thanks

答:
An equivalent answer to the more elegant use of sum is to use a fold operation. sum is implemented in a manner similar to this:

```<code>val myMap = Map("a" -> 1, "b" -> 2)
val sumAlcoholConsumption = myMap.values.foldLeft(0)(_ + _)
</code>```

values returns a sequence of only the values in the map. The first foldLeft argument is the zero value (think of it as the initial value for an accumulator value) for the operation. The second argument is a function that adds the current value of the accumulator to the current element, returning the sum of the two values - and it is applied to each value in turn. That said, sum is a lot more convenient.

Body:
I want to add all the values in a map without using var or any mutable structures. I have tried to do something like this but it doens't work:

val mymap = ("a" -> 1, "b" -> 2)
    val sum_of_alcohol_consumption =
    for ((k,v) <- mymap ) yield (sum_of_alcohol_consumption += v)

I have been told that I can use .sum on a list
Please help

Thanks

Body:
An equivalent answer to the more elegant use of sum is to use a fold operation. sum is implemented in a manner similar to this:

val myMap = Map("a" -> 1, "b" -> 2)
val sumAlcoholConsumption = myMap.values.foldLeft(0)(_ + _)

values returns a sequence of only the values in the map. The first foldLeft argument is the zero value (think of it as the initial value for an accumulator value) for the operation. The second argument is a function that adds the current value of the accumulator to the current element, returning the sum of the two values - and it is applied to each value in turn. That said, sum is a lot more convenient.


问:
How to middle align the content of the div with height 100vh?

```<code>.components{
    background-color: #1DA1F2;
    text-align: left;
     height: 100vh;
     padding: 20px;
 }
</code>```

I've used height:100vh on the outer div which surrounds the content but i cannot get the div content to align in the middle of the screen.  How can that be done ? The outer most div is .components and  the inner div is .row

答:
I made a simple example below ( Hope i understood what you wanted )

Just add display:flex;align-items:center on the .components . I used bootstrap but only for the cols to stay side by side . It doesn't matter how you arranged your layout , bootstrap or not, display:flex will work

.components {
  background-color: #1DA1F2;
  text-align: left;
  height: 100vh;
  padding: 20px;
  display:flex;
  align-items:center;
}

.row {
  width:100%;
}
.col-sm-4 {
  background:red;
  height:50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="components">
  <div class="row">
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
  </div>
</div></code>```

Body:
.components{
    background-color: #1DA1F2;
    text-align: left;
     height: 100vh;
     padding: 20px;
 }

I've used height:100vh on the outer div which surrounds the content but i cannot get the div content to align in the middle of the screen.  How can that be done ? The outer most div is .components and  the inner div is .row

Body:
I made a simple example below ( Hope i understood what you wanted )

Just add display:flex;align-items:center on the .components . I used bootstrap but only for the cols to stay side by side . It doesn't matter how you arranged your layout , bootstrap or not, display:flex will work

.components {
  background-color: #1DA1F2;
  text-align: left;
  height: 100vh;
  padding: 20px;
  display:flex;
  align-items:center;
}

.row {
  width:100%;
}
.col-sm-4 {
  background:red;
  height:50px;
}

<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="components">
  <div class="row">
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
    <div class="col-xs-4">
      col
    </div>
  </div>
</div>


问:
Responsive padding with jQuery
I have a problem with my code in jQuery, I've created a short code to measure the right padding to add on the top and on the bottom of an image that I couldn't add via position Absolute or Flex but It works only on the second click and not on the first one, here is the code:

```<code>$('.Scelta_olio').on('click', function(){
            var altezzaRecipiente = $(".Olio_non_cliccato").height();
            var altezzaOlio = $(".Olio_non_cliccato img").height();
            var paddingOlio = Math.floor((altezzaRecipiente - altezzaOlio)/2) + 'px';

            $(this).addClass('Olio_cliccato').removeClass('Olio_non_cliccato').find(".Attivazione_colonna_cliccata").delay(250).addClass("Attivata").animate({opacity: 1}, 1500);
            $('.Scelta_olio').not(this).addClass('Olio_non_cliccato').removeClass('Olio_cliccato').find(".Attivazione_colonna_cliccata").removeClass("Attivata").animate({opacity: 0}, 100);
            $('.Olio_non_cliccato .Immagine_bottiglia img').css({'padding-top': paddingOlio, 'padding-bottom': paddingOlio});
        });
</code>```

The website that I'm talking about is this one: www.poderinodelmadonnino.it, the last section with the 3 diefferent bottles. As you can see with the first click the other 2 bottles that are smaller don't have the right pading but If I click on another one to open it, It all works fine.

Can someone help me?

答:
When the page first loads, you don't have elements with the class Olio_non_cliccato so the height() returns null.

You set the classes afterward so on the second click, you get the correct height of your elements.

In order to fix this, your elements need to have the class Olio_non_cliccato when the click executes.

Here's what you can do (didn't test it and might not work because of your delays and animations)

```<code>$('.Scelta_olio').addClass('Olio_non_cliccato').removeClass('Olio_cliccato');
$(this).addClass('Olio_cliccato');
var altezzaRecipiente = $(".Olio_non_cliccato").height();
var altezzaOlio = $(".Olio_non_cliccato img").height();
</code>```

Title: Responsive padding with jQuery

Body:
I have a problem with my code in jQuery, I've created a short code to measure the right padding to add on the top and on the bottom of an image that I couldn't add via position Absolute or Flex but It works only on the second click and not on the first one, here is the code:

$('.Scelta_olio').on('click', function(){
            var altezzaRecipiente = $(".Olio_non_cliccato").height();
            var altezzaOlio = $(".Olio_non_cliccato img").height();
            var paddingOlio = Math.floor((altezzaRecipiente - altezzaOlio)/2) + 'px';

            $(this).addClass('Olio_cliccato').removeClass('Olio_non_cliccato').find(".Attivazione_colonna_cliccata").delay(250).addClass("Attivata").animate({opacity: 1}, 1500);
            $('.Scelta_olio').not(this).addClass('Olio_non_cliccato').removeClass('Olio_cliccato').find(".Attivazione_colonna_cliccata").removeClass("Attivata").animate({opacity: 0}, 100);
            $('.Olio_non_cliccato .Immagine_bottiglia img').css({'padding-top': paddingOlio, 'padding-bottom': paddingOlio});
        });

The website that I'm talking about is this one: www.poderinodelmadonnino.it, the last section with the 3 diefferent bottles. As you can see with the first click the other 2 bottles that are smaller don't have the right pading but If I click on another one to open it, It all works fine.

Can someone help me?

Body:
When the page first loads, you don't have elements with the class Olio_non_cliccato so the height() returns null.

You set the classes afterward so on the second click, you get the correct height of your elements.

In order to fix this, your elements need to have the class Olio_non_cliccato when the click executes.

Here's what you can do (didn't test it and might not work because of your delays and animations)

$('.Scelta_olio').addClass('Olio_non_cliccato').removeClass('Olio_cliccato');
$(this).addClass('Olio_cliccato');
var altezzaRecipiente = $(".Olio_non_cliccato").height();
var altezzaOlio = $(".Olio_non_cliccato img").height();


问:
How can i launch a new pane in java FX immediately to the right of the previous pane within the same window/stage?
My goal is to have a program with 3 panes. A mulitfactor Auth. The first pane will have the user type in a passphrase, while the second pain will allow the user to pick a image from a drop down list. But I want the 3rd pane to launch just to the right of the 2nd pane after the use selects a image in the same "Main" stage.

Not looking for someone to code a program just point me in the right direction to what im trying to do. My searching skills are failing, either im not explaining it right or theres another word for this.

Edit:
This is my idea of how i want it to work. Now that i look at it using a border pane probably makes since, But im still stuck with, How can I launch each section of the border at a different time, i.e when something is clicked.

答: The transition between panes could be done with a stackpane.</p>


问:
jQuery ajax validate works partially
This is my code:

```<code>    $(function() {

        var name = $( "#name" ),
            email = $( "#email" ),
            password = $( "#password" ),
            allFields = $( [] ).add( name ).add( email ).add( password ),
            tips = $( ".validateTips" );

        function updateTips( t ) {
            tips
                .text( t )
                .addClass( "ui-state-highlight" );
            setTimeout(function() {
                tips.removeClass( "ui-state-highlight", 1500 );
            }, 500 );
        }

        function checkLength( o, n, min, max ) {
            if ( o.val().length > max || o.val().length < min ) {
                o.addClass( "ui-state-error" );
                updateTips( "Length of " + n + " must be between " +
                    min + " and " + max + "." );
                return false;
            } else {
                return true;
            }
        }

        function checkRegexp( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                updateTips( n );
                return false;
            } else {
                return true;
            }
        }

function ajaxValidate(type,fval,n) {
    //alert(type+" "+fval.val()+" "+n);
    $.ajax({
       type: "GET",
       url: "ajaxValidate.php",
       data: "type="+type+"&q="+escape(fval.val()),
       success: function(msg){
         if (msg != "") {
         fval.addClass( "ui-state-error" );
         updateTips( n );
             return false;
         }
         else {
             return true;
         }
       }
     });
}

        $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 540,
            width: 420,
            modal: true,
            buttons: {
                "Create an account": function() {
                    var bValid = true;
                    allFields.removeClass( "ui-state-error" );

                    bValid = bValid && checkLength( name, "username", 3, 16 );
                    bValid = bValid && checkLength( email, "email", 6, 80 );
                    bValid = bValid && checkLength( password, "password", 5, 16 );
                    bValid = bValid && ajaxValidate("user", name,"Username is taken");
                    bValid = bValid && ajaxValidate("email", email,"Email address is taken");

                    bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                    // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                    bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. john.doe@pokermaps.org" );
                    bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                    if ( bValid ) {
                        $( "#users tbody" ).append( "<tr>" +
                            "<td>" + name.val() + "</td>" +
                            "<td>" + email.val() + "</td>" +
                            "<td>" + password.val() + "</td>" +
                        "</tr>" );

                        document.forms["regform"].submit();
                        $( this ).dialog( "close" );

                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }
        });

        $( "#create-user" )
            .button()
            .click(function() {
                $( "#dialog-form" ).dialog( "open" );
            });
    });
</code>```

My problem is with the ajaxValidate function and the two lines in the code that calls that function.

For some strange reason, it only works one time, meaning, if you keep the first call to validate the user, it will do it properly but won't validate the email, but if you place the email validate call first, it will validate it but won't validate the user.

The rest of the validation script works, so if I comment out the two call lines, everything works perfectly.

The PHP script also works.

Why is that?

UPDATE::

Ok guys, I have changed the function a bit by unifying the validation requests, so now ajaxValidate looks like this:

```<code>function ajaxValidate(fval1,fval2,n) {
    //alert(type+" "+fval.val()+" "+n);
    $.ajax({
       type: "GET",
       url: "ajaxValidate.php",
       data: "?email="+escape(fval1.val())+"&user="+escape(fval2.val()),
       success: function(msg){
         alert(fval1.val());
         alert(msg);
       }
     });
}
</code>```

The call to the function looks like this:

```<code>bValid = bValid && ajaxValidate(email, name ,"Email/User address is taken");
</code>```

And ajaxValidate.php looks like this:

```<code>require_once('classes/db/conn.php');
$user = $_GET['user'];
$email = $_GET['email'];

$query_user = mysql_fetch_array(mysql_query("SELECT USR_ID FROM users WHERE USR_Username = '$user'"));

$query_email= mysql_fetch_array(mysql_query("SELECT USR_ID FROM users WHERE USR_Email = '$email'"));

echo("SELECT USR_ID FROM users WHERE USR_Email = " . $email);
</code>```

Now, after I submit the form, I should be getting one alert with the email that was filled in, and one alert with the content of the ajax response which should be the sql query with the email from the $_GET var.

What i'm getting is, on the first alert I get the email address correctly, and on the second alert I'm getting the whole query, but without the email address. (SELECT USR_ID FROM users WHERE USR_Email =)

I'm going crazy, I can't figure this out!

答:
Your ajaxValidate function doesn't return anything explicitly, so it returns undefined implicitly, which is then casted to boolean false.

To be able to return validation status from function you should make synchronous call to server side validator. Check out jQuery docs about making ajax request, you will need to set async property to false.

Title: jQuery ajax validate works partially

Body:
This is my code:

    $(function() {

        var name = $( "#name" ),
            email = $( "#email" ),
            password = $( "#password" ),
            allFields = $( [] ).add( name ).add( email ).add( password ),
            tips = $( ".validateTips" );

        function updateTips( t ) {
            tips
                .text( t )
                .addClass( "ui-state-highlight" );
            setTimeout(function() {
                tips.removeClass( "ui-state-highlight", 1500 );
            }, 500 );
        }

        function checkLength( o, n, min, max ) {
            if ( o.val().length > max || o.val().length < min ) {
                o.addClass( "ui-state-error" );
                updateTips( "Length of " + n + " must be between " +
                    min + " and " + max + "." );
                return false;
            } else {
                return true;
            }
        }

        function checkRegexp( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                updateTips( n );
                return false;
            } else {
                return true;
            }
        }

function ajaxValidate(type,fval,n) {
    //alert(type+" "+fval.val()+" "+n);
    $.ajax({
       type: "GET",
       url: "ajaxValidate.php",
       data: "type="+type+"&q="+escape(fval.val()),
       success: function(msg){
         if (msg != "") {
         fval.addClass( "ui-state-error" );
         updateTips( n );
             return false;
         }
         else {
             return true;
         }
       }
     });
}

        $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 540,
            width: 420,
            modal: true,
            buttons: {
                "Create an account": function() {
                    var bValid = true;
                    allFields.removeClass( "ui-state-error" );

                    bValid = bValid && checkLength( name, "username", 3, 16 );
                    bValid = bValid && checkLength( email, "email", 6, 80 );
                    bValid = bValid && checkLength( password, "password", 5, 16 );
                    bValid = bValid && ajaxValidate("user", name,"Username is taken");
                    bValid = bValid && ajaxValidate("email", email,"Email address is taken");

                    bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                    // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                    bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. john.doe@pokermaps.org" );
                    bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                    if ( bValid ) {
                        $( "#users tbody" ).append( "
" +
                            "" + name.val() + "	" +
                            "" + email.val() + "	" +
                            "" + password.val() + "	" +
                        "
" );

                        document.forms["regform"].submit();
                        $( this ).dialog( "close" );

                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }
        });

        $( "#create-user" )
            .button()
            .click(function() {
                $( "#dialog-form" ).dialog( "open" );
            });
    });

My problem is with the ajaxValidate function and the two lines in the code that calls that function.

For some strange reason, it only works one time, meaning, if you keep the first call to validate the user, it will do it properly but won't validate the email, but if you place the email validate call first, it will validate it but won't validate the user.

The rest of the validation script works, so if I comment out the two call lines, everything works perfectly.

The PHP script also works.

Why is that?

UPDATE::

Ok guys, I have changed the function a bit by unifying the validation requests, so now ajaxValidate looks like this:

function ajaxValidate(fval1,fval2,n) {
    //alert(type+" "+fval.val()+" "+n);
    $.ajax({
       type: "GET",
       url: "ajaxValidate.php",
       data: "?email="+escape(fval1.val())+"&user="+escape(fval2.val()),
       success: function(msg){
         alert(fval1.val());
         alert(msg);
       }
     });
}

The call to the function looks like this:

bValid = bValid && ajaxValidate(email, name ,"Email/User address is taken");

And ajaxValidate.php looks like this:

require_once('classes/db/conn.php');
$user = $_GET['user'];
$email = $_GET['email'];

$query_user = mysql_fetch_array(mysql_query("SELECT USR_ID FROM users WHERE USR_Username = '$user'"));

$query_email= mysql_fetch_array(mysql_query("SELECT USR_ID FROM users WHERE USR_Email = '$email'"));

echo("SELECT USR_ID FROM users WHERE USR_Email = " . $email);

Now, after I submit the form, I should be getting one alert with the email that was filled in, and one alert with the content of the ajax response which should be the sql query with the email from the $_GET var.

What i'm getting is, on the first alert I get the email address correctly, and on the second alert I'm getting the whole query, but without the email address. (SELECT USR_ID FROM users WHERE USR_Email =)

I'm going crazy, I can't figure this out!