问:
How use public key with pyOpenSSL for verify a signed message?
I try to use pyOpenSSL for signed a data, I create key pair (private and publique) and certificate.

I'm a beginner with this technology, I use OpenSSl, but if you have suggestions for generate a signed message with private and public key in python, I'm take !
I want to use RSA and DSA algorithm for my tests.

I find m2Crypto, pyCrypto and other. I do not know what is the best for this.
gnupg for python and pyOpenSSl are more recent visibly.

I used function for signed a message with my private key, and I verify the data.
But when I see the function for verify the signature, in parameters I need :
private key, signature, data and digest type.

I do not know where I am wrong in this code, I find some examples, but I do not understand how this can work because the first parameters for the verify function is a X509 object "certificate is a X509 instance corresponding to the private key which generated the signature." and the second is the signature generated with the private key..

This code work perfectly with the private key :

```<code>from OpenSSL import crypto

_k = crypto.PKey()
_cert = crypto.X509()

# Create keys
_k.generate_key(crypto.TYPE_RSA, 2048)

# Add argument for create certificate
_cert.gmtime_adj_notBefore(0)
_cert.gmtime_adj_notAfter(0*365*24*60*60) #10 years expiry date
_cert.set_pubkey(_k)
_cert.sign(_k, 'sha256')

# Create key's file
with open("public_key.pem",'w') as f:
    f.write(crypto.dump_publickey(crypto.FILETYPE_PEM, _k))

with open("private_key.pem",'w') as f:
    f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, _k))

with open("certificate.pem",'w') as f:
    f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, _cert))

#-------------------------------------------------------------------------------

# Open key and load in var
with open("private_key.pem",'r') as f:
    priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())

with open("public_key.pem",'r') as f:
    pub_key = crypto.load_publickey(crypto.FILETYPE_PEM, f.read())

with open("certificate.pem",'r') as f:
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())

# sign message 'hello world' with private key and certificate
sign = crypto.sign(priv_key, "hello world", 'sha256')
print crypto.verify(cert, sign, "hello world", 'sha256')
</code>```

So, my question is, how use the public key for verify the data ?
If Bob give a public key to alice, How it checks the message with this public key ?

You have a idea ?

Thanks a lot,
Romain

答:
ok I understood my mistake : Cryptography Digital signatures

source

Body:
I try to use pyOpenSSL for signed a data, I create key pair (private and publique) and certificate.

I'm a beginner with this technology, I use OpenSSl, but if you have suggestions for generate a signed message with private and public key in python, I'm take !
I want to use RSA and DSA algorithm for my tests.

I find m2Crypto, pyCrypto and other. I do not know what is the best for this.
gnupg for python and pyOpenSSl are more recent visibly.

I used function for signed a message with my private key, and I verify the data.
But when I see the function for verify the signature, in parameters I need :
private key, signature, data and digest type.

I do not know where I am wrong in this code, I find some examples, but I do not understand how this can work because the first parameters for the verify function is a X509 object "certificate is a X509 instance corresponding to the private key which generated the signature." and the second is the signature generated with the private key..

This code work perfectly with the private key :

from OpenSSL import crypto

_k = crypto.PKey()
_cert = crypto.X509()

# Create keys
_k.generate_key(crypto.TYPE_RSA, 2048)

# Add argument for create certificate
_cert.gmtime_adj_notBefore(0)
_cert.gmtime_adj_notAfter(0*365*24*60*60) #10 years expiry date
_cert.set_pubkey(_k)
_cert.sign(_k, 'sha256')

# Create key's file
with open("public_key.pem",'w') as f:
    f.write(crypto.dump_publickey(crypto.FILETYPE_PEM, _k))

with open("private_key.pem",'w') as f:
    f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, _k))

with open("certificate.pem",'w') as f:
    f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, _cert))

#-------------------------------------------------------------------------------

# Open key and load in var
with open("private_key.pem",'r') as f:
    priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())

with open("public_key.pem",'r') as f:
    pub_key = crypto.load_publickey(crypto.FILETYPE_PEM, f.read())

with open("certificate.pem",'r') as f:
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())

# sign message 'hello world' with private key and certificate
sign = crypto.sign(priv_key, "hello world", 'sha256')
print crypto.verify(cert, sign, "hello world", 'sha256')

So, my question is, how use the public key for verify the data ?
If Bob give a public key to alice, How it checks the message with this public key ?

You have a idea ?

Thanks a lot,
Romain


来源: stackexchange

问:
Android OnClickListener - identify a button
I have the activity:

```<code>public class Mtest extends Activity {
  Button b1;
  Button b2;
  public void onCreate(Bundle savedInstanceState) {
    ...
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(myhandler);
    b2.setOnClickListener(myhandler);
    ...
  }
  View.OnClickListener myhandler = new View.OnClickListener() {
    public void onClick(View v) {
      // MY QUESTION STARTS HERE!!!
      // IF b1 do this
      // IF b2 do this
      // MY QUESTION ENDS HERE!!!
    }
  }
}
</code>```

How do I check which button has been clicked?

答:
```<code>Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId() == R.id.button1){
        Toast.makeText(context, "Button 1 Click", Toast.LENGTH_LONG).show();
    }
}
</code>```

Check this article for more details

ContentLicense: CC BY-SA 4.0

Body:
I have the activity:

public class Mtest extends Activity {
  Button b1;
  Button b2;
  public void onCreate(Bundle savedInstanceState) {
    ...
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(myhandler);
    b2.setOnClickListener(myhandler);
    ...
  }
  View.OnClickListener myhandler = new View.OnClickListener() {
    public void onClick(View v) {
      // MY QUESTION STARTS HERE!!!
      // IF b1 do this
      // IF b2 do this
      // MY QUESTION ENDS HERE!!!
    }
  }
}

How do I check which button has been clicked?

Body:
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId() == R.id.button1){
        Toast.makeText(context, "Button 1 Click", Toast.LENGTH_LONG).show();
    }
}

Check this article for more details

ContentLicense: CC BY-SA 3.0


问:
Visual Studio 2015 or 2017 does not discover unit tests
EDIT 2016-10-19:

The original question was about an issue specific to VS2015 CTP6 with the XUnit test runner. It's clear from the answers that there is a much broader issue with unit test discovery in Visual Studio which may occur in many different situations. I have cleaned up my question to reflect that.

I have also included a script in my own answer that I still use to this day to solve similar problems when they appear.

Many other answers have also proven helpful in better understanding the intricacies of the VS test runner. I appreciate that people are still sharing their solutions!

Original question 2015-04-10:

Since yesterday, my Visual Studio Test Explorer won't discover tests for any of my projects. It does not show the green loading bar after building, either.

When I go to the Visual Studio Test Explorer and click "Run All", or when I right-click any test method and select "Run Tests", I get the following in my output window:

Could not load file or assembly 'Microsoft.VisualStudio.Web.ProjectSystem, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I am running Visual Studio 2015 CTP 6 on Windows 10 Pro Technical Preview, build 10041. The .NET Framework version does not seem to matter - it happens on 4.0, 4.5.2 and 4.6.

I tried with the following testing frameworks and all of them give the same behavior:

Microsoft.VisualStudio.QualityTools.UnitTestFramework v14.0.22609.0

xunit v2.1.0-beta1-build2945 with xunit.runner.visualstudio v2.1.0-beta1-build1051

NUnit v2.6.4 with NUnitTestAdapter v2.0.0

I found an issue on GitHub (xunit) that appeared to be similar: Cannot get tests discovered #295, with this comment from the xunit team:

Be aware that Visual Studio 2015 CTP 5 has been reported to be broken
  by many people with unit testing in general (not just xUnit.net), so
  don't expect that to work.

Also, please make sure you've cleaned out Visual Studio's runner
  cache. If it gets corrupted, Visual Studio will permanently misbehave
  until it's deleted. To clear the cache, shut down all instances of
  Visual Studio, then delete the folder
  %TEMP%\VisualStudioTestExplorerExtensions (honestly, it probably
  wouldn't hurt to delete everything in %TEMP% that can be deleted).

I tried their suggestion to delete the folder %TEMP%\VisualStudioTestExplorerExtensions. Unfortunately that did not fix the problem.

I noticed that ReSharper actually is able to discover some tests. It only works for the VS and NUnit tests, not for xunit.

There has to be some sort of temp or cache folder I need to clear, but I know Visual Studio has many of them and not all of them can be deleted without unwanted side-effects.

答:
If you are working with multiple App or Web.Config files. eg:

Its likely you are using a Config that is RELEASE MODE and that will strip the Debug mode setting from the config:

```<code>  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
</code>```

Change the Config to one that doesn't remove DEBUG MODE.

Body:
If you are working with multiple App or Web.Config files. eg:

Its likely you are using a Config that is RELEASE MODE and that will strip the Debug mode setting from the config:

  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />

Change the Config to one that doesn't remove DEBUG MODE.


问:
Select a set of cells in one column based on value in another
I have a big set of data in excel of the following form

```<code>A   B
1   stuff1
6   stuff2
3   stuff3
1   stuff4
1   stuff5
7   stuff6
3   stuff7
2   stuff8
.   .
.   .
.   .
5   stuffn
</code>```

and what i would like is some vba code that will select all the cells in B that have a "1" in column A - I will be using this set to do some tasks in another part of my code

any ideas?

Thanks

答:
This should work:</p>

```<code>Sub SelectCellsInColBBasedOnColA()
    Dim TheSheet As Worksheet
    If TypeOf ActiveSheet Is Worksheet Then
        Set TheSheet = ActiveSheet
    Else
        Exit Sub
    End If

    Dim Row As Integer
    Dim CellsToSelect As String
    For Row = 1 To TheSheet.Range("A" & CStr(TheSheet.Rows.Count)).End(xlUp).Row
        If TheSheet.Range("A" & CStr(Row)).Value = 1 Then
            If CellsToSelect <> "" Then CellsToSelect = CellsToSelect & ","
            CellsToSelect = CellsToSelect & "B" & CStr(Row)
        End If
    Next Row
    TheSheet.Range(CellsToSelect).Select
End Sub
</code>```

OwnerDisplayName: mish

ContentLicense: CC BY-SA 2.5

Body:
I have a big set of data in excel of the following form

A   B
1   stuff1
6   stuff2
3   stuff3
1   stuff4
1   stuff5
7   stuff6
3   stuff7
2   stuff8
.   .
.   .
.   .
5   stuffn

and what i would like is some vba code that will select all the cells in B that have a "1" in column A - I will be using this set to do some tasks in another part of my code

any ideas?

Thanks

Body:
This should work:

Sub SelectCellsInColBBasedOnColA()
    Dim TheSheet As Worksheet
    If TypeOf ActiveSheet Is Worksheet Then
        Set TheSheet = ActiveSheet
    Else
        Exit Sub
    End If

    Dim Row As Integer
    Dim CellsToSelect As String
    For Row = 1 To TheSheet.Range("A" & CStr(TheSheet.Rows.Count)).End(xlUp).Row
        If TheSheet.Range("A" & CStr(Row)).Value = 1 Then
            If CellsToSelect <> "" Then CellsToSelect = CellsToSelect & ","
            CellsToSelect = CellsToSelect & "B" & CStr(Row)
        End If
    Next Row
    TheSheet.Range(CellsToSelect).Select
End Sub

OwnerDisplayName: Jon Fournier


问:
How to get KeyListener to use main thread and not EDT?
In my program, I have a method that is called when a key is pressed.
That method shouldn't return until some task is completed, so it blocks the thread with something like:

```<code>while (!taskIsDone);
</code>```

and runs some background process with javax.swing.Timer.

However, since KeyListener is handled by the Event Dispatch Thread, the method blocks the Event Dispatch Thread, not the main Thread, and the program cannot run if the Event Dispatch Thread is being blocked.

Is there any way around this?

答:
and runs some background process with javax.swing.Timer.

Background process should not be run with a Timer. Timer code executes on the EDT. So a long running task will prevent the GUI from repainting itself and responding to events.

Start a separate Thread to execute your background task.

The easiest way to do this is to use a SwingWorker.

Read the section from the Swing tutorial on Worker Thread and SwingWorker for more information and working examples.

If you want to block further input while the task is executing, maybe you can display a progress bar so the user knows processing is happening in the background.

Body:
In my program, I have a method that is called when a key is pressed.
That method shouldn't return until some task is completed, so it blocks the thread with something like:

while (!taskIsDone);

and runs some background process with javax.swing.Timer.

However, since KeyListener is handled by the Event Dispatch Thread, the method blocks the Event Dispatch Thread, not the main Thread, and the program cannot run if the Event Dispatch Thread is being blocked.

Is there any way around this?


问:
How to do custom list grouping based on variable?
Say I have a list that gets generated such as:

```<code>list_x = [0,1,2,3,4,5,6,7,8,9]
</code>```

Then I divide it up like this:

```<code>list_x = [01,23,45,67,89]
</code>```

with this list comprehension:

```<code>list_x = [0,1,2,3,4,5,6,7,8,9]
grp_count = 2
new_list = map(int, [list_x[i+0]+list_x[i+1] for i in range(0, len(list_x)-1, grp_count)])
</code>```

How can I make this code so I can group it into a grouping based on `grp_count'

for example if group_count = 5:

```<code>list_x = [01234,56789]
</code>```

I know I have to insert multiple list_x[i+n] for each addition of grouping size somehow.

答:
This looks a lot like the itertools grouper recipe from https://docs.python.org/3/library/itertools.html

```<code>from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)
</code>```

then

```<code>list_x = [0,1,2,3,4,5,6,7,8,9]
print(list(grouper(list_x, 5, 0)))
</code>```

gives

```<code>[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
</code>```

Body:
Say I have a list that gets generated such as:

list_x = [0,1,2,3,4,5,6,7,8,9]

Then I divide it up like this:

list_x = [01,23,45,67,89]

with this list comprehension:

list_x = [0,1,2,3,4,5,6,7,8,9]
grp_count = 2
new_list = map(int, [list_x[i+0]+list_x[i+1] for i in range(0, len(list_x)-1, grp_count)])

How can I make this code so I can group it into a grouping based on `grp_count'

for example if group_count = 5:

list_x = [01234,56789]

I know I have to insert multiple list_x[i+n] for each addition of grouping size somehow.

Body:
This looks a lot like the itertools grouper recipe from https://docs.python.org/3/library/itertools.html

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

then

list_x = [0,1,2,3,4,5,6,7,8,9]
print(list(grouper(list_x, 5, 0)))

gives

[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]


问:
Is there an equivalent of a Func<T> or better yet, an ActionBlock in javascript?
I am trying to make potentially dozens of ajax calls and want to stack them out 4 or 5 concurrently but not fire them all at once. In C# I would use an ActionBlock, and send in my delegate until I'm ready and then start executing.

so, I am attempting to build the same in JavaScript, and have been able to get everything working using $.when and arrays, but I am not able to pass in a delegate to a function with particular parameters.

I have tried fn.apply and fn.bind, but both of them execute immediately while trying to create the execution chain.

In c#, the signature would simply be :

```<code>public Push(Action|Func<T> methodToCall){...}
</code>```

Then I would invoke it recursively in the .then handler of the $.when

答:
At jQuery you can use .queue(queueName) to set an array of N synchronous functions or asynchronous procedures which can be called in sequence, that is when the previous function returns a Promise or other value; .promise(queueName) to wait for all functions in queueName array to be called; .then() chained to .promise(queueName) to perform action when queueName jQuery promise object is fulfilled.

The same pattern can also be composed without using jQuery; by using Array.prototype.shift(), Promise constructor or other Promise object, and recursion or repeated scheduling.

See

Execute function queue in javascript

javascript, $.ajax, variable name

multiple, sequential fetch() Promise

Body:
I am trying to make potentially dozens of ajax calls and want to stack them out 4 or 5 concurrently but not fire them all at once. In C# I would use an ActionBlock, and send in my delegate until I'm ready and then start executing.

so, I am attempting to build the same in JavaScript, and have been able to get everything working using $.when and arrays, but I am not able to pass in a delegate to a function with particular parameters.

I have tried fn.apply and fn.bind, but both of them execute immediately while trying to create the execution chain.

In c#, the signature would simply be :

public Push(Action|Func<T> methodToCall){...}

Then I would invoke it recursively in the .then handler of the $.when


问:
Create a function that returns a data frame from CSV files?
I am trying to make a function that outputs a dataframe from 8 different CSV files. They all have the same variables and same sort of data. The only difference in them is the year. I have tried to write out the function, but I can't seem to make it work. I am thinking a lapply woulf work, but I am not sure how to incorporate it.

These are the instructions:
Write a function named 'air' that takes a 'year' argument and returns a data.frame containing that data for that year, suppressing the automatic conversion to factors.

```<code>path <- "C:/Users/Lacy Macc/Downloads/adviz/"
files <- list.files(path=path, pattern="*.csv")
for(y in files)
 air <- function(year){
   if (!exists(""))
     }
 }
</code>```

答:
If the filenames of each file varied, you might need to use list.files and search through the filenames to identify one matching the year. But with a fixed filename scheme, all you need to do is insert the year at the appropriate point in the filename:

```<code>path <- "C:/Users/Lacy Macc/Downloads/adviz/"
year <- 2013
file_path <- paste0(path, "ad_viz_plotval_data-", year, ".csv")
</code>```

I have left out the full details of how to convert this into a function that takes in the year as I suspect this might be a homework Q.

Body:
I am trying to make a function that outputs a dataframe from 8 different CSV files. They all have the same variables and same sort of data. The only difference in them is the year. I have tried to write out the function, but I can't seem to make it work. I am thinking a lapply woulf work, but I am not sure how to incorporate it.

These are the instructions:
Write a function named 'air' that takes a 'year' argument and returns a data.frame containing that data for that year, suppressing the automatic conversion to factors.

path <- "C:/Users/Lacy Macc/Downloads/adviz/"
files <- list.files(path=path, pattern="*.csv")
for(y in files)
 air <- function(year){
   if (!exists(""))
     }
 }

Body:
If the filenames of each file varied, you might need to use list.files and search through the filenames to identify one matching the year. But with a fixed filename scheme, all you need to do is insert the year at the appropriate point in the filename:

path <- "C:/Users/Lacy Macc/Downloads/adviz/"
year <- 2013
file_path <- paste0(path, "ad_viz_plotval_data-", year, ".csv")

I have left out the full details of how to convert this into a function that takes in the year as I suspect this might be a homework Q.


问:
FBSDK empty login view
Since upgraded to the newest Xcode, I ran into some issues with FBSDK while trying to login via FBSDKLoginManager. The login window in Safari pops up but it stays white (empty view), without either navigation items or content.

Console returns the following:

[ViewService] Failed to get remote view controller with error: Error: domain=_UIViewServiceInterfaceErrorDomain, code=2

答: Try dragging a new view controller into your storyboard and assign the login page class to that storyboard view controller and run. This should work.</p>

Title: FBSDK empty login view


问:
share arraylsit among request in Spring controller
I used the same ArrayList in 2 webservices in spring controller, so I want to get it once from DB using request or session scope I tried to make a bean

```<code>@WebAppConfiguration
public class exampleBean {
List<user> users = new ArrayList<user>();

@Bean
@Scope(value = "request")
public List<user> getuserList(){
    return users ;
}

@Bean
@Scope(value = "request")
public void setAttendessList(List<user>  userList){
    users = userList;
}
</code>```

}

And in Controller

ApplicationContext ctx = new AnnotationConfigApplicationContext(exampleBean .class);
    AttendeesBean attendeeBean = ctx.getBean(exampleBean .class);

and in first service I set the list, but didn't find it in second service.

答:
Problem was with the scope, when you define request scope, value or bean will be available on a single request and won't be available for other requests. Read spring scopes for more info.

So Once you changed the scope to session then all bean/object created in one request will be available for all other requests in the same session. Hence changing scope to session solved your issue.

Body:
I used the same ArrayList in 2 webservices in spring controller, so I want to get it once from DB using request or session scope I tried to make a bean

@WebAppConfiguration
public class exampleBean {
List<user> users = new ArrayList<user>();

@Bean
@Scope(value = "request")
public List<user> getuserList(){
    return users ;
}

@Bean
@Scope(value = "request")
public void setAttendessList(List<user>  userList){
    users = userList;
}

}

And in Controller

ApplicationContext ctx = new AnnotationConfigApplicationContext(exampleBean .class);
    AttendeesBean attendeeBean = ctx.getBean(exampleBean .class);

and in first service I set the list, but didn't find it in second service.


问:
HTML to Note content
When I trying to write some HTML text to Note, I have error (I think because HTML have some prohibited tags):

```<code>Evernote.EDAM.Error.EDAMUserException
</code>```

When I use the same HTML with:

```<code>ENNote.Content = ENNoteContentAdvanced.NoteContentWithSanitizedHTML(HTML);
</code>```

it works fine.

But I need get notes by ID, for updating. And I am not understand how I can write correctly HTML to Note (in HTML I have tables), or catching ENNote by GUID.

UPD.

I writing service for synchronization Notes (EN) between Evernotes and Microsoft Exchange Appointments (MA). When user create/update EN, my service create/update MA. When user update MA (created from Evernote), my service update EN. For linking I use EN GUID (I store it in MA in extended property). So I can find EN with this code:

```<code>List<ExtendedProperty> guids = appointment.ExtendedProperties.Where(ap => ap.PropertyDefinition == guidProp).ToList();

if (guids.Count > 0)
{
    string guid = (string)guids.First().Value;

    Note sNote = store.GetNote(guid, true, false, false, false);
}
</code>```

But when I trying to set EN content I have error:
Error code "ENML_VALIDATION"
Parameter = "Document is invalid: no grammar found"

I can't store ENNoteRef in MA, because it object, not string. So I need to find ENNote by GUID (not ENNoteRef), or some stuff to set HTML to Note.Content without loosing tables.

答:
It would help if you provide more of your code that surrounds the ENNote.Content call so we have more context.

Given the code you've provided: once you've created the ENNote and its content using the NoteContentWithSanitizedHTML function, you're then adding the note to the Evernote service with something like the following, correct?

```<code>ENNoteRef myNoteRef = ENSession.SharedSession.UploadNote(ENNote, null);
</code>```

When you do this, you get back a NoteRef object, which is a reference to an actual specific note in the Evernote service. The NoteRef object has a Guid property, which is what you're looking for.

Title: HTML to Note content

Body:
When I trying to write some HTML text to Note, I have error (I think because HTML have some prohibited tags):

Evernote.EDAM.Error.EDAMUserException

When I use the same HTML with:

ENNote.Content = ENNoteContentAdvanced.NoteContentWithSanitizedHTML(HTML);

it works fine.

But I need get notes by ID, for updating. And I am not understand how I can write correctly HTML to Note (in HTML I have tables), or catching ENNote by GUID.

UPD.

I writing service for synchronization Notes (EN) between Evernotes and Microsoft Exchange Appointments (MA). When user create/update EN, my service create/update MA. When user update MA (created from Evernote), my service update EN. For linking I use EN GUID (I store it in MA in extended property). So I can find EN with this code:

List<ExtendedProperty> guids = appointment.ExtendedProperties.Where(ap => ap.PropertyDefinition == guidProp).ToList();

if (guids.Count > 0)
{
    string guid = (string)guids.First().Value;

    Note sNote = store.GetNote(guid, true, false, false, false);
}

But when I trying to set EN content I have error:
Error code "ENML_VALIDATION"
Parameter = "Document is invalid: no grammar found"

I can't store ENNoteRef in MA, because it object, not string. So I need to find ENNote by GUID (not ENNoteRef), or some stuff to set HTML to Note.Content without loosing tables.

Body:
It would help if you provide more of your code that surrounds the ENNote.Content call so we have more context.

Given the code you've provided: once you've created the ENNote and its content using the NoteContentWithSanitizedHTML function, you're then adding the note to the Evernote service with something like the following, correct?

ENNoteRef myNoteRef = ENSession.SharedSession.UploadNote(ENNote, null);

When you do this, you get back a NoteRef object, which is a reference to an actual specific note in the Evernote service. The NoteRef object has a Guid property, which is what you're looking for.


问:
Java: Remove an active key listener that's in another class
I'm making a little game that draws "Game over" at a certain event and I want the player to lose control of the character when this happens. I am using key adapter in a different class and adding it in the constructor, like this:

```<code>addKeyListener(new GetKeyStroke(this));
</code>```

My game over code looks like this (it's in the paint method):

```<code>if (gameOver) {
        g.setFont(pauseFont);
        g.setColor(Color.WHITE);
        g.drawString("Game Over!", screenSize.width / 2 - 110, screenSize.height / 5);
    }
</code>```

I've tried using

```<code>removeKeyListener(new GetKeyStroke(this));
</code>```

but from what I know, that creates a new object and that's why it doesn't work.

Any help is greatly appreciated

答:
u could create a object as your keylistener

```<code>Object a = new GetKeyStroke();
</code>```

then you can add and remove it.

```<code>button.addKeyListener((KeyListener) a);
button.removeKeyListener((KeyListener) a);
</code>```

Note i am not a expert, i know using Object isnt good, but i just could not figure out what i was supposed to use

Body:
I'm making a little game that draws "Game over" at a certain event and I want the player to lose control of the character when this happens. I am using key adapter in a different class and adding it in the constructor, like this:

addKeyListener(new GetKeyStroke(this));

My game over code looks like this (it's in the paint method):

if (gameOver) {
        g.setFont(pauseFont);
        g.setColor(Color.WHITE);
        g.drawString("Game Over!", screenSize.width / 2 - 110, screenSize.height / 5);
    }

I've tried using

removeKeyListener(new GetKeyStroke(this));

but from what I know, that creates a new object and that's why it doesn't work.

Any help is greatly appreciated

Body:
u could create a object as your keylistener

Object a = new GetKeyStroke();

then you can add and remove it.

button.addKeyListener((KeyListener) a);
button.removeKeyListener((KeyListener) a);

Note i am not a expert, i know using Object isnt good, but i just could not figure out what i was supposed to use


问:
R: Conditionally replacing values based on column pre-fixes and suffixes
I have two data frames. Data frame A has many observations/rows, an ID for each observation, and many additional columns. For a subset of observations X, the values for a set of columns are missing/NA. Data frame B contains a subset of the observations in X (which can be matched across data frames using the ID) and variables with identical names as in data frame A, but containing values to replace the missing values in the set of columns with missing/NA.

My code below (using a join operation) merely adds columns rather than replacing missing values. For each of the additional variables (let's name them W) in B, the resulting table produces W.x and W.y.

```<code>library(dplyr)

foo <- data.frame(id = seq(1:6), x = c(NA, NA, NA, 1, 3, 8), z = seq_along(10:15))
bar <- data.frame(id = seq(1:2), x = c(10, 9))
dplyr::left_join(x = foo, y = bar, by = "id")
</code>```

I am trying to replace the missing values in A using the values in B based on the ID, but do so in an efficient manner since I have many columns and many rows. My goal is this:

```<code>  id   x z
1  1  10 1
2  2   9 2
3  3  NA 3
4  4   1 4
5  5   3 5
6  6   8 6
</code>```

One thought was to use ifelse() after joining, but typing out ifelse() functions for all of the variables is not feasible. Is there a way to do this simply without the database join or is there a way to apply a function across all columns ending in .x to replace the values in .x with the value in .y if the value in .x is missing?

答:
You can iterate dplyr::coalesce over the intersect of non-grouping columns. It's not elegant, but it should scale reasonably well:

library(tidyverse)

foo <- data.frame(id = seq(1:6),
                  x = c(NA, NA, NA, 1, 3, 8),
                  y = 1:6,    # add extra shared variable
                  z = seq_along(10:15))
bar <- data.frame(id = seq(1:2),
                  y = c(1L, NA),
                  x = c(10, 9))

# names of non-grouping variables in both
vars <- intersect(names(foo), names(bar))[-1]

foobar <- left_join(foo, bar, by = 'id')

foobar <- vars %>%
    map(paste0, c('.x', '.y')) %>%    # make list of columns to coalesce
    map(~foobar[.x]) %>%    # for each set, subset foobar to a two-column data.frame
    invoke_map(.f = coalesce) %>%    # ...and coalesce it into a vector
    set_names(vars) %>%   # add names to list elements
    bind_cols(foobar) %>%   # bind into data.frame and cbind to foobar
    select(union(names(foo), names(bar)))    # drop duplicated columns

foobar
#> # A tibble: 6 x 4
#>      id     x     y     z
#>   <int> <dbl> <int> <int>
#> 1     1    10     1     1
#> 2     2     9     2     2
#> 3     3    NA     3     3
#> 4     4     1     4     4
#> 5     5     3     5     5
#> 6     6     8     6     6
```

Body:
I have two data frames. Data frame A has many observations/rows, an ID for each observation, and many additional columns. For a subset of observations X, the values for a set of columns are missing/NA. Data frame B contains a subset of the observations in X (which can be matched across data frames using the ID) and variables with identical names as in data frame A, but containing values to replace the missing values in the set of columns with missing/NA.

My code below (using a join operation) merely adds columns rather than replacing missing values. For each of the additional variables (let's name them W) in B, the resulting table produces W.x and W.y.

library(dplyr)

foo <- data.frame(id = seq(1:6), x = c(NA, NA, NA, 1, 3, 8), z = seq_along(10:15))
bar <- data.frame(id = seq(1:2), x = c(10, 9))
dplyr::left_join(x = foo, y = bar, by = "id")

I am trying to replace the missing values in A using the values in B based on the ID, but do so in an efficient manner since I have many columns and many rows. My goal is this:

  id   x z
1  1  10 1
2  2   9 2
3  3  NA 3
4  4   1 4
5  5   3 5
6  6   8 6

One thought was to use ifelse() after joining, but typing out ifelse() functions for all of the variables is not feasible. Is there a way to do this simply without the database join or is there a way to apply a function across all columns ending in .x to replace the values in .x with the value in .y if the value in .x is missing?


问:
method doPost, assignment of if in eclipse and servlets
That this wrong in the code? I want to make an answer HttpServlet with an if but "I appear "the left-hand an assignment must be a variable" in the last else, I cannot correctly declare the method, How can I fix it?

```<code>package controladores;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AjaxController
 */
@WebServlet("/AjaxController")
public class AjaxController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain ");

        PrintWriter out =  response.getWriter();
        String action = request.getParameter("action");

        if(action.equals("demo1")){
            String nombreCompleto = request.getParameter("nombreCompleto");
            out.println("Hola " + nombreCompleto);
        }
        else if (action.equals("demo2")){
            int a = Integer.parseInt(request.getParameter("numero1"));
            int b = Integer.parseInt(request.getParameter("numero2"));
            out.println(a + b);
        } else(action.equals("demo3")){
            int d = Integer.parseInt(request.getParameter("numa"));
            int c = Integer.parseInt(request.getParameter("numb"));
            out.println(c * d);
        }

    }
}
</code>```

and index.jsp

```<code><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
    <head>
        <title>Demo Ajax</title>

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet"/>
<link href="" rel="stylesheet"/>
<link type="text/css" rel="stylesheet" href="resources/css/miPrimerCSS.css" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

  $(document).ready(function(){
     $('#unHola').click(function(){
         var nombreCompleto = $('#nombreCompleto').val();
         $.ajax({
             type:'POST',
             data: {
                 nombreCompleto : nombreCompleto,
                 action: 'demo1'
             },
             url: 'AjaxController',
             success: function(result){
                 $('#resultadoNombre').html(result);
             }

         });
     });

     $('#unaSuma').click(function(){
         var numero1 = $('#numero1').val();
         var numero2 = $('#numero2').val();
         $.ajax({
             type:'POST',
             data: {
                 numero1 : numero1,
                 numero2 : numero2,
                 action: 'demo2'
             },
             url:'AjaxController',
             success : function(result){
                 $('#resultadoSuma').html(result);
             }

         });
     });

     $('#unProducto').click(function(){
         var numero1 = $('#numa').val();
         var numero2 = $('#numb').val();
         $.ajax({
             type:'POST',
             data: {
                 numa : numa,
                 numb : numb,
                 action: 'demo3'
             },
             url:'AjaxController',
             success : function(result){
                 $('#resultadoProd').html(result);
             }

         });
     });
 });

</script>
</head>

 <body>

<nav>

  <div class="nav-wrapper">

    <a href="#!" class="brand-logo">  Logo</a>
    <ul class="right hide-on-med-and-down">
      <li><a href="sass.html">Home</a></li>
      <li><a href="badges.html">Pages</a></li>
      <li><a href="badges.html">About us</a></li>
      <li><a href="badges.html">Lab</a></li>
      <!-- Dropdown Trigger -->
      <!-- <li><a class="dropdown-button" href="#!" data-activates="dropdown1">Dropdown<i class="material-icons right">arrow_drop_down</i></a></li> -->
    </ul>
  </div>
</nav>

     <div class="container">
      <p class="z-depth-5">
     <fieldset>
        <h3>Un Hola</h3>
           <form>
              Introduce tu nombre <input type="text" id="nombreCompleto"><br>
              <input type="button" value="Hola" id="unHola"><br>
              <span id="resultadoNombre"></span>
           </form>
     </fieldset>
     </div>

     <br><br>

    <div class="container">
    <fieldset>
        <h3>Una Suma</h3>
        <form>
            Numero 1 <input type="text" id="numero1"><br>
            Numero 2 <input type="text" id="numero2"><br>
            Resultado <span
                id=resultadoSuma></span><br> <input type="button" value="Suma"
                id="unaSuma">
        </form>
        </fieldset>
    </div>

    <div class="container">
    <fieldset>
        <h3>Un Producto</h3>
        <form>
            Numero 1 <input type="text" id="numero1"><br>
            Numero 2 <input type="text" id="numero2"><br>
            Resultado <span id=resultadoProd></span><br> <input type="button" value="Producto"
                id="unProducto">
        </form>
        </fieldset>
    </div>

        <footer class="page-footer">
          <div class="container">
            <h5 class="white-text">Footer Content</h5>

              </div>

          <div class="footer-copyright">
            <div class="container">
            © 2014 Copyright Text
            <a class="grey-text text-lighten-4 right" href="#!">More Links</a>
            </div>
          </div>
        </footer>
  </body>

</html>
</code>```

答:
```<code>    } else(action.equals("demo3")){
</code>```

I assume you meant:

```<code>    } else if(action.equals("demo3")){
</code>```

Body:
That this wrong in the code? I want to make an answer HttpServlet with an if but "I appear "the left-hand an assignment must be a variable" in the last else, I cannot correctly declare the method, How can I fix it?

package controladores;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AjaxController
 */
@WebServlet("/AjaxController")
public class AjaxController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain ");

        PrintWriter out =  response.getWriter();
        String action = request.getParameter("action");

        if(action.equals("demo1")){
            String nombreCompleto = request.getParameter("nombreCompleto");
            out.println("Hola " + nombreCompleto);
        }
        else if (action.equals("demo2")){
            int a = Integer.parseInt(request.getParameter("numero1"));
            int b = Integer.parseInt(request.getParameter("numero2"));
            out.println(a + b);
        } else(action.equals("demo3")){
            int d = Integer.parseInt(request.getParameter("numa"));
            int c = Integer.parseInt(request.getParameter("numb"));
            out.println(c * d);
        }

    }
}

and index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

        <title>Demo Ajax</title>

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet"/>
<link href="" rel="stylesheet"/>
<link type="text/css" rel="stylesheet" href="resources/css/miPrimerCSS.css" />

      Logo

Home

Pages

About us

Lab

     <fieldset>

Un Hola

           <form>
              Introduce tu nombre <input type="text" id="nombreCompleto">

              <input type="button" value="Hola" id="unHola">

           </form>
     </fieldset>

    <fieldset>

Una Suma

        <form>
            Numero 1 <input type="text" id="numero1">

            Numero 2 <input type="text" id="numero2">

            Resultado
 <input type="button" value="Suma"
                id="unaSuma">
        </form>
        </fieldset>

    <fieldset>

Un Producto

        <form>
            Numero 1 <input type="text" id="numero1">

            Numero 2 <input type="text" id="numero2">

            Resultado
 <input type="button" value="Producto"
                id="unProducto">
        </form>
        </fieldset>

Footer Content

            © 2014 Copyright Text
            More Links

Body:
    } else(action.equals("demo3")){

I assume you meant:

    } else if(action.equals("demo3")){


问:
Web Audio API creating a Peak Meter with AnalyserNode
What is the correct way to implement a Peak Meter like those in Logic Pro with the Web Audio API AnalyserNode?

I know AnalyserNode.getFloatFrequencyData() returns decibel values, but how do you combine those values to get the one to be displayed in the meter? Do you just take the maximum value like in the following code sample (where analyserData comes from getFloatFrequencyData():

```<code>let peak = -Infinity;
for (let i = 0; i < analyserData.length; i++) {
  const x = analyserData[i];
  if (x > peak) {
    peak = x;
  }
}
</code>```

Inspecting some output from just taking the max makes it look like this is not the correct approach. Am I wrong?

Alternatively, would it be a better idea to use a ScriptProcessorNode instead? How would that approach differ?

答:
If you take the maximum of getFloatFrequencyData()'s results in one frame, then what you are measuring is the audio power at a single frequency (whichever one has the most power). What you actually want to measure is the peak at any frequency — in other words, you want to not use the frequency data, but the unprocessed samples not separated into frequency bins.

The catch is that you'll have to compute the decibels power yourself. This is fairly simple arithmetic: you take some number of samples (one or more), square them, and average them. Note that even a “peak” meter may be doing averaging — just on a much shorter time scale.

Here's a complete example. (Warning: produces sound.)

document.getElementById('start').addEventListener('click', () => {
  const context = new(window.AudioContext || window.webkitAudioContext)();

  const oscillator = context.createOscillator();
  oscillator.type = 'square';
  oscillator.frequency.value = 440;
  oscillator.start();

  const gain1 = context.createGain();

  const analyser = context.createAnalyser();

  // Reduce output level to not hurt your ears.
  const gain2 = context.createGain();
  gain2.gain.value = 0.01;

  oscillator.connect(gain1);
  gain1.connect(analyser);
  analyser.connect(gain2);
  gain2.connect(context.destination);

  function displayNumber(id, value) {
    const meter = document.getElementById(id + '-level');
    const text = document.getElementById(id + '-level-text');
    text.textContent = value.toFixed(2);
    meter.value = isFinite(value) ? value : meter.min;
  }

  // Time domain samples are always provided with the count of
  // fftSize even though there is no FFT involved.
  // (Note that fftSize can only have particular values, not an
  // arbitrary integer.)
  analyser.fftSize = 2048;
  const sampleBuffer = new Float32Array(analyser.fftSize);

  function loop() {
    // Vary power of input to analyser. Linear in amplitude, so
    // nonlinear in dB power.
    gain1.gain.value = 0.5 * (1 + Math.sin(Date.now() / 4e2));

    analyser.getFloatTimeDomainData(sampleBuffer);

    // Compute average power over the interval.
    let sumOfSquares = 0;
    for (let i = 0; i < sampleBuffer.length; i++) {
      sumOfSquares += sampleBuffer[i] ** 2;
    }
    const avgPowerDecibels = 10 * Math.log10(sumOfSquares / sampleBuffer.length);

    // Compute peak instantaneous power over the interval.
    let peakInstantaneousPower = 0;
    for (let i = 0; i < sampleBuffer.length; i++) {
      const power = sampleBuffer[i] ** 2;
      peakInstantaneousPower = Math.max(power, peakInstantaneousPower);
    }
    const peakInstantaneousPowerDecibels = 10 * Math.log10(peakInstantaneousPower);

    // Note that you should then add or subtract as appropriate to
    // get the _reference level_ suitable for your application.

    // Display value.
    displayNumber('avg', avgPowerDecibels);
    displayNumber('inst', peakInstantaneousPowerDecibels);

    requestAnimationFrame(loop);
  }
  loop();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="start">Start</button>

<p>
  Short average
  <meter id="avg-level" min="-100" max="10" value="-100"></meter>
  <span id="avg-level-text">—</span> dB
</p>

<p>
  Instantaneous
  <meter id="inst-level" min="-100" max="10" value="-100"></meter>
  <span id="inst-level-text">—</span> dB
</p></code>```

Body:
What is the correct way to implement a Peak Meter like those in Logic Pro with the Web Audio API AnalyserNode?

I know AnalyserNode.getFloatFrequencyData() returns decibel values, but how do you combine those values to get the one to be displayed in the meter? Do you just take the maximum value like in the following code sample (where analyserData comes from getFloatFrequencyData():

let peak = -Infinity;
for (let i = 0; i < analyserData.length; i++) {
  const x = analyserData[i];
  if (x > peak) {
    peak = x;
  }
}

Inspecting some output from just taking the max makes it look like this is not the correct approach. Am I wrong?

Alternatively, would it be a better idea to use a ScriptProcessorNode instead? How would that approach differ?

Body:
If you take the maximum of getFloatFrequencyData()'s results in one frame, then what you are measuring is the audio power at a single frequency (whichever one has the most power). What you actually want to measure is the peak at any frequency — in other words, you want to not use the frequency data, but the unprocessed samples not separated into frequency bins.

The catch is that you'll have to compute the decibels power yourself. This is fairly simple arithmetic: you take some number of samples (one or more), square them, and average them. Note that even a “peak” meter may be doing averaging — just on a much shorter time scale.

Here's a complete example. (Warning: produces sound.)

document.getElementById('start').addEventListener('click', () => {
  const context = new(window.AudioContext || window.webkitAudioContext)();

  const oscillator = context.createOscillator();
  oscillator.type = 'square';
  oscillator.frequency.value = 440;
  oscillator.start();

  const gain1 = context.createGain();

  const analyser = context.createAnalyser();

  // Reduce output level to not hurt your ears.
  const gain2 = context.createGain();
  gain2.gain.value = 0.01;

  oscillator.connect(gain1);
  gain1.connect(analyser);
  analyser.connect(gain2);
  gain2.connect(context.destination);

  function displayNumber(id, value) {
    const meter = document.getElementById(id + '-level');
    const text = document.getElementById(id + '-level-text');
    text.textContent = value.toFixed(2);
    meter.value = isFinite(value) ? value : meter.min;
  }

  // Time domain samples are always provided with the count of
  // fftSize even though there is no FFT involved.
  // (Note that fftSize can only have particular values, not an
  // arbitrary integer.)
  analyser.fftSize = 2048;
  const sampleBuffer = new Float32Array(analyser.fftSize);

  function loop() {
    // Vary power of input to analyser. Linear in amplitude, so
    // nonlinear in dB power.
    gain1.gain.value = 0.5 * (1 + Math.sin(Date.now() / 4e2));

    analyser.getFloatTimeDomainData(sampleBuffer);

    // Compute average power over the interval.
    let sumOfSquares = 0;
    for (let i = 0; i < sampleBuffer.length; i++) {
      sumOfSquares += sampleBuffer[i] ** 2;
    }
    const avgPowerDecibels = 10 * Math.log10(sumOfSquares / sampleBuffer.length);

    // Compute peak instantaneous power over the interval.
    let peakInstantaneousPower = 0;
    for (let i = 0; i < sampleBuffer.length; i++) {
      const power = sampleBuffer[i] ** 2;
      peakInstantaneousPower = Math.max(power, peakInstantaneousPower);
    }
    const peakInstantaneousPowerDecibels = 10 * Math.log10(peakInstantaneousPower);

    // Note that you should then add or subtract as appropriate to
    // get the _reference level_ suitable for your application.

    // Display value.
    displayNumber('avg', avgPowerDecibels);
    displayNumber('inst', peakInstantaneousPowerDecibels);

    requestAnimationFrame(loop);
  }
  loop();
});

<button id="start">Start</button>

<p>
  Short average
  <meter id="avg-level" min="-100" max="10" value="-100"></meter>
  <span id="avg-level-text">—</span> dB
</p>

<p>
  Instantaneous
  <meter id="inst-level" min="-100" max="10" value="-100"></meter>
  <span id="inst-level-text">—</span> dB
</p>


问:
VBA single select on a Pivot Table field filter
I am working on my VBA code for a PivotTable field.

What I want to achieve is to only select Acc Payable in field Group. The following code can help me get what I want, but I'm considering whether there is a way to delete those False lines and make the code shorter?

```<code>With ActiveSheet.PivotTables("PivotTable1").PivotFields("Group")
        .PivotItems("Acc Services").Visible = False
        .PivotItems("FRG").Visible = False
        .PivotItems("Non FinOps").Visible = False
        .PivotItems("Semi Auto").Visible = False
        .PivotItems("Acc Payable").Visible = True
    End With
        End With
</code>```

答:
You can use a For loop, to iterate through the PivotField named "Group" PivotItems, and if the PivotItem.Name = "Acc Payable" then make it visible.

Code

```<code>Dim PvtItm As PivotItem

For Each PvtItm In ActiveSheet.PivotTables("PivotTable1").PivotFields("Group").PivotItems
    If PvtItm.Name = "Acc Payable" Then
        PvtItm.Visible = True
    Else
        PvtItm.Visible = False
    End If
Next PvtItm
</code>```

Body:
I am working on my VBA code for a PivotTable field.

What I want to achieve is to only select Acc Payable in field Group. The following code can help me get what I want, but I'm considering whether there is a way to delete those False lines and make the code shorter?

With ActiveSheet.PivotTables("PivotTable1").PivotFields("Group")
        .PivotItems("Acc Services").Visible = False
        .PivotItems("FRG").Visible = False
        .PivotItems("Non FinOps").Visible = False
        .PivotItems("Semi Auto").Visible = False
        .PivotItems("Acc Payable").Visible = True
    End With
        End With

Body:
You can use a For loop, to iterate through the PivotField named "Group" PivotItems, and if the PivotItem.Name = "Acc Payable" then make it visible.

Code

Dim PvtItm As PivotItem

For Each PvtItm In ActiveSheet.PivotTables("PivotTable1").PivotFields("Group").PivotItems
    If PvtItm.Name = "Acc Payable" Then
        PvtItm.Visible = True
    Else
        PvtItm.Visible = False
    End If
Next PvtItm


问:
Sum variables using R by categories condition
I have a data frame that shows the number of publications by year. But I am interested just in Conference and Journals Publications. I would like to sum all other categories in Others type.

Examples of data frame:

```<code>year    type                n
1994    Conference          2
1994    Journal             3
1995    Conference         10
1995    Editorship          3
1996    Conference         20
1996    Editorship          2
1996    Books and Thesis    3
</code>```

And the result would be:

```<code>year type             n
1994    Conference    2
1994    Journal       3
1995    Conference   10
1995    Other         3
1996    Conference   20
1996    Other         5
</code>```

答:
With dplyr we can replace anything other than "Journal" or "Conference" to "Other" and then sum them by year and type.

```<code>library(dplyr)
df %>%
  mutate(type = sub("^((Journal|Conference))", "Other", type)) %>%
  group_by(year, type) %>%
  summarise(n = sum(n))

#  year       type     n
#  <int>      <chr> <int>
#1  1994 Conference     2
#2  1994    Journal     3
#3  1995 Conference    10
#4  1995      Other     3
#5  1996 Conference    20
#6  1996      Other     5
</code>```

Body:
I have a data frame that shows the number of publications by year. But I am interested just in Conference and Journals Publications. I would like to sum all other categories in Others type.

Examples of data frame:

year    type                n
1994    Conference          2
1994    Journal             3
1995    Conference         10
1995    Editorship          3
1996    Conference         20
1996    Editorship          2
1996    Books and Thesis    3

And the result would be:

year type             n
1994    Conference    2
1994    Journal       3
1995    Conference   10
1995    Other         3
1996    Conference   20
1996    Other         5

Body:
With dplyr we can replace anything other than "Journal" or "Conference" to "Other" and then sum them by year and type.

library(dplyr)
df %>%
  mutate(type = sub("^((Journal|Conference))", "Other", type)) %>%
  group_by(year, type) %>%
  summarise(n = sum(n))

#  year       type     n
#  <int>      <chr> <int>
#1  1994 Conference     2
#2  1994    Journal     3
#3  1995 Conference    10
#4  1995      Other     3
#5  1996 Conference    20
#6  1996      Other     5


问:
Change datepicker display format (php)
how can i change the display format of date picker?

```<code><tr>
  <td width="30%"><label>Date Registered</label</td>
  <td >'.$row["dateRegistered_vehicle"].'</td>
</tr>
</code>```

using the date attributes, the data would be displayed as 2017/08/21.
how can i change this to 21/08/2017?

ive used datepicker in the insert form and does show the value as i want. but when i want to display the date in a table(html), the date come out as 2017/02/21 instead of 21/02/2017.

答:
This how you will change the date format

```<code><?php
date("d/m/Y", strtotime($row["dateRegistered_vehicle"]));
?>
</code>```

also DatePicker format

```<code><script>
$('#date_field').datepicker({
        format: 'dd/mm/yyyy'
});
</script>
</code>```

Title: Change datepicker display format (php)

Body:
how can i change the display format of date picker?

  Date Registered</label
  '.$row["dateRegistered_vehicle"].'

using the date attributes, the data would be displayed as 2017/08/21.
how can i change this to 21/08/2017?

ive used datepicker in the insert form and does show the value as i want. but when i want to display the date in a table(html), the date come out as 2017/02/21 instead of 21/02/2017.

Body:
This how you will change the date format

<?php
date("d/m/Y", strtotime($row["dateRegistered_vehicle"]));
?>

also DatePicker format

<script>
$('#date_field').datepicker({
        format: 'dd/mm/yyyy'
});
</script>


答:
```<code>levels(df$type)[levels(df$type) %in% c("Editorship", "Books_and_Thesis")] <- "Other"
aggregate(n ~ type + year, data=df, sum)

#         type year  n
# 1 Conference 1994  2
# 2    Journal 1994  3
# 3      Other 1995  3
# 4 Conference 1995 10
# 5      Other 1996  5
# 6 Conference 1996 20
</code>```

Input data:

```<code>df <- structure(list(year = c(1994L, 1994L, 1995L, 1995L, 1996L, 1996L,
  1996L), type = structure(c(2L, 3L, 2L, 1L, 2L, 1L, 1L), .Label = c("Other",
  "Conference", "Journal"), class = "factor"), n = c(2L, 3L, 10L,
  3L, 20L, 2L, 3L)), .Names = c("year", "type", "n"), row.names = c(NA, -7L), class = "data.frame")
</code>```

Title: Sum variables using R by categories condition

Body:
levels(df$type)[levels(df$type) %in% c("Editorship", "Books_and_Thesis")] <- "Other"
aggregate(n ~ type + year, data=df, sum)

#         type year  n
# 1 Conference 1994  2
# 2    Journal 1994  3
# 3      Other 1995  3
# 4 Conference 1995 10
# 5      Other 1996  5
# 6 Conference 1996 20

Input data:

df <- structure(list(year = c(1994L, 1994L, 1995L, 1995L, 1996L, 1996L,
  1996L), type = structure(c(2L, 3L, 2L, 1L, 2L, 1L, 1L), .Label = c("Other",
  "Conference", "Journal"), class = "factor"), n = c(2L, 3L, 10L,
  3L, 20L, 2L, 3L)), .Names = c("year", "type", "n"), row.names = c(NA, -7L), class = "data.frame")


问:
PHP & MySQL Calling Data With a LEFT JOIN in a while loop
Simple question here, but I'm creating a forum and on the 'Category view' page I have a table with links to each topic in that category, I also have the date each topic was posted. My issue is, I'm trying to display the person who posted the topic's username. My code looks like this:

```<code>$sql = "SELECT * FROM topics t LEFT JOIN users AS u ON t.topic_by=u.user_id WHERE t.topic_cat = :topicCat";
$query = $DB_con->prepare($sql);
    $query->execute(array(':topicCat' => $catid));
...
echo '<table class="table">
    <thead class="thead-inverse">
            <tr>
                <th>Topic</th>
                <th>Posted by</th>
                <th>Created on</th>
            </tr>
        </thead>';
        while ($topicRow = $query->fetch(PDO::FETCH_ASSOC)) {
            echo '<tr>
                <td>
                    <h3><a href="topic.php?id=' . $topicRow['u.user_name'] . '">' . $topicRow['topic_subject'] . '</a></h3>
                </td>
                <td>
                    <a href="user.php?id=' . $topicRow['topic_by'] . '"></a>
                </td>
                <td>
                    ' . date('d-m-Y', strtotime($topicRow['topic_date'])) . '
                </td>
            </tr>';
        }

        echo '</table>';
</code>```

$catid is already defined from a $_GET variable, the problem is the '. I can't seem to link the two tables although they already have a foreign key link. See my db here:href="https://i.stack.imgur.com/IZ6FA.png" rel="nofollow noreferrer">

This is the error I'm getting right now:

Notice: Undefined index: u.user_name in C:\xampp\htdocs\WEBSITE\category.php on line 41

Does anybody know what I'm doing wrong?

答:
When PHP returns the columns from the MySQL call it does NOT include the table prefix in the call.  So $topicRow['u.user_name'] should just be $topicRow['user_name'].

If you had multiple columns after the JOIN by the name user_name then you'd want to specify which in the SELECT part, like SELECT *,u.user_name AS user_name,...

Body:
Simple question here, but I'm creating a forum and on the 'Category view' page I have a table with links to each topic in that category, I also have the date each topic was posted. My issue is, I'm trying to display the person who posted the topic's username. My code looks like this:

$sql = "SELECT * FROM topics t LEFT JOIN users AS u ON t.topic_by=u.user_id WHERE t.topic_cat = :topicCat";
$query = $DB_con->prepare($sql);
    $query->execute(array(':topicCat' => $catid));
...
echo '

                Topic
                Posted by
                Created on

';
        while ($topicRow = $query->fetch(PDO::FETCH_ASSOC)) {
            echo '

' . $topicRow['topic_subject'] . '

                    ' . date('d-m-Y', strtotime($topicRow['topic_date'])) . '

';
        }

        echo '
';

$catid is already defined from a $_GET variable, the problem is the '. I can't seem to link the two tables although they already have a foreign key link. See my db here:

This is the error I'm getting right now:

Notice: Undefined index: u.user_name in C:\xampp\htdocs\WEBSITE\category.php on line 41

Does anybody know what I'm doing wrong?


问:
Pony ORM and a micro-service architecture
We have a monolithic application built with a Flask/Pony framework. It works great right now.

However, in the near future we are going to start shifting to a micro-service architecture. In this process, we are going to most likely have a separate Db for each service. For a number of reasons that I wont go into, this is beneficial. But i get hung up, and I know many others do too, when thinking about the foreign key relationships developed between tables at the moment.

People have solved this by denormalizing their db's ending up with duplicated tables in another service's DB.

Im curious what the users of pony think of this solution and if its feasible.

And what have others using PonyORM, or any other ORM for that matter, come up with when using a micro service architecture?

Edit:

Our database right now is simplistically:

```<code>Main DB
User
|-id
|-name
|-role = Required("Role")
Role
|-id
|-name
|-set("User")
</code>```

Now this is all in one Db but the logic is within two different services. User service and role service.  The role service controls authorizations and views allowed that the user is allowed to access.

Ideally, I would like to split these into separate Db's, but still be able to keep the relationship between the two. I don't think that it can be done through a natural sql query/index (or can it?).

答:
First of all I should notice, that splitting an application into microservices is not always a good idea, as it can add more complexity. Here is a couple of links to interesting articles and its discussions on HN:
    The End of Microservices, Enough with the microservices, Modules vs Microservices.

But you've mentioned that there are reasons for this move. In this case, you cannot avoid duplication of some data in both databases. One of the possible ways to split the original database is the following:

The first microservice and the corresponding database is responsible for the user and the set of roles it has.

The second microservice answers the question "which rights gives the particular role".

The first database will have the User and the Role entities, but the Role entity will only have a minimal number of attributes - id and name.

The second database will have no User entity, only the Role entity with full information about the rights, that this role provides. The id and the name attributes of the Role objects in the second database should have the same value as the ones in the first database.

This way the relationship between the User and the Role entities will not be broken, as they belong to the same database. This will help keeping data integrity. In the same time, there will be some operations that require synchronous change in both databases - roles creating, renaming and deleting. For this purpose you can make the changes in the Role microservice first and then send the corresponding request to the User microservice. But you need to implement the logic that will make sure that both changes were made without errors, retry or rollback if the second change wasn't successful.

Body:
We have a monolithic application built with a Flask/Pony framework. It works great right now.

However, in the near future we are going to start shifting to a micro-service architecture. In this process, we are going to most likely have a separate Db for each service. For a number of reasons that I wont go into, this is beneficial. But i get hung up, and I know many others do too, when thinking about the foreign key relationships developed between tables at the moment.

People have solved this by denormalizing their db's ending up with duplicated tables in another service's DB.

Im curious what the users of pony think of this solution and if its feasible.

And what have others using PonyORM, or any other ORM for that matter, come up with when using a micro service architecture?

Edit:

Our database right now is simplistically:

Main DB
User
|-id
|-name
|-role = Required("Role")
Role
|-id
|-name
|-set("User")

Now this is all in one Db but the logic is within two different services. User service and role service.  The role service controls authorizations and views allowed that the user is allowed to access.

Ideally, I would like to split these into separate Db's, but still be able to keep the relationship between the two. I don't think that it can be done through a natural sql query/index (or can it?).


答:
You can use list comprehension to do the trick like this example:

```<code>def grouper(a, num):
    if num > int(len(a)/2):
        return []
    # If you need to return only a list of lists use:
    # return [a[k:k+num] for k in range(0, len(a), num)]
    return ["".join(map(str, a[k:k+num])) for k in range(0, len(a), num)]

a = [0,1,2,3,4,5,6,7,8,9]
print(grouper(a, 2))
print(grouper(a, 5))
</code>```

Output:

```<code>['01', '23', '45', '67', '89']
['01234', '56789']
</code>```

Title: How to do custom list grouping based on variable?

Body:
Say I have a list that gets generated such as:

list_x = [0,1,2,3,4,5,6,7,8,9]

Then I divide it up like this:

list_x = [01,23,45,67,89]

with this list comprehension:

list_x = [0,1,2,3,4,5,6,7,8,9]
grp_count = 2
new_list = map(int, [list_x[i+0]+list_x[i+1] for i in range(0, len(list_x)-1, grp_count)])

How can I make this code so I can group it into a grouping based on `grp_count'

for example if group_count = 5:

list_x = [01234,56789]

I know I have to insert multiple list_x[i+n] for each addition of grouping size somehow.

Body:
You can use list comprehension to do the trick like this example:

def grouper(a, num):
    if num > int(len(a)/2):
        return []
    # If you need to return only a list of lists use:
    # return [a[k:k+num] for k in range(0, len(a), num)]
    return ["".join(map(str, a[k:k+num])) for k in range(0, len(a), num)]

a = [0,1,2,3,4,5,6,7,8,9]
print(grouper(a, 2))
print(grouper(a, 5))

Output:

['01', '23', '45', '67', '89']
['01234', '56789']


问:
What is the purpose of ApplicationBuilder.Properties?
What is the purpose of the ApplicationBuilder.Properties collection?  Why not simply use HttpContext.Items?

About the only thing I can come up with is if you want to pass objects from one piece of middleware to another, but again, you could just as easily use HttpContext.Items for that.

I suppose there is an argument for reducing scope.. if an object is only of use for middleware, why pollute HttpContext.Items?

Back in the Owin days, we would use Owin properties, and you could get these properties in your app by using GetOwinContext(), but there doesn't seem to be any equivalent of that in the asp.net middleware.  So that doesn't seem like it holds the answer.

I did some searching through the framework and couldn't find anything using it within the framework itself.  I might have missed something though.

Any ideas?

答:
What is the purpose of ApplicationBuilder.Properties?

According to source code on Github

```<code>/// <summary>
/// Gets a key/value collection that can be used to share data between middleware.
/// </summary>
IDictionary<string, object> Properties { get; }
</code>```

to speculate about anything else would be primarily opinion-based.

Body:
What is the purpose of ApplicationBuilder.Properties?

According to source code on Github

/// <summary>
/// Gets a key/value collection that can be used to share data between middleware.
/// </summary>
IDictionary<string, object> Properties { get; }

to speculate about anything else would be primarily opinion-based.


问:
Microsoft Graph API from service
I'm trying to Authorize Office 365 a single time, allowing the user to only sign in once.

here's my code so far

```<code>IdentityClientApp = new ConfidentialClientApplication(this.clientId, "[uri]", new ClientCredential("[private key from Application Secrets section]"), new Microsoft.Identity.Client.TokenCache(), new Microsoft.Identity.Client.TokenCache());
authResult = await IdentityClientApp.AcquireTokenForClientAsync(new []{ "User.Read.All" });
</code>```

I get an exception: AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope User.Read.All is not valid.

I'm not sure how I'm supposed to get a valid token I can exit and restart without popping up the authpage every hour.

答:
From your description , you are using client credentials flow with Azure AD V2.0 with MSAL library . When using client credentials flow with Azure AD V2.0 , the value passed for the scope parameter in this request should be the resource identifier (Application ID URI) of the resource you want, affixed with the .default suffix. For the Microsoft Graph example, the value is https://graph.microsoft.com/.default.

Please click here for more details . And here is a tutorial for using client credentials flow with Azure AD V2.0 endpoint.

In addition , since you are using app identity(client credential flow ) , user doesn't need to login your app  . Please read more about authentication Scenarios for Azure AD .If you want to use user identity , you could try OAuth 2.0 authorization code flow and here is a code sample . With user identity ,to extend the duration of your session(user won't logout after one hour). You could try to renew session by adding a hidden iframe in your page  which hits the new sign in route at regular time intervals (In sign in operation you could acquire a new access token ). Please refer to article controlling a Web App’s session duration for details and code sample .

Title: Microsoft Graph API from service

Body:
I'm trying to Authorize Office 365 a single time, allowing the user to only sign in once.

here's my code so far

IdentityClientApp = new ConfidentialClientApplication(this.clientId, "[uri]", new ClientCredential("[private key from Application Secrets section]"), new Microsoft.Identity.Client.TokenCache(), new Microsoft.Identity.Client.TokenCache());
authResult = await IdentityClientApp.AcquireTokenForClientAsync(new []{ "User.Read.All" });

I get an exception: AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope User.Read.All is not valid.

I'm not sure how I'm supposed to get a valid token I can exit and restart without popping up the authpage every hour.


问:
Set filter by partial string in mapbox-gl
My first question here, sorry in advance for any mistake...

I'm developing a mapbox web for my own pleasure, featuring photos taked by myself in a map. Info is loaded in JSON files, with this structure:

```<code>"type": "Feature",
"geometry": {
  "type": "Point",
  "coordinates": [-8.5375900268555,42.881175994873]
},
"properties": {
  "title": "Graffiti",
  "description": "",
  "image": {
      "imageSize": [1024, 768], "imageLandscape": 1, "imageUrl": "imgs/gsa_2016_files/20160805173018_OLY_PEP3_P8052307.jpg" },
  "icon": {
    "iconSize": [96, 73],
    "iconUrl": "imgs/gsa_2016_files/thumb_20160805173018_OLY_PEP3_P8052307.jpg"
  },
  "extended_info": {
    "tags": "graffitis,nomada",
    "place": "europa,españa,galicia,santiago de compostela"
  },
  "time": "2016:08:05 17:30:18",
  "year": 2016,
  "month": 8,
  "day": 5
}
</code>```

}

I work with different JSON files for each map, which are loaded this way:

```<code>var map = new mapboxgl.Map({ blah, blah... });

var layerIds = [ '2016' ];
var layerColors = [ 'rgba(255,0,0,1)' ];

function add_sources_to_map()
{
  for (var i = 0; i < layerIds.length; i++) {
    var id = layerIds[i];
    var layerId = layerIdPrefix + id;
    var geoJsonFile = 'jsons/'+ id + '.geoJSON';

    map.addSource(layerId, { type: 'geojson', data: geoJsonFile });
  }
}
</code>```

Later on I use a function to filter elements by year:

```<code>function filterByYear(year) {
    var filterFullYear = [ '==', 'year', year];

    // Aplica os filtros nas capas
    for (var i = 0; i < layerIds.length; i++) {
        var id = layerIds[i];

        map.setFilter(id, filterFullYear);
    }
}
</code>```

But I would like to do some more filtering, by part of tags or place content. For example, anyone with a "tag" which contains "nomada", or any "place" with "europe". I have tried to do it but failed miserably, although my knowledge of mapbox-gl or even js is limited. Can this be done? Should I change my JSON structure? Can anybody point me to some help?

TIA!

答: This is not supported in Mapbox-GL-JS. The issue is being tracked here: https://github.com/mapbox/mapbox-gl-js/issues/4698</p>

Body:
My first question here, sorry in advance for any mistake...

I'm developing a mapbox web for my own pleasure, featuring photos taked by myself in a map. Info is loaded in JSON files, with this structure:

"type": "Feature",
"geometry": {
  "type": "Point",
  "coordinates": [-8.5375900268555,42.881175994873]
},
"properties": {
  "title": "Graffiti",
  "description": "",
  "image": {
      "imageSize": [1024, 768], "imageLandscape": 1, "imageUrl": "imgs/gsa_2016_files/20160805173018_OLY_PEP3_P8052307.jpg" },
  "icon": {
    "iconSize": [96, 73],
    "iconUrl": "imgs/gsa_2016_files/thumb_20160805173018_OLY_PEP3_P8052307.jpg"
  },
  "extended_info": {
    "tags": "graffitis,nomada",
    "place": "europa,españa,galicia,santiago de compostela"
  },
  "time": "2016:08:05 17:30:18",
  "year": 2016,
  "month": 8,
  "day": 5
}

}

I work with different JSON files for each map, which are loaded this way:

var map = new mapboxgl.Map({ blah, blah... });

var layerIds = [ '2016' ];
var layerColors = [ 'rgba(255,0,0,1)' ];

function add_sources_to_map()
{
  for (var i = 0; i < layerIds.length; i++) {
    var id = layerIds[i];
    var layerId = layerIdPrefix + id;
    var geoJsonFile = 'jsons/'+ id + '.geoJSON';

    map.addSource(layerId, { type: 'geojson', data: geoJsonFile });
  }
}

Later on I use a function to filter elements by year:

function filterByYear(year) {
    var filterFullYear = [ '==', 'year', year];

    // Aplica os filtros nas capas
    for (var i = 0; i < layerIds.length; i++) {
        var id = layerIds[i];

        map.setFilter(id, filterFullYear);
    }
}

But I would like to do some more filtering, by part of tags or place content. For example, anyone with a "tag" which contains "nomada", or any "place" with "europe". I have tried to do it but failed miserably, although my knowledge of mapbox-gl or even js is limited. Can this be done? Should I change my JSON structure? Can anybody point me to some help?

TIA!


问:
MongoDB error: Cannot use 'commands' readMode, degrading to 'legacy' mode
So I was developing a project using mongo and I got an error after executing the code:
db.usercollection.insert({ "username" : "testuser1", "email" : "testuser1@testdomain.com" })

The error displayed was:

```<code>Cannot use 'commands' readMode, degrading to 'legacy' mode WriteResult({
        "writeError" : {
                "code" : 13,
                "errmsg" : "not authorized on watersheds to execute command { insert: \"usercollection\", documents: [ { _id: ObjectId('568d0eda45d472b121116bef'), username: \"testuser1\", email: \"testuser1@testdomain.com\" } ], ordered: true }"
        } })
</code>```

The db.version() is 3.0.7 and I installed MongoDB shell version is 3.2.0

How should I fix this?

Regards,
Daryll

答:
```<code>db.getCollection(collectionName).count({});
db.getCollection(collectionName).find({});
</code>```

It works! maybe mongo needs other operation.

Body:
So I was developing a project using mongo and I got an error after executing the code:
db.usercollection.insert({ "username" : "testuser1", "email" : "testuser1@testdomain.com" })

The error displayed was:

Cannot use 'commands' readMode, degrading to 'legacy' mode WriteResult({
        "writeError" : {
                "code" : 13,
                "errmsg" : "not authorized on watersheds to execute command { insert: \"usercollection\", documents: [ { _id: ObjectId('568d0eda45d472b121116bef'), username: \"testuser1\", email: \"testuser1@testdomain.com\" } ], ordered: true }"
        } })

The db.version() is 3.0.7 and I installed MongoDB shell version is 3.2.0

How should I fix this?

Regards,
Daryll

Body:
db.getCollection(collectionName).count({});
db.getCollection(collectionName).find({});

It works! maybe mongo needs other operation.


问:
Adding CSS3 animation to elements created with HTML string method in pure JavaScript ( No Library)
I am struggling to create a fade in effect using vanilla JavaScript. Adding a className property works for the elements created using document.createElement method but doesn't not seem to work using var elem = "
 List Item
" method. I have ul with id list in html and I am creating a list item using html string method. I am using list.innerHTML = elem to append list item to the list and then trying to add a class "fade-in" on list item. I have used setTimeout function to delay the animation but it still doesn't work. Please refer to the code below.

var list = document.getElementById("list");

var li = "
 This is a list item
";
list.innerHTML = li;
li.className = "fade-in";
// setTimeout(function(){
//   li.className = "fade-in";
// },5);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#list {
  opacity: 0;
}

.fade-in {
  opacity: 1;
  transition: opacity 0.5s;
}

li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

```

答:
```<code><!DOCTYPE html>
<html>
<body>

<ul id="div1">
<li id="p1">This is a paragraph.</li>
<li id="p2">This is another paragraph.</li>
</ul>
<style>
#list>li { /*Set opacity on this list itmes, not the list*/
  opacity: 0;
}

#list .fade-in { /*Use a selector that is atleast as specific as the above.*/
  opacity: 1;
  transition: opacity 0.5s;
}
li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}
</style>
<script>
window.onload = function(e){
var para = document.createElement("li");
var node = document.createTextNode("This is new.");
para.appendChild(node);
para.className = "fade-in";
var element = document.getElementById("div1");
element.appendChild(para);
}
</script>

</body>
</html>
</code>```

i edit it. hope helpful

Body:
I am struggling to create a fade in effect using vanilla JavaScript. Adding a className property works for the elements created using document.createElement method but doesn't not seem to work using var elem = "
 List Item
" method. I have ul with id list in html and I am creating a list item using html string method. I am using list.innerHTML = elem to append list item to the list and then trying to add a class "fade-in" on list item. I have used setTimeout function to delay the animation but it still doesn't work. Please refer to the code below.

var list = document.getElementById("list");

var li = "
 This is a list item
";
list.innerHTML = li;
li.className = "fade-in";
// setTimeout(function(){
//   li.className = "fade-in";
// },5);

#list {
  opacity: 0;
}

.fade-in {
  opacity: 1;
  transition: opacity 0.5s;
}

li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Body:
<!DOCTYPE html>
<html>
<body>

<ul id="div1">
<li id="p1">This is a paragraph.</li>
<li id="p2">This is another paragraph.</li>
</ul>
<style>
#list>li { /*Set opacity on this list itmes, not the list*/
  opacity: 0;
}

#list .fade-in { /*Use a selector that is atleast as specific as the above.*/
  opacity: 1;
  transition: opacity 0.5s;
}
li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}
</style>
<script>
window.onload = function(e){
var para = document.createElement("li");
var node = document.createTextNode("This is new.");
para.appendChild(node);
para.className = "fade-in";
var element = document.getElementById("div1");
element.appendChild(para);
}
</script>

</body>
</html>

i edit it. hope helpful


问:
Running embedded tomcat java Spring app in linux vm (Microsoft Azure)
I have a Spring application that I am trying to run in a linux virtual machine.  I can package the .WAR file and run it locally with no problems on my machine, but I am unable to come up with an understanding on how I would go about running this .WAR file and accessing it externally on a vm as this is my first attempt in doing so.

Right now, I have copied the .WAR file over to the vm, and run java -jarcmd through terminal to deploy.  In doing so, my tables are created in my postgres database that is running on the vm.  However, I am not sure how I would go about configuring my endpoint to be able to access my APIs?

Any advice would be greatly appreciated, thank you!

答:
According to your description, I suggest you could configure check VM and app as the following methods.

1.You could use netstat -ant to check, please ensure your port 80(your server port) is listening on 0.0.0.0. If your service is listening on 127.0.0.1. You only could access your API inside the VM.

2.Open port 80 on Azure NSG or  Azure endpoint.

If your VM is ARM VM, you need open port 80 on Azure NSG(Inbound rules). More information about how to add rules on Azure Portal please refer to this link. If your VM is classic VM, you need open port 80 on endpoint. More information please refer to this link.

Note: If your APP is listening on 8080 or other ports, you need change 80 to 8080 or others.


问:
How to use NumberFormat method inside a loop in vba
I'm new in VBA and I have a range and when the value in the range is small than 0, then I'll multiply the value by 1000 and then change its format by using the NumberFormat method. But somehow it doesn't work. The error code is on this line: RngToThousand.NumberFormat = "$-#,##0,""K""". The error says "Object required", I guess there is something wrong with the datatype. Anyhelp would be appreciated, thanks.

Below is the code I have:

```<code>Dim Rng As Range
Dim RngToNum As Range
Set RngToNum = Range("H2:J21")
For Each Rng In RngToNum
    If Rng.Value < 0 Then
        RngToThousand = Rng.Value * 1000
        RngToThousand.NumberFormat = "$-#,##0,""K"""
    Else: Rng.NumberFormat = ""
    End If
Next
</code>```

答:
NumberFormat requires an object such as Range and your RngToThousand variable is not an object. I tested the following and it worked ok:</p>

```<code>    If Rng.Value < 0 Then
        Rng.Value = Rng.Value * 1000
        Rng.NumberFormat = "$-#,##0,""K"""
    ...
</code>```

Body:
I'm new in VBA and I have a range and when the value in the range is small than 0, then I'll multiply the value by 1000 and then change its format by using the NumberFormat method. But somehow it doesn't work. The error code is on this line: RngToThousand.NumberFormat = "$-#,##0,""K""". The error says "Object required", I guess there is something wrong with the datatype. Anyhelp would be appreciated, thanks.

Below is the code I have:

Dim Rng As Range
Dim RngToNum As Range
Set RngToNum = Range("H2:J21")
For Each Rng In RngToNum
    If Rng.Value < 0 Then
        RngToThousand = Rng.Value * 1000
        RngToThousand.NumberFormat = "$-#,##0,""K"""
    Else: Rng.NumberFormat = ""
    End If
Next

Body:
NumberFormat requires an object such as Range and your RngToThousand variable is not an object. I tested the following and it worked ok:

    If Rng.Value < 0 Then
        Rng.Value = Rng.Value * 1000
        Rng.NumberFormat = "$-#,##0,""K"""
    ...


问:
Gradle dependency between tasks
So this has started happening since adding the new Room android architecture library. I had issues with the AppDatabase_Impl not exsisting, which I fixed by adding kapt to the annotations as:

Android Room Persistences library and Kotlin

Room Persistence lib implementation in Kotlin

Room Persistence lib implementation in Kotlin(Gradle error)

I had other errors that I suspected were due to AS, Kotlin and Java 8, so I tried updating to AS 3.0

I am now getting the following error when trying to build:

```<code>Information:Gradle tasks [:app:generateDebugSources,     :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:compileDebugSources, :app:compileDebugAndroidTestSources, :app:compileDebugUnitTestSources, :cryptocurrency-icons:generateDebugSources, :cryptocurrency-icons:mockableAndroidJar, :cryptocurrency-icons:generateDebugAndroidTestSources, :cryptocurrency-icons:compileDebugSources, :cryptocurrency-icons:compileDebugUnitTestSources, :cryptocurrency-icons:compileDebugAndroidTestSources]
Error:Circular dependency between the following tasks:
:app:compileDebugKotlin
+--- :app:dataBindingExportBuildInfoDebug
|    \--- :app:compileDebugKotlin (*)
\--- :app:kaptDebugKotlin
     \--- :app:dataBindingExportBuildInfoDebug (*)
(*) - details omitted (listed previously)
Information:BUILD FAILED in 1s
Information:1 error
Information:0 warnings
Information:See complete output in console
</code>```

My gradle files look like:

Project gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }

    ext {
        compileSdkVersion = 25
        buildToolsVersion = "25.0.3"
        minSdkVersion = 16
        targetSdkVersion = 25
        kotlin_version = '1.1.2-4'
        gradle_version = '2.3.2'
        android_arch_room_version = '1.0.0-alpha1'
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
        maven { url 'https://maven.google.com' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Module gradle

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    defaultConfig {
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        consumerProguardFiles 'consumer-proguard-rules.pro'
        versionCode 100
        versionName "1.0.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.mikepenz:iconics-core:2.8.2@aar'
}
</code>```

App gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

kapt {
    generateStubs = true
}

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    defaultConfig {
        applicationId "com.my.application"
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
}

dependencies {
    //Jars
    compile fileTree(include: ['*.jar'], dir: 'libs')
    //Modules
    compile project(':cryptocurrency-icons')
    //Kotlin
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    //Support
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    //OSS
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
    compile 'com.github.daniel-stoneuk:material-about-library:1.9.0'
    compile 'com.mikepenz:iconics-core:2.8.2@aar'
    compile 'com.mikepenz:community-material-typeface:1.9.32.1@aar'
    compile 'com.github.paolorotolo:appintro:4.1.0'
    compile 'com.journeyapps:zxing-android-embedded:3.5.0'
    //Data binding
    kapt "com.android.databinding:compiler:$gradle_version"
    //Room
    compile "android.arch.persistence.room:runtime:$android_arch_room_version"
    kapt  "android.arch.persistence.room:compiler:$android_arch_room_version"
    //Test
    testCompile 'junit:junit:4.12'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}
repositories {
    mavenCentral()
}
</code>```

答:
Please take a look at this.
Looks like it is a bug in the Kotlin Gradle plugin 1.1.2-4</p>

Title: Gradle dependency between tasks

Body:
So this has started happening since adding the new Room android architecture library. I had issues with the AppDatabase_Impl not exsisting, which I fixed by adding kapt to the annotations as:

Android Room Persistences library and Kotlin

Room Persistence lib implementation in Kotlin

Room Persistence lib implementation in Kotlin(Gradle error)

I had other errors that I suspected were due to AS, Kotlin and Java 8, so I tried updating to AS 3.0

I am now getting the following error when trying to build:

Information:Gradle tasks [:app:generateDebugSources,     :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:compileDebugSources, :app:compileDebugAndroidTestSources, :app:compileDebugUnitTestSources, :cryptocurrency-icons:generateDebugSources, :cryptocurrency-icons:mockableAndroidJar, :cryptocurrency-icons:generateDebugAndroidTestSources, :cryptocurrency-icons:compileDebugSources, :cryptocurrency-icons:compileDebugUnitTestSources, :cryptocurrency-icons:compileDebugAndroidTestSources]
Error:Circular dependency between the following tasks:
:app:compileDebugKotlin
+--- :app:dataBindingExportBuildInfoDebug
|    \--- :app:compileDebugKotlin (*)
\--- :app:kaptDebugKotlin
     \--- :app:dataBindingExportBuildInfoDebug (*)
(*) - details omitted (listed previously)
Information:BUILD FAILED in 1s
Information:1 error
Information:0 warnings
Information:See complete output in console

My gradle files look like:

Project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }

    ext {
        compileSdkVersion = 25
        buildToolsVersion = "25.0.3"
        minSdkVersion = 16
        targetSdkVersion = 25
        kotlin_version = '1.1.2-4'
        gradle_version = '2.3.2'
        android_arch_room_version = '1.0.0-alpha1'
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
        maven { url 'https://maven.google.com' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module gradle

apply plugin: 'com.android.library'

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    defaultConfig {
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        consumerProguardFiles 'consumer-proguard-rules.pro'
        versionCode 100
        versionName "1.0.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.mikepenz:iconics-core:2.8.2@aar'
}

App gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

kapt {
    generateStubs = true
}

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    defaultConfig {
        applicationId "com.my.application"
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
}

dependencies {
    //Jars
    compile fileTree(include: ['*.jar'], dir: 'libs')
    //Modules
    compile project(':cryptocurrency-icons')
    //Kotlin
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    //Support
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    //OSS
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
    compile 'com.github.daniel-stoneuk:material-about-library:1.9.0'
    compile 'com.mikepenz:iconics-core:2.8.2@aar'
    compile 'com.mikepenz:community-material-typeface:1.9.32.1@aar'
    compile 'com.github.paolorotolo:appintro:4.1.0'
    compile 'com.journeyapps:zxing-android-embedded:3.5.0'
    //Data binding
    kapt "com.android.databinding:compiler:$gradle_version"
    //Room
    compile "android.arch.persistence.room:runtime:$android_arch_room_version"
    kapt  "android.arch.persistence.room:compiler:$android_arch_room_version"
    //Test
    testCompile 'junit:junit:4.12'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}
repositories {
    mavenCentral()
}


问:
Why does module pattern create a singleton?
When I try and make different instances of this module, it does not work.

It seems to be a singleton.  I can only have one instance at a time.

What mechanism limits the constructor function publik() to only have on instance?

http://jsfiddle.net/AVxZR/

```<code>var Module = ( function ()
{
    var publik = function ( )
    {
    };
    publik.prototype.test;
    publik.prototype.get = function()
    {
        document.getElementById( 'a'+test ).innerHTML = test;
    };
    publik.prototype.set = function( value )
    {
         test = value;
    };
    return publik;
} ) ();

var object1 = new Module();
var object2 = new Module();

object1.set('1');
object2.set('2');

object1.get();
object2.get();
</code>```

答:
You code doesn't create a singleton. It only acts like a singleton since your test variable is a global variable.

To fix this change test to this.test so the variable is attached to each instance.

Body:
When I try and make different instances of this module, it does not work.

It seems to be a singleton.  I can only have one instance at a time.

What mechanism limits the constructor function publik() to only have on instance?

http://jsfiddle.net/AVxZR/

var Module = ( function ()
{
    var publik = function ( )
    {
    };
    publik.prototype.test;
    publik.prototype.get = function()
    {
        document.getElementById( 'a'+test ).innerHTML = test;
    };
    publik.prototype.set = function( value )
    {
         test = value;
    };
    return publik;
} ) ();

var object1 = new Module();
var object2 = new Module();

object1.set('1');
object2.set('2');

object1.get();
object2.get();