问:
How can I obtain the BundleWiring of the calling Bundle in OSGi?
I have an active bundle called bundleA which implements a class called Example with a method called doSomething() from another bundle. ExampleImpl implements Example and is loaded via ServiceLoader (thanks to SPI Fly). In ExampleImpl.doSomething() from bundleA, I need to get the BundleWiring of the bundle which called doSomething() (without passing the Bundle or BundleContext since I cannot change the API). I can get bundleA's BundleWiring, but not the calling bundle's BundleWiring:

```<code>Bundle bundleA = FrameworkUtil.getBundle(ExampleClass.class);
BundleWiring bundleWiringOfBundleA = bundle.adapt(BundleWiring.class);
</code>```

How can I obtain the calling bundle's BundleWiring?

In my particular case, the calling bundle will always be a WAB which happens to be running in Liferay Portal 7.0. So if there's a solution specific to Liferay Portal, I would accept that, but a more general OSGi solution would be fine as well.

Note that I want the calling bundle's bundle wiring not the bundle wiring of every bundle that depends on the current bundle wiring. I know that I can obtain the bundle wirings that are dependent on the current bundle wiring, but that won't help me obtain the calling bundle specifically:

```<code>Bundle bundleA = FrameworkUtil.getBundle(ExampleClass.class);
List<BundleWires> bundleWires =
    bundleWiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE);
bundleWires.get(0).getRequirerWiring();
</code>```

答:
In Liferay, the calling WAB's BundleContext is stored in the ServletContext as "osgi-bundlecontext":

```<code>BundleContext bundleContext = servletContext.getAttribute("osgi-bundlecontext");
Bundle bundle = bundleContext.getBundle();
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
</code>```

So as long as you have access to the ServletContext in Liferay you can obtain the calling bundle's Bundle and BundleWiring.

Body:
I have an active bundle called bundleA which implements a class called Example with a method called doSomething() from another bundle. ExampleImpl implements Example and is loaded via ServiceLoader (thanks to SPI Fly). In ExampleImpl.doSomething() from bundleA, I need to get the BundleWiring of the bundle which called doSomething() (without passing the Bundle or BundleContext since I cannot change the API). I can get bundleA's BundleWiring, but not the calling bundle's BundleWiring:

Bundle bundleA = FrameworkUtil.getBundle(ExampleClass.class);
BundleWiring bundleWiringOfBundleA = bundle.adapt(BundleWiring.class);

How can I obtain the calling bundle's BundleWiring?

In my particular case, the calling bundle will always be a WAB which happens to be running in Liferay Portal 7.0. So if there's a solution specific to Liferay Portal, I would accept that, but a more general OSGi solution would be fine as well.

Note that I want the calling bundle's bundle wiring not the bundle wiring of every bundle that depends on the current bundle wiring. I know that I can obtain the bundle wirings that are dependent on the current bundle wiring, but that won't help me obtain the calling bundle specifically:

Bundle bundleA = FrameworkUtil.getBundle(ExampleClass.class);
List<BundleWires> bundleWires =
    bundleWiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE);
bundleWires.get(0).getRequirerWiring();

Body:
In Liferay, the calling WAB's BundleContext is stored in the ServletContext as "osgi-bundlecontext":

BundleContext bundleContext = servletContext.getAttribute("osgi-bundlecontext");
Bundle bundle = bundleContext.getBundle();
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);

So as long as you have access to the ServletContext in Liferay you can obtain the calling bundle's Bundle and BundleWiring.


来源: stackexchange

问:
How to find the index based on the gathered population
A dataset has some patterns of gathered group. Here is the dataset:

```<code>index <- c(1:30)
a <- c(0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,0)
b <- c(1,1,1,0,0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,1,1)
c <- c(1,1,1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
d <- c(0,0,0,0,0,0,1,0,1,0,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,1)
df <- data.frame(cbind(index, a, b, c, d))
</code>```

In general, the task is to identify the index (i.e., the column "index") when the data columns (i.e., a, b, c, d) show at least three consecutive value (i.e., 1) in its column and also its neighbor column show at least three consecutive value (i.e., 1).

For example, the result from the example below will output 2, 3, 4, 7, 8, 9. See highlighted consecutive value.

index   1 2 3 4 5 6 7 8 9

col-a 0 0 0 0 0 1 1 0 1

col-b 1 0 1 0 1 1 1 1 1

col-c 0 1 1 1 0 0 1 1 1

col-d 1 1 1 1 0 0 0 0 0

The result should output the index: 1, 2, 3, 6, 7, 8, 12, 13, 14, 17, 18, 19, 27.

答:
This is not the most extensible solution, but it returns the desired result

```<code># convert 1s that do not have at least runs of length 3 to 0
df[LETTERS[1:4]] <- lapply(df[-1], function(x) {
                                     tmp <- rle(x)
                                     tmp$values[tmp$lengths < 3] <- 0L
                                     inverse.rle(tmp)})

# add neighbor columns use logical subsetting to return the relevant indices
df$index[(pmax(df[[LETTERS[1]]] + df[[LETTERS[2]]],
               df[[LETTERS[2]]] + df[[LETTERS[3]]],
               df[[LETTERS[3]]] + df[[LETTERS[4]]]) > 1)]
[1]  1  2  3  6  7  8 12 13 14 17 18 19 27
</code>```

Here is a version that is extensible to n columns.

```<code># convert 1s that do not have at least runs of length 3 to 0, put into list
l <- lapply(df[-1], function(x) {
                                 tmp <- rle(x)
                                 tmp$values[tmp$lengths < 3] <- 0L
                                 inverse.rle(tmp)})
</code>```

Same as above, only store in a new object, for convenience. Now, useMap to return a list of the sums of adjacent columns. Use do.call with pmax to return the element-level maximum.

```<code>df$index[do.call(pmax, Map(function(x, y) l[[x]] + l[[y]],
                           head(seq_along(l), -1), tail(seq_along(l), -1))) > 1]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
A dataset has some patterns of gathered group. Here is the dataset:

index <- c(1:30)
a <- c(0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,0)
b <- c(1,1,1,0,0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,1,1)
c <- c(1,1,1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
d <- c(0,0,0,0,0,0,1,0,1,0,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,1)
df <- data.frame(cbind(index, a, b, c, d))

In general, the task is to identify the index (i.e., the column "index") when the data columns (i.e., a, b, c, d) show at least three consecutive value (i.e., 1) in its column and also its neighbor column show at least three consecutive value (i.e., 1).

For example, the result from the example below will output 2, 3, 4, 7, 8, 9. See highlighted consecutive value.

index   1 2 3 4 5 6 7 8 9

col-a 0 0 0 0 0 1 1 0 1

col-b 1 0 1 0 1 1 1 1 1

col-c 0 1 1 1 0 0 1 1 1

col-d 1 1 1 1 0 0 0 0 0

The result should output the index: 1, 2, 3, 6, 7, 8, 12, 13, 14, 17, 18, 19, 27.

Body:
This is not the most extensible solution, but it returns the desired result

# convert 1s that do not have at least runs of length 3 to 0
df[LETTERS[1:4]] <- lapply(df[-1], function(x) {
                                     tmp <- rle(x)
                                     tmp$values[tmp$lengths < 3] <- 0L
                                     inverse.rle(tmp)})

# add neighbor columns use logical subsetting to return the relevant indices
df$index[(pmax(df[[LETTERS[1]]] + df[[LETTERS[2]]],
               df[[LETTERS[2]]] + df[[LETTERS[3]]],
               df[[LETTERS[3]]] + df[[LETTERS[4]]]) > 1)]
[1]  1  2  3  6  7  8 12 13 14 17 18 19 27

Here is a version that is extensible to n columns.

# convert 1s that do not have at least runs of length 3 to 0, put into list
l <- lapply(df[-1], function(x) {
                                 tmp <- rle(x)
                                 tmp$values[tmp$lengths < 3] <- 0L
                                 inverse.rle(tmp)})

Same as above, only store in a new object, for convenience. Now, useMap to return a list of the sums of adjacent columns. Use do.call with pmax to return the element-level maximum.

df$index[do.call(pmax, Map(function(x, y) l[[x]] + l[[y]],
                           head(seq_along(l), -1), tail(seq_along(l), -1))) > 1]


问:
Using IEX API for real-time stock info (Yahoo Finance replacement)?
Just like the title says, I'm looking for a replacement source for stock info now that Yahoo has disabled the API many people have been using. The new source I've been looking at is found here: https://iextrading.com/developer/

My question is how to actually get the data in to Excel...I was thinking through VBA since that is what I had used to get the data from Yahoo. However, I think what I would like to do is well beyond my current abilities...I also tried using Excel's WEBSERVICE() function with the following URL to simply look at a price: https://api.iextrading.com/1.0/stock/aapl/price but that didn't work. From my understanding, IEX has made a plethora of data available to us for free, I just don't know how to access it. My reasoning for VBA is so that I am able to use an input list from a workbook for tickers, and would be able to put this data access in many workbooks. Any help is much appreciated. Additionally, any sort of direction as to where I can look to begin learning this on my own would be similarly welcome. Thanks.

Update: Code mentioned in my comment

```<code>Function StockPrice(ticker As String, item As String) As Double

Dim strURL As String, strCSV As Double, itemFound As Integer, tag As String

itemFound = 0
If item = "lastprice" Then
    tag = "price"
    itemFound = 1
ElseIf item = "pe" Then
    tag = "peRatio"
    itemFound = 1

End If

If itemFound = 1 Then

    strURL = "https://api.iextrading.com/1.0/stock/" & ticker & "/" & tag
    Set XMLHTTP = CreateObject("MSXML2.XMLHTTP")
    XMLHTTP.Open "GET", strURL, False
    XMLHTTP.send
    StockPrice = XMLHTTP.responseText
    Set XMLHTTP = Nothing

Else

    StockPrice = "Item Not Found"

End If

End Function
</code>```

答:
I think I've mostly solved the issue. Here is the code for anyone who is interested. This works as a direct replacement for those using Yahoo Finance's API.

```<code>Function StockPrice(ticker As String, item As String)

Dim strURL As String, strCSV As Double, itemFound As Integer, tag As String

itemFound = 0
If item = "lastprice" Then
    tag = "latestPrice"
    itemFound = 1

ElseIf item = "pe" Then
    tag = "peRatio"
    itemFound = 1

ElseIf item = "company" Then
    tag = "companyName"
    itemFound = 1

ElseIf item = "sector" Then
    tag = "sector"
    itemFound = 1

ElseIf item = "open" Then
    tag = "open"
    itemFound = 1

ElseIf item = "yclose" Then
    tag = "previousClose"
    itemFound = 1

ElseIf item = "change" Then
    tag = "change"
    itemFound = 1

ElseIf item = "%change" Then
    tag = "changePercent"
    itemFound = 1

ElseIf item = "marketcap" Then
    tag = "marketCap"
    itemFound = 1

ElseIf item = "52high" Then
    tag = "week52High"
    itemFound = 1

ElseIf item = "52low" Then
    tag = "week52Low"
    itemFound = 1

End If

If itemFound = 1 Then

    strURL = "https://api.iextrading.com/1.0/stock/" & ticker & "/quote/" & tag
    Set XMLHTTP = CreateObject("MSXML2.XMLHTTP")
    XMLHTTP.Open "GET", strURL, False
    XMLHTTP.send
    StockPrice = XMLHTTP.responseText
    Set XMLHTTP = Nothing

Else

    StockPrice = "Item Not Found"

End If

End Function
</code>```

IEX has much more functionality than I've built here. Just not experienced enough to build around it. Check those features here: https://iextrading.com/developer/docs/

Body:
Just like the title says, I'm looking for a replacement source for stock info now that Yahoo has disabled the API many people have been using. The new source I've been looking at is found here: https://iextrading.com/developer/

My question is how to actually get the data in to Excel...I was thinking through VBA since that is what I had used to get the data from Yahoo. However, I think what I would like to do is well beyond my current abilities...I also tried using Excel's WEBSERVICE() function with the following URL to simply look at a price: https://api.iextrading.com/1.0/stock/aapl/price but that didn't work. From my understanding, IEX has made a plethora of data available to us for free, I just don't know how to access it. My reasoning for VBA is so that I am able to use an input list from a workbook for tickers, and would be able to put this data access in many workbooks. Any help is much appreciated. Additionally, any sort of direction as to where I can look to begin learning this on my own would be similarly welcome. Thanks.

Update: Code mentioned in my comment

Function StockPrice(ticker As String, item As String) As Double

Dim strURL As String, strCSV As Double, itemFound As Integer, tag As String

itemFound = 0
If item = "lastprice" Then
    tag = "price"
    itemFound = 1
ElseIf item = "pe" Then
    tag = "peRatio"
    itemFound = 1

End If

If itemFound = 1 Then

    strURL = "https://api.iextrading.com/1.0/stock/" & ticker & "/" & tag
    Set XMLHTTP = CreateObject("MSXML2.XMLHTTP")
    XMLHTTP.Open "GET", strURL, False
    XMLHTTP.send
    StockPrice = XMLHTTP.responseText
    Set XMLHTTP = Nothing

Else

    StockPrice = "Item Not Found"

End If

End Function

Body:
I think I've mostly solved the issue. Here is the code for anyone who is interested. This works as a direct replacement for those using Yahoo Finance's API.

Function StockPrice(ticker As String, item As String)

Dim strURL As String, strCSV As Double, itemFound As Integer, tag As String

itemFound = 0
If item = "lastprice" Then
    tag = "latestPrice"
    itemFound = 1

ElseIf item = "pe" Then
    tag = "peRatio"
    itemFound = 1

ElseIf item = "company" Then
    tag = "companyName"
    itemFound = 1

ElseIf item = "sector" Then
    tag = "sector"
    itemFound = 1

ElseIf item = "open" Then
    tag = "open"
    itemFound = 1

ElseIf item = "yclose" Then
    tag = "previousClose"
    itemFound = 1

ElseIf item = "change" Then
    tag = "change"
    itemFound = 1

ElseIf item = "%change" Then
    tag = "changePercent"
    itemFound = 1

ElseIf item = "marketcap" Then
    tag = "marketCap"
    itemFound = 1

ElseIf item = "52high" Then
    tag = "week52High"
    itemFound = 1

ElseIf item = "52low" Then
    tag = "week52Low"
    itemFound = 1

End If

If itemFound = 1 Then

    strURL = "https://api.iextrading.com/1.0/stock/" & ticker & "/quote/" & tag
    Set XMLHTTP = CreateObject("MSXML2.XMLHTTP")
    XMLHTTP.Open "GET", strURL, False
    XMLHTTP.send
    StockPrice = XMLHTTP.responseText
    Set XMLHTTP = Nothing

Else

    StockPrice = "Item Not Found"

End If

End Function

IEX has much more functionality than I've built here. Just not experienced enough to build around it. Check those features here: https://iextrading.com/developer/docs/


问:
Code Contracts in .NET 4.0, no joy for non-nullable reference types fans?
I've been playing with Code Contracts on VS2008 (http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx).

They surely are nice and provide a solid alternative to if-then-throw checks inside methods.

Nonetheless I've been hoping that they could satisfy the need that I strongly feel for non-nullable reference types.

Alas, from what I could see this doesn't seem to be the case.

This is what I understood:

Something like this will still cause issues at runtime:

MyClass a = null;

a.ToString();

I still have to explicitly write checks, even if in a more concise and streamlined way.

Unless you use VS Team System you can only use code contracts to check things at runtime, no benefits at compile time.

Meaning that you still have to handle things when something goes wrong.

Not much different from handling a simple exception.

Even with VSTS static analysis isn't as a good as the one done at runtime.

This is perfectly understandable, still it's another sign that this feature is meant for runtime usage.

Please correct me if I'm wrong but from what I see there's no way Code Contracts can make my life easier, and my programs more robust, like non-nullable reference types would.

Don't get me wrong, I don't dislike code contracts.

They are a very nice enhancement to the whole framework.

It's just that if this doesn't fill the gap that C# leaves by not having non-nullable reference types, at this point I'm afraid that nothing will.

What do you think?

答:
Non-nullable reference checking at compile time was the killer feature I was waiting for in Code Contracts, and it isn't really there.

Update 2017 (8 years later), while Non-nullable reference type is still not there... nullable reference type might.

Mads Torgersen (C# Language PM at Microsoft) does mention it in this tweet:

The prototype of nullable reference types is finally here!

This is detailed in "Introducing Nullable Reference Types in C#", and in this video "new features available C# 7.1 and 7.2".

This can be achieved if instead we add only one new “safe” kind of reference type, and then reinterpret existing reference types as being the other “safe” kind. More specifically, we think that the default meaning of unannotated reference types such as string should be non-nullable reference types, for a couple of reasons:

We believe that it is more common to want a reference not to be null. Nullable reference types would be the rarer kind (though we don’t have good data to tell us by how much), so they are the ones that should require a new annotation.
  The language already has a notion of – and a syntax for – nullable value types. The analogy between the two would make the language addition conceptually easier, and linguistically simpler.

  It seems right that you shouldn’t burden yourself or your consumer with cumbersome null values unless you’ve actively decided that you want them. Nulls, not the absence of them, should be the thing that you explicitly have to opt in to.

  Here’s what it looks like:

```<code>class Person
{
    public string FirstName;   // Not null
    public string? MiddleName; // May be null
    public string LastName;    // Not null
}
</code>```

This class is now able to express the intent that everyone has a first and a last name, but only some people have a middle name.

Thus we get to the reason we call this language feature “nullable reference types”: Those are the ones that get added to the language. The nonnullable ones are already there, at least syntactically.

This is still a prototype, and might end up (or not) in the language.

See more at "The C# Nullable Reference Types Preview".

ContentLicense: CC BY-SA 2.5

Body:
Non-nullable reference checking at compile time was the killer feature I was waiting for in Code Contracts, and it isn't really there.

Update 2017 (8 years later), while Non-nullable reference type is still not there... nullable reference type might.

Mads Torgersen (C# Language PM at Microsoft) does mention it in this tweet:

The prototype of nullable reference types is finally here!

This is detailed in "Introducing Nullable Reference Types in C#", and in this video "new features available C# 7.1 and 7.2".

This can be achieved if instead we add only one new “safe” kind of reference type, and then reinterpret existing reference types as being the other “safe” kind. More specifically, we think that the default meaning of unannotated reference types such as string should be non-nullable reference types, for a couple of reasons:

We believe that it is more common to want a reference not to be null. Nullable reference types would be the rarer kind (though we don’t have good data to tell us by how much), so they are the ones that should require a new annotation.
  The language already has a notion of – and a syntax for – nullable value types. The analogy between the two would make the language addition conceptually easier, and linguistically simpler.

  It seems right that you shouldn’t burden yourself or your consumer with cumbersome null values unless you’ve actively decided that you want them. Nulls, not the absence of them, should be the thing that you explicitly have to opt in to.

  Here’s what it looks like:

class Person
{
    public string FirstName;   // Not null
    public string? MiddleName; // May be null
    public string LastName;    // Not null
}

This class is now able to express the intent that everyone has a first and a last name, but only some people have a middle name.

Thus we get to the reason we call this language feature “nullable reference types”: Those are the ones that get added to the language. The nonnullable ones are already there, at least syntactically.

This is still a prototype, and might end up (or not) in the language.

See more at "The C# Nullable Reference Types Preview".


问:
Is setting the Authorization header in HttpClient safe?
I'm working in a MVC5 ASP.NET project, and learned that to send authenticated requests to a WEB API from the controller I could do the following to add a token to the header(using an example code):

```<code>public static class APICaller
{
    // Use a single instance for HttpClient to reduce overhead
    private static readonly HttpClient client = new HttpClient();

    //Set the Authorization Header
    public static string SetHeader( string token )
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        return("Success");
    }
}
</code>```

Is setting the header this way on the HttpClient thread-safe? Will other users have a way to access this same token, given that there is only one instance of this HttpClient?

EDIT:

I'd like to ask one more question to get a better understanding of how it works. Would I need to add the header each time I'm making a request with the same HttpClient object?

答:
Will other users have a way to access this same token, given that there is only one instance of this HttpClient?

Yes, that is why you need to be careful when setting the default headers.

Would I need to add the header each time I'm making a request with the same HttpClient object?

No, because you set the default header all requests created with that object will have the header.

For things like a Bearer token it is better to not put in the default headers and instead put it in the request header by creating a new HttpRequestMessage object, setting the headers you need there, then using HttpClient.SendAsync(  passing in the request message to send the headers along with your request.

Body:
I'm working in a MVC5 ASP.NET project, and learned that to send authenticated requests to a WEB API from the controller I could do the following to add a token to the header(using an example code):

public static class APICaller
{
    // Use a single instance for HttpClient to reduce overhead
    private static readonly HttpClient client = new HttpClient();

    //Set the Authorization Header
    public static string SetHeader( string token )
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        return("Success");
    }
}

Is setting the header this way on the HttpClient thread-safe? Will other users have a way to access this same token, given that there is only one instance of this HttpClient?

EDIT:

I'd like to ask one more question to get a better understanding of how it works. Would I need to add the header each time I'm making a request with the same HttpClient object?


问:
How would I create a palindrome checker without if statements
I'm trying to create a programme like this previous one I've made;

It simply gives a boolean true/false on if a string backwards is still spelt the same way.

I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements

Any help appreciated as always; thanks.

```<code>import java.util.*;
public class testingthingsv24 {

private static Scanner in;

public static void main(String args[])
{
    in = new Scanner(System.in);
    System.out.println("Please Enter Your String: ");
    String n=in.nextLine();
    System.out.println("Your String Was: "+n);
    StringBuffer str=new StringBuffer(n);
    StringBuffer str2=new StringBuffer(str.reverse());
    String s2=new String(str2);
    System.out.println("Reversed Is: "+str2);
    if(n.equals(s2))
        System.out.println("ITS A PALINDROME");
    else
        System.out.println("ITS NOT A PALINDROME");
}
}
</code>```

Output:

```<code>Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME
</code>```

答:
Can be done with recursion too</p>

```<code>boolean isPalindrome (String s) {
    return s.length() < 2 ? true : s.charAt(0) == s.charAt(s.length() - 1) && isPalindrome(s.substring(1,s.length() - 1));
}
</code>```

Body:
I'm trying to create a programme like this previous one I've made;

It simply gives a boolean true/false on if a string backwards is still spelt the same way.

I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements

Any help appreciated as always; thanks.

import java.util.*;
public class testingthingsv24 {

private static Scanner in;

public static void main(String args[])
{
    in = new Scanner(System.in);
    System.out.println("Please Enter Your String: ");
    String n=in.nextLine();
    System.out.println("Your String Was: "+n);
    StringBuffer str=new StringBuffer(n);
    StringBuffer str2=new StringBuffer(str.reverse());
    String s2=new String(str2);
    System.out.println("Reversed Is: "+str2);
    if(n.equals(s2))
        System.out.println("ITS A PALINDROME");
    else
        System.out.println("ITS NOT A PALINDROME");
}
}

Output:

Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME

Body:
Can be done with recursion too

boolean isPalindrome (String s) {
    return s.length() < 2 ? true : s.charAt(0) == s.charAt(s.length() - 1) && isPalindrome(s.substring(1,s.length() - 1));
}


问:
Angular directive crashing browser
I have the following directive in my project:

```<code>app.directive('eventSessionsList', function() {
  return {
      restrict: 'AEC',
      scope: {
        input: '=data'
      },
      templateUrl: 'directives/event-sessions-list.html'
  };
});
</code>```

The template looks like this:

```<code><ul class="event-sessions-list">
  <li ng-repeat="session in input.eventSessions">
    <span class="date">{{ session.date }}</span>
    <p class="info">
    {{ session.length }} hr session @ {{ session.venue }}</p>
  </li>
</ul>
</code>```

When I try to load the page it crashes with no errors (tested in both Safari and Chrome).

答:
I had a very similar problem but instead of a clash with CSS classes (OP's case), I had it with HTML tags.

Just posting in case someone runs into this slightly different variation of the same root problem.

HTML

```<code><div id="header">
    <div id="header_main">
        <nav></nav>
    </div>
</div>
</code>```

Nav Template

```<code><div class="dark-blue-section main-color">
  <div class="container">
    <nav class="navbar" role="navigation">
</code>```

Nav Component

```<code>angular
.module('common')
.component('nav', {
    templateUrl: './nav.html',
});
</code>```

Like OP said, simply renaming it will solve it.

NOTE: I did first try renaming from nav to navbar which is ALSO an HTML class if you look at the Nav Template HTML, but this did not seem to confuse AngularJS.

Not sure why CSS classes cause confusion, but HTML classes don't so maybe someone else can chime in there.

Title: Angular directive crashing browser

Body:
I have the following directive in my project:

app.directive('eventSessionsList', function() {
  return {
      restrict: 'AEC',
      scope: {
        input: '=data'
      },
      templateUrl: 'directives/event-sessions-list.html'
  };
});

The template looks like this:

    {{ session.date }}

    {{ session.length }} hr session @ {{ session.venue }}

When I try to load the page it crashes with no errors (tested in both Safari and Chrome).

Body:
I had a very similar problem but instead of a clash with CSS classes (OP's case), I had it with HTML tags.

Just posting in case someone runs into this slightly different variation of the same root problem.

HTML

<div id="header">
    <div id="header_main">
        <nav></nav>
    </div>
</div>

Nav Template

<div class="dark-blue-section main-color">
  <div class="container">
    <nav class="navbar" role="navigation">

Nav Component

angular
.module('common')
.component('nav', {
    templateUrl: './nav.html',
});

Like OP said, simply renaming it will solve it.

NOTE: I did first try renaming from nav to navbar which is ALSO an HTML class if you look at the Nav Template HTML, but this did not seem to confuse AngularJS.

Not sure why CSS classes cause confusion, but HTML classes don't so maybe someone else can chime in there.


问:
Why to I need to exclude from enableAutoConfiguration when I have autowired beans byname
I have 3 DataSource beans

```<code><bean id="dataSource1" name="dataSource1" autowire="byName" .....>
<bean id="dataSource2" name="dataSource2" autowire="byName" .....>
<bean id="dataSource3" name="dataSource3" autowire="byName" .....>
</code>```

I have set autowire "byName" in the beans in xml

I am creating 3 JdbcTemplates

```<code>@Autowired
@Qualifier("dataSource1")
BasicDataSource dataSource1;

@Autowired
@Qualifier("dataSource2")
BasicDataSource dataSource2;

@Autowired
@Qualifier("dataSource3")
BasicDataSource dataSource3;

@Autowired
@Bean(name="jdbcTemplate1")
public JdbcTemplate createJdbcTemplate(){
         return new JdbcTemplate((DateSource)dataSource1)
}

@Autowired
@Bean(name="jdbcTemplate2")
public JdbcTemplate createJdbcTemplate(){
         return new JdbcTemplate((DateSource)dataSource2)
}

@Autowired
@Bean(name="jdbcTemplate3")
public JdbcTemplate createJdbcTemplate(){
         return new JdbcTemplate((DateSource)dataSource3)
}
</code>```

StackTrace :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-16 23:50:04.562 ERROR 15180 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field dataSource1 in com.MyClass required a single bean, but 3 were found:

```<code>- dataSource1: defined in class path resource [datasource.xml]

- dataSource2: defined in class path resource [datasource.xml]

- dataSource3: defined in class path resource [datasource.xml]
</code>```

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

When I add EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) everything works fine.

Can anyone explain why do I need to exclude the AutoConfiguration despite autowiring-byName.

答:
You don't need to ignore the auto-configuration, you just need to mark one of the datasources as @Primary, as auto-configurations might try to get one by type. This leads to the error you have.

Also, feel free to check the dedicated section in the reference documentation about dealing with multiple datasources; there are better ways to configure multiple datasources and still leverage Spring Boot features and infrastructure.

Body:
I have 3 DataSource beans

<bean id="dataSource1" name="dataSource1" autowire="byName" .....>
<bean id="dataSource2" name="dataSource2" autowire="byName" .....>
<bean id="dataSource3" name="dataSource3" autowire="byName" .....>

I have set autowire "byName" in the beans in xml

I am creating 3 JdbcTemplates

@Autowired
@Qualifier("dataSource1")
BasicDataSource dataSource1;

@Autowired
@Qualifier("dataSource2")
BasicDataSource dataSource2;

@Autowired
@Qualifier("dataSource3")
BasicDataSource dataSource3;

@Autowired
@Bean(name="jdbcTemplate1")
public JdbcTemplate createJdbcTemplate(){
         return new JdbcTemplate((DateSource)dataSource1)
}

@Autowired
@Bean(name="jdbcTemplate2")
public JdbcTemplate createJdbcTemplate(){
         return new JdbcTemplate((DateSource)dataSource2)
}

@Autowired
@Bean(name="jdbcTemplate3")
public JdbcTemplate createJdbcTemplate(){
         return new JdbcTemplate((DateSource)dataSource3)
}

StackTrace :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-16 23:50:04.562 ERROR 15180 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

APPLICATION FAILED TO START

Description:

Field dataSource1 in com.MyClass required a single bean, but 3 were found:

- dataSource1: defined in class path resource [datasource.xml]

- dataSource2: defined in class path resource [datasource.xml]

- dataSource3: defined in class path resource [datasource.xml]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

When I add EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) everything works fine.

Can anyone explain why do I need to exclude the AutoConfiguration despite autowiring-byName.


问:
Iphone Core Data Noob Question- Why can't I change or add entities in data model?
If I build a new project using the IOS Navigation template and add a single attribute to event entity in the data model, and then run, the application crashes.

I'm new to IOS development and have worked through the Apple Core Data app tutorial, and have read a few posts on migration issues, but I haven't seen this specific problem discussed so I must be missing something incredibly obvious.

Do I need to refresh the data model? Is it a migration issue? It has no existing entries as it's a clean application.

Thanks!

Console Output:

```<code>#0  0x97225ef6 in __kill
#1  0x97225ee8 in kill$UNIX2003
#2  0x972b862d in raise
#3  0x972ce6e4 in abort
#4  0x00002674 in -[NavBonjourAppDelegate persistentStoreCoordinator] at NavBonjourAppDelegate.m:175
#5  0x00002342 in -[NavBonjourAppDelegate managedObjectContext] at NavBonjourAppDelegate.m:111
#6  0x0000210e in -[NavBonjourAppDelegate awakeFromNib] at NavBonjourAppDelegate.m:25
#7  0x004a94f0 in -[UINib instantiateWithOwner:options:]
#8  0x004ab081 in -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:]
#9  0x002b5943 in -[UIApplication _loadMainNibFile]
#10 0x002b64ca in -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:]
#11 0x002c0db2 in -[UIApplication handleEvent:withNewEvent:]
#12 0x002b9202 in -[UIApplication sendEvent:]
#13 0x002be732 in _UIApplicationHandleEvent
#14 0x018b7a36 in PurpleEventCallback
#15 0x00f63064 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
#16 0x00ec36f7 in __CFRunLoopDoSource1
#17 0x00ec0983 in __CFRunLoopRun
#18 0x00ec0240 in CFRunLoopRunSpecific
#19 0x00ec0161 in CFRunLoopRunInMode
#20 0x002b5fa8 in -[UIApplication _run]
#21 0x002c242e in UIApplicationMain
#22 0x0000209c in main at main.m:14
</code>```

from #0 details:

```<code>0x97225eec  <+0000>  mov    $0xc0025,%eax
0x97225ef1  <+0005>  call   0x971c53d8 <_sysenter_trap>
0x97225ef6  <+0010>  jae    0x97225f06 <__kill+26>
0x97225ef8  <+0012>  call   0x97225efd <__kill+17>
0x97225efd  <+0017>  pop    %edx
0x97225efe  <+0018>  mov    0x96c29e3(%edx),%edx
0x97225f04  <+0024>  jmp    *%edx
0x97225f06  <+0026>  ret
</code>```

答: It's a missmatch in Data Models. Just delete the "old" version from simulator/device and run again, should work then.</p>

Body:
If I build a new project using the IOS Navigation template and add a single attribute to event entity in the data model, and then run, the application crashes.

I'm new to IOS development and have worked through the Apple Core Data app tutorial, and have read a few posts on migration issues, but I haven't seen this specific problem discussed so I must be missing something incredibly obvious.

Do I need to refresh the data model? Is it a migration issue? It has no existing entries as it's a clean application.

Thanks!

Console Output:

#0  0x97225ef6 in __kill
#1  0x97225ee8 in kill$UNIX2003
#2  0x972b862d in raise
#3  0x972ce6e4 in abort
#4  0x00002674 in -[NavBonjourAppDelegate persistentStoreCoordinator] at NavBonjourAppDelegate.m:175
#5  0x00002342 in -[NavBonjourAppDelegate managedObjectContext] at NavBonjourAppDelegate.m:111
#6  0x0000210e in -[NavBonjourAppDelegate awakeFromNib] at NavBonjourAppDelegate.m:25
#7  0x004a94f0 in -[UINib instantiateWithOwner:options:]
#8  0x004ab081 in -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:]
#9  0x002b5943 in -[UIApplication _loadMainNibFile]
#10 0x002b64ca in -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:]
#11 0x002c0db2 in -[UIApplication handleEvent:withNewEvent:]
#12 0x002b9202 in -[UIApplication sendEvent:]
#13 0x002be732 in _UIApplicationHandleEvent
#14 0x018b7a36 in PurpleEventCallback
#15 0x00f63064 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
#16 0x00ec36f7 in __CFRunLoopDoSource1
#17 0x00ec0983 in __CFRunLoopRun
#18 0x00ec0240 in CFRunLoopRunSpecific
#19 0x00ec0161 in CFRunLoopRunInMode
#20 0x002b5fa8 in -[UIApplication _run]
#21 0x002c242e in UIApplicationMain
#22 0x0000209c in main at main.m:14

from #0 details:

0x97225eec  <+0000>  mov    $0xc0025,%eax
0x97225ef1  <+0005>  call   0x971c53d8 <_sysenter_trap>
0x97225ef6  <+0010>  jae    0x97225f06 <__kill+26>
0x97225ef8  <+0012>  call   0x97225efd <__kill+17>
0x97225efd  <+0017>  pop    %edx
0x97225efe  <+0018>  mov    0x96c29e3(%edx),%edx
0x97225f04  <+0024>  jmp    *%edx
0x97225f06  <+0026>  ret


问:
c++ unordered_map iterator on single object
I have a string and an unordered_map of (string, Object). I already have some code in which I am iterating over the map:

```<code>for(auto& item : map) {
    do_something;
}
</code>```

I want to modify it to do the part inside the for loop when the string is non-empty and found inside the map else if string is empty do it for all items in the map.

```<code>if(!string.empty()){
    item = map.find(string);
    do_something;
}
else {
    for(auto& item : map) {
        do_something;
    }
}
</code>```

Can I do this without rewriting the do_something or creating a separate function?

答:
To follow the line of thought you presented in the comments. You can replace the range for loop by a regular for loop over a specific range (defined by iterators). To define it, you'd need something like this:

```<code>auto begin = map.begin(), end = map.end(); // The whole map

if(!string.empty())
  std::tie(begin, end) = map.equal_range(string);
  // constrain range to the single element

for(; begin != end; ++begin) { // loop over it
  auto& item = *begin;
  // Do something
}
</code>```

The star of the above is std::unordered_map::equal_range.

Body:
I have a string and an unordered_map of (string, Object). I already have some code in which I am iterating over the map:

for(auto& item : map) {
    do_something;
}

I want to modify it to do the part inside the for loop when the string is non-empty and found inside the map else if string is empty do it for all items in the map.

if(!string.empty()){
    item = map.find(string);
    do_something;
}
else {
    for(auto& item : map) {
        do_something;
    }
}

Can I do this without rewriting the do_something or creating a separate function?

Body:
To follow the line of thought you presented in the comments. You can replace the range for loop by a regular for loop over a specific range (defined by iterators). To define it, you'd need something like this:

auto begin = map.begin(), end = map.end(); // The whole map

if(!string.empty())
  std::tie(begin, end) = map.equal_range(string);
  // constrain range to the single element

for(; begin != end; ++begin) { // loop over it
  auto& item = *begin;
  // Do something
}

The star of the above is std::unordered_map::equal_range.


问:
Can you use push notifications and in app purchases?
I noticed that apps that use push notifications and in app purchases need unique bundle identifiers for the various features they entail.

Would there be a conflict of interests or can you use both features in the same app?

答:
Yes you can.

Bundle identifiers allow the Apple ecosystem to identify your particular app between all the millions(?) other ones. Having one bundle id, and only one, is absolutely ok and intended. You can use all the services in parallel like remote notifications, in app purchases and others. All these services live in their own 'universe' and don't care if you also use your app with another service.


问:
Is print in Haskell a pure function?
Is print in Haskell a pure function; why or why not? I'm thinking it's not, because it does not always return the same value as pure functions should.

答:
A value of type IO Int is not really an Int. It's more like a piece of paper which reads "hey Haskell runtime, please produce an Int value in such and such way". The piece of paper is inert and remains the same, even if the Ints eventually produced by the runtime are different.

You send the piece of paper to the runtime by assigning it to main. If the IO action never comes in the way of main and instead languishes inside some container, it will never get executed.

Functions that return IO actions are pure like the others. They always return the same piece of paper. What the runtime does with those instructions is another matter.

If they weren't pure, we would have to think twice before changing

```<code>foo :: (Int -> IO Int) -> IO Int
foo f = liftA2 (+) (f 0) (f 0)
</code>```

to:

```<code>foo :: (Int -> IO Int) -> IO Int
foo f = let x = f 0 in liftA2 (+) x x
</code>```

ContentLicense: CC BY-SA 4.0

Title: Is print in Haskell a pure function?

Body:
A value of type IO Int is not really an Int. It's more like a piece of paper which reads "hey Haskell runtime, please produce an Int value in such and such way". The piece of paper is inert and remains the same, even if the Ints eventually produced by the runtime are different.

You send the piece of paper to the runtime by assigning it to main. If the IO action never comes in the way of main and instead languishes inside some container, it will never get executed.

Functions that return IO actions are pure like the others. They always return the same piece of paper. What the runtime does with those instructions is another matter.

If they weren't pure, we would have to think twice before changing

foo :: (Int -> IO Int) -> IO Int
foo f = liftA2 (+) (f 0) (f 0)

to:

foo :: (Int -> IO Int) -> IO Int
foo f = let x = f 0 in liftA2 (+) x x


问:
why I get wrong current user in firebase android xamarin
I use this code to define Current user and email in Firebase:

```<code>var CurrentUserEmail = FirebaseAuth.Instance.CurrentUser.Email;
</code>```

It doesn't give the right user and email. Did you have the same issue?

答:
I am not familiar with xamarin, but if you want to get a the current user or his/her email then you should make sure that the user is signed in or else you can't get these details, something like that:</p>

```<code> //get the current user like that

var currentuser =FirebaseAuth.Instance.CurrentUser;

 //check is user not null (in other words if user signed in)

  if(currentuser != null){

   //this means user is signed in

     //get user uid
    var uid= currentuser.Uid;

     //get user email
    var email= currnetuser.Email;

  }
</code>```

Body:
I use this code to define Current user and email in Firebase:

var CurrentUserEmail = FirebaseAuth.Instance.CurrentUser.Email;

It doesn't give the right user and email. Did you have the same issue?

Body:
I am not familiar with xamarin, but if you want to get a the current user or his/her email then you should make sure that the user is signed in or else you can't get these details, something like that:

 //get the current user like that

var currentuser =FirebaseAuth.Instance.CurrentUser;

 //check is user not null (in other words if user signed in)

  if(currentuser != null){

   //this means user is signed in

     //get user uid
    var uid= currentuser.Uid;

     //get user email
    var email= currnetuser.Email;

  }


问:
Can we reassign the reference in C++?
I have read everywhere that a reference has to be initialized then and there and can't be re-initialized again.

To test my understanding, I have written the following small program. It seems as if I have actually succeeded in reassigning a reference. Can someone explain to me what is actually going on in my program?

```<code>#include <iostream>
#include <stdio.h>
#include <conio.h>

using namespace std;

int main()
{
    int i = 5, j = 9;

    int &ri = i;
    cout << " ri is : " << ri  <<"\n";

    i = 10;
    cout << " ri is : " << ri  << "\n";

    ri = j; // >>> Is this not reassigning the reference? <<<
    cout << " ri is : " << ri  <<"\n";

    getch();
    return 0;
}
</code>```

The code compiles fine and the output is as I expect:

ri is : 5
ri is : 10
ri is : 9
```

答:
OP asked for altering the referenced object through assignment to the reference and was very correctly told that this changed the reference object, not the reference.
Now I did a more poignant attempt at really changing the reference and found potentially nasty stuff.
First the code. It attempts to reassign to the reference var a newly created object, then alters the reference aka referenced object, finds that this is not reflected in the apparently referenced objects and concludes that we may have a case of a dangling pointer in C++. Sorry for the hastily composed code.

```<code>using namespace std;
vector<int>myints;

auto &i = myints.emplace_back();   // allocate and reference new int in vector
auto myintsaddr = &myints; auto myintfrontaddr = &myints.front(); // for future reference
i = 1;                             // assign a value to the new int through reference
cout << hex << "address of i: 0x" << &i << " equals " << "address of
myints.back(): 0x" << &myints.back() << '.' << endl;  // check reference as expected
i = myints.emplace_back();     // allocate new int in vector and assign to old reference variable
i = 2;                         // give another value to i
cout << "i=" << i << ", myints={" << myints[0] << ", "<< myints[1] << '}' << endl; // any change to potentially referenced objects?
cout << hex << "&i: 0x" << &i << " unequal to " << "&myints.back(): 0x" << &myints.back() << " as well as &myints.front(): 0x" << &myints.front() << endl;
cout << "Myints " << (myintsaddr== &myints?"not ":"") << "relocated from " << myintsaddr << " to " << &myints << endl;
cout << "Myints front() " << (myintfrontaddr == &myints.front() ? "not " : "") << "relocated from " << myintfrontaddr << " to " << &myints.front() << endl;
</code>```

Output:

```<code>address of i: 0x0063C1A0 equals address of myints.back(): 0x0063C1A0.
i=2, myints={1, 0}
&i: 0x0063C1A0 unequal to &myints.back(): 0x0063F00C as well as &myints.front(): 0x0063F008
Myints not relocated from 0039FE48 to 0039FE48
Myints front() relocated from 0063C1A0 to 0063F008
</code>```

Conclusion: at least in my case (VS2017) the reference has kept the exact same address in memory, but the referenced values (part of the vector) have been reallocated elsewhere. Reference i may be dangling.

Title: Can we reassign the reference in C++?

Body:
I have read everywhere that a reference has to be initialized then and there and can't be re-initialized again.

To test my understanding, I have written the following small program. It seems as if I have actually succeeded in reassigning a reference. Can someone explain to me what is actually going on in my program?

#include <iostream>
#include <stdio.h>
#include <conio.h>

using namespace std;

int main()
{
    int i = 5, j = 9;

    int &ri = i;
    cout << " ri is : " << ri  <<"\n";

    i = 10;
    cout << " ri is : " << ri  << "\n";

    ri = j; // >>> Is this not reassigning the reference? <<<
    cout << " ri is : " << ri  <<"\n";

    getch();
    return 0;
}

The code compiles fine and the output is as I expect:

ri is : 5
ri is : 10
ri is : 9

Body:
OP asked for altering the referenced object through assignment to the reference and was very correctly told that this changed the reference object, not the reference.
Now I did a more poignant attempt at really changing the reference and found potentially nasty stuff.
First the code. It attempts to reassign to the reference var a newly created object, then alters the reference aka referenced object, finds that this is not reflected in the apparently referenced objects and concludes that we may have a case of a dangling pointer in C++. Sorry for the hastily composed code.

using namespace std;
vector<int>myints;

auto &i = myints.emplace_back();   // allocate and reference new int in vector
auto myintsaddr = &myints; auto myintfrontaddr = &myints.front(); // for future reference
i = 1;                             // assign a value to the new int through reference
cout << hex << "address of i: 0x" << &i << " equals " << "address of
myints.back(): 0x" << &myints.back() << '.' << endl;  // check reference as expected
i = myints.emplace_back();     // allocate new int in vector and assign to old reference variable
i = 2;                         // give another value to i
cout << "i=" << i << ", myints={" << myints[0] << ", "<< myints[1] << '}' << endl; // any change to potentially referenced objects?
cout << hex << "&i: 0x" << &i << " unequal to " << "&myints.back(): 0x" << &myints.back() << " as well as &myints.front(): 0x" << &myints.front() << endl;
cout << "Myints " << (myintsaddr== &myints?"not ":"") << "relocated from " << myintsaddr << " to " << &myints << endl;
cout << "Myints front() " << (myintfrontaddr == &myints.front() ? "not " : "") << "relocated from " << myintfrontaddr << " to " << &myints.front() << endl;

Output:

address of i: 0x0063C1A0 equals address of myints.back(): 0x0063C1A0.
i=2, myints={1, 0}
&i: 0x0063C1A0 unequal to &myints.back(): 0x0063F00C as well as &myints.front(): 0x0063F008
Myints not relocated from 0039FE48 to 0039FE48
Myints front() relocated from 0063C1A0 to 0063F008

Conclusion: at least in my case (VS2017) the reference has kept the exact same address in memory, but the referenced values (part of the vector) have been reallocated elsewhere. Reference i may be dangling.


问:
is there a faster way to write similar test cases for Django views?
Basically, I realize that I am writing the same test case (test_update_with_only_1_field) for a similar URL for multiple models

```<code>from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
    superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword')
    self.factory = RequestFactory()
    self.user = superuser
    self.client.login(username=superuser.username, password='testpassword')

class SomeModelApiTests(base_tests.BaseApiTest):
def test_update_with_only_1_field(self):
    """
    Tests for update only 1 field

    GIVEN the following shape and related are valid
    WHEN we update only with just 1 field
    THEN we expect the update to be successful
    """
    shape_data = {
        'name': 'test shape',
        'name_en': 'test shape en',
        'name_zh_hans': 'test shape zh hans',
        'serial_number': 'test shape serial number',
        'model_name': {
            'some_field': '123'
        }
    }

    data = json.dumps(shape_data)
    response = self.client.post(reverse('shape-list-create'), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    some_model = response.data['some_model']
    new_some_field = '12345'

    data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']})
    response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(new_some_field, response.data['some_field'])
</code>```

I need to do this for more than 10 times. Which I have already done so.

the only difference each time, is the following phrases "some_model", "some-model", and "some_field"

I was wondering if there's a faster way to do this.

I can think abstractly two ways:

create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor

There's a way I can write slightly more code in the form of converting this test case into a behavior class that the individual test class can call. aka composition.

Which one makes more sense or there's a different way to do this?

Please note that BaseApi class is also inherited by other test class that do NOT have that repetitive test case method.

答:
You can use pytest package for unit testing.
It is very simple and easy to use.

@pytest.mark.parametrize() decorator can be used to achieve that functionality.

An example for parametrized test cases is as follows:

```<code>import pytest
class SampleTesting(object):
    data_for_test = [
                      ('{inputdata1:value1}','output1'),
                      ('{inputdata1:value2}','output2')
                     ]
   @pytest.mark.parametrized('input_data, expected_output', data_for_test)
   def test_sample_function(self, input_data, expected_output):
       response = function_to_be_tested(input_data)
       assert response == expected_output
</code>```

You can read more about this decorator in the docs'

You can also use the @pytest.fixture() decorator to setup the test function.

Body:
Basically, I realize that I am writing the same test case (test_update_with_only_1_field) for a similar URL for multiple models

from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
    superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword')
    self.factory = RequestFactory()
    self.user = superuser
    self.client.login(username=superuser.username, password='testpassword')

class SomeModelApiTests(base_tests.BaseApiTest):
def test_update_with_only_1_field(self):
    """
    Tests for update only 1 field

    GIVEN the following shape and related are valid
    WHEN we update only with just 1 field
    THEN we expect the update to be successful
    """
    shape_data = {
        'name': 'test shape',
        'name_en': 'test shape en',
        'name_zh_hans': 'test shape zh hans',
        'serial_number': 'test shape serial number',
        'model_name': {
            'some_field': '123'
        }
    }

    data = json.dumps(shape_data)
    response = self.client.post(reverse('shape-list-create'), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    some_model = response.data['some_model']
    new_some_field = '12345'

    data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']})
    response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(new_some_field, response.data['some_field'])

I need to do this for more than 10 times. Which I have already done so.

the only difference each time, is the following phrases "some_model", "some-model", and "some_field"

I was wondering if there's a faster way to do this.

I can think abstractly two ways:

create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor

There's a way I can write slightly more code in the form of converting this test case into a behavior class that the individual test class can call. aka composition.

Which one makes more sense or there's a different way to do this?

Please note that BaseApi class is also inherited by other test class that do NOT have that repetitive test case method.

Body:
You can use pytest package for unit testing.
It is very simple and easy to use.

@pytest.mark.parametrize() decorator can be used to achieve that functionality.

An example for parametrized test cases is as follows:

import pytest
class SampleTesting(object):
    data_for_test = [
                      ('{inputdata1:value1}','output1'),
                      ('{inputdata1:value2}','output2')
                     ]
   @pytest.mark.parametrized('input_data, expected_output', data_for_test)
   def test_sample_function(self, input_data, expected_output):
       response = function_to_be_tested(input_data)
       assert response == expected_output

You can read more about this decorator in the docs'

You can also use the @pytest.fixture() decorator to setup the test function.


问:
grunt "undefined variable" errors for imported sass files
I am trying to set up grunt to compile my sass into css.

I actually have it working, but the problem (I think) is that the way I have the grunt file structured, it is compiling every scss file in the watch task, rather than just the base scss file, which imports all the others. As a result, even though they're not being used, the compiled .css files all have ugly backtrace statements in them for the errors on the undefined variables, and I imagine grunt is running much slower because it's compiling each sass file into a css file, instead of just the one base file.

What I want to have happen is grunt recognize a change in any scss file in the watch task, but only compile the base scss file. Below is my base scss file, and an excerpt from my grunt file:

base.scss:

```<code>@import "compass";
@import "breakpoint";
@import "singularitygs";
@import "toolkit-no-css";

@import "variables/**/*";
@import "abstractions/**/*";
@import "base/**/*";
@import "components/**/*";
@import "pages/*";
</code>```

gruntfile:

```<code>module.exports = function (grunt) {

  grunt.initConfig({
    watch: {
      sass: {
        files: ['sass/{,**/}*.{scss,sass}'],
        tasks: ['compass:dev'],
        options: {
          livereload: false
        }
      },
      css: {
        files: ['css/{,**/}*.css']
      }
    },
    compass: {
      options: {
        config: 'config.rb',
        bundleExec: true,
        force: true
      },
      dev: {
        options: {
          environment: 'development'
        }
      },
      dist: {
        options: {
          environment: 'production'
        }
      }
    }

  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-shell');

  grunt.registerTask('build', [
    'uglify:dist',
    'compass:dist',
    'jshint'
  ]);

};
</code>```

UPDATE:
Here is my config.rb:

```<code>saved = environment
if (environment.nil?)
  environment = :development
else
  environment = saved
end

# Location of the theme's resources.
css_dir = "css"
sass_dir = "sass"
images_dir = "images"
generated_images_dir = images_dir + "/generated"
javascripts_dir = "js"

# Require any additional compass plugins installed on your system.
require 'compass-normalize'
require 'rgbapng'
require 'toolkit'
require 'singularitygs'
require 'sass-globbing'

##
## You probably don't need to edit anything below this.
##

output_style = (environment == :production) ? :expanded : :nested

line_comments = (environment == :production) ? false : true

sass_options = (environment == :production) ? {} : {:debug_info => false} #MH  - turned off debugging - doesn't seem to be rendering properly

add_import_path 'sass'
</code>```

How do I fix this?

答:
Faced same issue while using grunt-sass
( Grunt sass compilation  was working fine with grunt-contrib-sass)

```<code>Running "sass:build" (sass) task
</code>```

Error: Undefined variable: "$size".
            on line 135 of output/xxx_core/cartridge/static/default/css/scss/helpers/_mixins.scss

*/
           --^
        Warning:  Use --force to continue.

Aborted due to warnings.
enter code here

File naming was totally correct. After hours of debugging I found that if I removed the commented code from scss file which in my case was

```<code>/*
@mixin arialFont($size, $lineHeight, $family) {
   font: #{$size}/#{$lineHeight} $family
}
*/
</code>```

Sass compilation started working with grunt-sass as well

Body:
I am trying to set up grunt to compile my sass into css.

I actually have it working, but the problem (I think) is that the way I have the grunt file structured, it is compiling every scss file in the watch task, rather than just the base scss file, which imports all the others. As a result, even though they're not being used, the compiled .css files all have ugly backtrace statements in them for the errors on the undefined variables, and I imagine grunt is running much slower because it's compiling each sass file into a css file, instead of just the one base file.

What I want to have happen is grunt recognize a change in any scss file in the watch task, but only compile the base scss file. Below is my base scss file, and an excerpt from my grunt file:

base.scss:

@import "compass";
@import "breakpoint";
@import "singularitygs";
@import "toolkit-no-css";

@import "variables/**/*";
@import "abstractions/**/*";
@import "base/**/*";
@import "components/**/*";
@import "pages/*";

gruntfile:

module.exports = function (grunt) {

  grunt.initConfig({
    watch: {
      sass: {
        files: ['sass/{,**/}*.{scss,sass}'],
        tasks: ['compass:dev'],
        options: {
          livereload: false
        }
      },
      css: {
        files: ['css/{,**/}*.css']
      }
    },
    compass: {
      options: {
        config: 'config.rb',
        bundleExec: true,
        force: true
      },
      dev: {
        options: {
          environment: 'development'
        }
      },
      dist: {
        options: {
          environment: 'production'
        }
      }
    }

  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-shell');

  grunt.registerTask('build', [
    'uglify:dist',
    'compass:dist',
    'jshint'
  ]);

};

UPDATE:
Here is my config.rb:

saved = environment
if (environment.nil?)
  environment = :development
else
  environment = saved
end

# Location of the theme's resources.
css_dir = "css"
sass_dir = "sass"
images_dir = "images"
generated_images_dir = images_dir + "/generated"
javascripts_dir = "js"

# Require any additional compass plugins installed on your system.
require 'compass-normalize'
require 'rgbapng'
require 'toolkit'
require 'singularitygs'
require 'sass-globbing'

##
## You probably don't need to edit anything below this.
##

output_style = (environment == :production) ? :expanded : :nested

line_comments = (environment == :production) ? false : true

sass_options = (environment == :production) ? {} : {:debug_info => false} #MH  - turned off debugging - doesn't seem to be rendering properly

add_import_path 'sass'

How do I fix this?

Body:
Faced same issue while using grunt-sass
( Grunt sass compilation  was working fine with grunt-contrib-sass)

Running "sass:build" (sass) task

Error: Undefined variable: "$size".
            on line 135 of output/xxx_core/cartridge/static/default/css/scss/helpers/_mixins.scss

*/
           --^
        Warning:  Use --force to continue.

Aborted due to warnings.
enter code here

File naming was totally correct. After hours of debugging I found that if I removed the commented code from scss file which in my case was

/*
@mixin arialFont($size, $lineHeight, $family) {
   font: #{$size}/#{$lineHeight} $family
}
*/

Sass compilation started working with grunt-sass as well


问:
write the result into input field
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span style="font-size:20px;">Your bid:</span> <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;"> <br>
        <input type="button" onClick="cal();">
        <span style="font-size:20px;" >Our Fee (10%):</span><input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;"><br>
        <span style="font-size:20px;">You'll paid:</span> <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;"></code>```

答:
You should use id instead of name to get elements in javascript and you saved the input field in the variable bid instead of saving the value of the input field.

```<code><html>

<head>
  <script>
    function cal() {

      var bid = document.getElementById("bid").value;

      var result1 = bid * 0.1;
      var result2 = bid - result1;

      document.getElementById("fee").value = result1;
      document.getElementById("get").value = result2;

    }
  </script>
</head>

<body>
  <span style="font-size:20px;">Your bid:</span> <input type="number" id="bid" class="form-control" style="max-width:250px; margin-top:10px;"> <br>
  <input type="button" onClick="cal();">
  <span style="font-size:20px;">Our Fee (10%):</span><input type="number" id="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;"><br>
  <span style="font-size:20px;">You'll paid:</span> <input type="number" id="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

</body>

</html>
</code>```

Title: write the result into input field

Body:
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

Your bid: <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;">

        <input type="button" onClick="cal();">
        Our Fee (10%):<input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">

        You'll paid: <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

Body:
You should use id instead of name to get elements in javascript and you saved the input field in the variable bid instead of saving the value of the input field.

<html>

<head>
  <script>
    function cal() {

      var bid = document.getElementById("bid").value;

      var result1 = bid * 0.1;
      var result2 = bid - result1;

      document.getElementById("fee").value = result1;
      document.getElementById("get").value = result2;

    }
  </script>
</head>

<body>
  <span style="font-size:20px;">Your bid:</span> <input type="number" id="bid" class="form-control" style="max-width:250px; margin-top:10px;"> <br>
  <input type="button" onClick="cal();">
  <span style="font-size:20px;">Our Fee (10%):</span><input type="number" id="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;"><br>
  <span style="font-size:20px;">You'll paid:</span> <input type="number" id="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

</body>

</html>


问:
Excel VBA - create column names using MS Project headers
I'm in the middle of writing a script that populates an excel spreadsheet with data from an MS Project file.  I would like the script to recognize the title name of the MS Project columns as I have a number of custom columns with different names (custom number fields are populated with different names)

The code below was my attempt, but i'm getting an error when it comes to writing the value of the task column title to the sheet, am I doing something wrong here?

```<code>Sub PopulateSheet()
Dim Proj             As MSProject.Application
Dim NewProj          As MSProject.Project
Dim t                As MSProject.Task

Dim xl as workbook
Dim s as worksheet
Dim Newsheet as worksheet

Set Xl = ThisWorkbook
BookNam = Xl.Name
Set Newsheet = Xl.Worksheets.Add

'Code to find and open project files
Set Proj = New MSProject.Application
MsgBox ("Please Select MS Project File for Quality Checking")

'Select Project File
FileOpenType = Application.GetOpenFilename( _
               FileFilter:="MS Project Files (*.mpp), *.mpp", _
               Title:="Select MS Project file", _
               MultiSelect:=False)

'Detect if File is selected, if not then stop code
If FileOpenType = False Then
    MsgBox ("You Havent Selected a File")
    Exit Sub
End If

'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)

Newsheet.Name = NewProjFileName
Set s = Newsheet

'Populate spreadsheet header row with column titles from MS Project
s.Range("A1").Value = t.Number1  ***<-- Error '91' - Object variable or With block variable not set***

End Sub
</code>```

答:
Here is generic code that loops through the fields in the active task table and prints out the field headings as displayed in the table.

```<code>Sub GetTaskTableHeaders()

    Dim t As Table
    Set t = ActiveProject.TaskTables(ActiveProject.CurrentTable)
    Dim f As TableField
    For Each f In t.TableFields
        If f.Field > 0 Then
            Dim header As String
            Dim custom As String
            custom = Application.CustomFieldGetName(f.Field)
            If Len(f.Title) > 0 Then
                header = f.Title
            ElseIf Len(custom) > 0 Then
                header = custom
            Else
                header = Application.FieldConstantToFieldName(f.Field)
            End If
            Debug.Print "Field " & f.Index, header
        End If
    Next f

End Sub
</code>```

Note that fields can be customized at the project level to be given a different title, or they can be customized at the table level. This code looks for both customizations and if neither is found, the field name is used.

Body:
I'm in the middle of writing a script that populates an excel spreadsheet with data from an MS Project file.  I would like the script to recognize the title name of the MS Project columns as I have a number of custom columns with different names (custom number fields are populated with different names)

The code below was my attempt, but i'm getting an error when it comes to writing the value of the task column title to the sheet, am I doing something wrong here?

Sub PopulateSheet()
Dim Proj             As MSProject.Application
Dim NewProj          As MSProject.Project
Dim t                As MSProject.Task

Dim xl as workbook
Dim s as worksheet
Dim Newsheet as worksheet

Set Xl = ThisWorkbook
BookNam = Xl.Name
Set Newsheet = Xl.Worksheets.Add

'Code to find and open project files
Set Proj = New MSProject.Application
MsgBox ("Please Select MS Project File for Quality Checking")

'Select Project File
FileOpenType = Application.GetOpenFilename( _
               FileFilter:="MS Project Files (*.mpp), *.mpp", _
               Title:="Select MS Project file", _
               MultiSelect:=False)

'Detect if File is selected, if not then stop code
If FileOpenType = False Then
    MsgBox ("You Havent Selected a File")
    Exit Sub
End If

'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)

Newsheet.Name = NewProjFileName
Set s = Newsheet

'Populate spreadsheet header row with column titles from MS Project
s.Range("A1").Value = t.Number1  ***<-- Error '91' - Object variable or With block variable not set***

End Sub

Body:
Here is generic code that loops through the fields in the active task table and prints out the field headings as displayed in the table.

Sub GetTaskTableHeaders()

    Dim t As Table
    Set t = ActiveProject.TaskTables(ActiveProject.CurrentTable)
    Dim f As TableField
    For Each f In t.TableFields
        If f.Field > 0 Then
            Dim header As String
            Dim custom As String
            custom = Application.CustomFieldGetName(f.Field)
            If Len(f.Title) > 0 Then
                header = f.Title
            ElseIf Len(custom) > 0 Then
                header = custom
            Else
                header = Application.FieldConstantToFieldName(f.Field)
            End If
            Debug.Print "Field " & f.Index, header
        End If
    Next f

End Sub

Note that fields can be customized at the project level to be given a different title, or they can be customized at the table level. This code looks for both customizations and if neither is found, the field name is used.


问:
Activate certain functions based on percent
```<code>            if chance == 1:
                function1()

            elif chance == 4:
                function2()

            elif chance == 20:
                function3()

            elif chance == 10:
                functiongettingoutofideas()

            elif chance == 40:
               function_minecraft_club_was_not_on_today_insertcryingemoji()

            elif chance == 10:
               function8()

            elif chance == 4:
                functionthesearealotoffunctions()

            elif chance == 5:
                function_above_when_i_mean_5_i_mean_5_percent_chance()

            elif chance == 6:
                function_thank_you_for_your_help()
</code>```

In the if and the elifs when i put for example, chance == 10, that means there is a 10% chance of that function being activated.

Any help will be much appreciated

答:
If you pick a random number between 0-100, and you want a 10% chance of something happening, you can do:

```<code>if random < 10:
    doSomething()
</code>```

The doSomething will happen for the numbers 0-10, but not for the numbers 11-100, giving you a 10% chance. Repeat as needed for other functions / probabilities.

Body:
            if chance == 1:
                function1()

            elif chance == 4:
                function2()

            elif chance == 20:
                function3()

            elif chance == 10:
                functiongettingoutofideas()

            elif chance == 40:
               function_minecraft_club_was_not_on_today_insertcryingemoji()

            elif chance == 10:
               function8()

            elif chance == 4:
                functionthesearealotoffunctions()

            elif chance == 5:
                function_above_when_i_mean_5_i_mean_5_percent_chance()

            elif chance == 6:
                function_thank_you_for_your_help()

In the if and the elifs when i put for example, chance == 10, that means there is a 10% chance of that function being activated.

Any help will be much appreciated

Body:
If you pick a random number between 0-100, and you want a 10% chance of something happening, you can do:

if random < 10:
    doSomething()

The doSomething will happen for the numbers 0-10, but not for the numbers 11-100, giving you a 10% chance. Repeat as needed for other functions / probabilities.


问:
JpaRepository.findOne()'s influence on JpaRepository.getOne()
I am using spring boot, spring web and spring data for the following example.

I have one entity called Person and I already populated two Persons in the database:

Person entity

```<code>@Entity
public class Person {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
private long id;
private String name;

public long getId() {
    return id;
}
public void setId(long id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Personne() {
}
public Personne(long id, String name) {
    this.id = id;
    this.name = name;
}}
</code>```

PersonRepository

```<code>@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
}
</code>```

PersonController

```<code>@RestController
public class PersonController {

@Autowired
private PersonRepository personRepo;

@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
    return personRepo.xxxx(id);
}}
</code>```

Use case 1:

When I replace personRepo.xxxx(id) with personRepo.getOne(id) and tap localhost:8080/perss/1 i get Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) error in the browser due to the fact that getOne() method returns a proxy to Person that jackson somehow cannot convert.

Use case 2:

When I replace personRepo.xxxx(id) with personRepo.findOne(id) and tap localhost:8080/perss/1 I get the desired Person object in the correct JSON format (this one works fine).

Use case 3:

When I replace PersonController getById() method's code with the following one:

```<code>@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
    Person p1 = personRepo.findOne(id);
    Person p2 = personRepo.getOne(id);
    return p2;
}
</code>```

And tap localhost:8080/perss/1 I get the wanted Person object in the correct JSON format.

Question:

Using getOne() got me an error, but using findOne() and getOne() together gave me good result.

How does the findOne() influence the getOne()'s behavior.

EDIT

Use Case 4

When I reverse the order of p1 and p2 i get an error.

```<code>@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
    Person p2 = personRepo.getOne(id);
    Person p1 = personRepo.findOne(id);
    return p2;
}
</code>```

答:
You are correct that the order of invocation does effect the result when using both findOne() and getOne().

Short Answer: Both methods will first lookup the ID in the persistence context and return the cached value if it is present. If there is nothing found in the persistence context, they will proceed to load their preferred result and cache it. The cached value will be found by the other method the next time it runs.

getOne(id) will load (and cache) a proxy if id is not in the persistence context.

findOne(id) will load (and cache) the naked entity if id is not in the persistence context.

Long Answer: I ran into the same problem and my project uses Hibernate 5.2.4.Final. The details of what is happening involves some Hibernate code. After debugging for a while I found that both findOne() and getOne() eventually call Hibernate's DefaultLoadEventListener.onLoad() method, but they call it with different loadType arguments:

getOne() eventually delegates to SessionImpl.IdentifierLoadAccessImpl<T>.doGetReference() which specifies the loadType of LoadEventListener.LOAD which is eventually passed down to DefaultLoadEventListener.proxyOrLoad(). LoadEventListener.LOAD does allow for the creation of a proxy.

findOne() eventually delegates to SessionImpl.IdentifierLoadAccessImpl<T>.doLoad() which specifies the loadType value of LoadEventListener.GET which is eventually passed down to DefaultLoadEventListener.proxyOrLoad(). LoadEventListener.GET does not allow creation of a proxy.

Set a breakpoint in DefaultLoadEventListener.proxyOrLoad() to verify that the LoadType options argument that is passed in has different values for its allowProxyCreation field depending on whether findOne() or getOne() is calling it.

You can see that if allowProxyCreation is true and there is no proxy, then proxyOrLoad() will return the result of createProxyIfNecessary(). In the case where only getOne() is used, this will result in returning a proxy.

If it happens that findOne() was called for the same entity type and ID before getOne(), then when the getOne() call makes its way into createProxyIfNecessary() it will return early because the entity will already be found in the persistence context. In that case calling getOne() will not result in creating a proxy.

If you call getOne() before findOne() then the proxy will be created and stored in the persistence context, and findOne() will also return the proxy because it will simply retrieve the cached proxy from the persistence context.

Body:
I am using spring boot, spring web and spring data for the following example.

I have one entity called Person and I already populated two Persons in the database:

Person entity

@Entity
public class Person {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
private long id;
private String name;

public long getId() {
    return id;
}
public void setId(long id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Personne() {
}
public Personne(long id, String name) {
    this.id = id;
    this.name = name;
}}

PersonRepository

@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
}

PersonController

@RestController
public class PersonController {

@Autowired
private PersonRepository personRepo;

@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
    return personRepo.xxxx(id);
}}

Use case 1:

When I replace personRepo.xxxx(id) with personRepo.getOne(id) and tap localhost:8080/perss/1 i get Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) error in the browser due to the fact that getOne() method returns a proxy to Person that jackson somehow cannot convert.

Use case 2:

When I replace personRepo.xxxx(id) with personRepo.findOne(id) and tap localhost:8080/perss/1 I get the desired Person object in the correct JSON format (this one works fine).

Use case 3:

When I replace PersonController getById() method's code with the following one:

@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
    Person p1 = personRepo.findOne(id);
    Person p2 = personRepo.getOne(id);
    return p2;
}

And tap localhost:8080/perss/1 I get the wanted Person object in the correct JSON format.

Question:

Using getOne() got me an error, but using findOne() and getOne() together gave me good result.

How does the findOne() influence the getOne()'s behavior.

EDIT

Use Case 4

When I reverse the order of p1 and p2 i get an error.

@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
    Person p2 = personRepo.getOne(id);
    Person p1 = personRepo.findOne(id);
    return p2;
}


问:
Why AVCaptureSession output a wrong orientation?
So, I followed Apple's instructions to capture video session using AVCaptureSession: http://developer.apple.com/iphone/library/qa/qa2010/qa1702.html. One problem I'm facing is that even though the orientation of the camera / iPhone device is vertical (and the AVCaptureVideoPreviewLayer shows a vertical camera stream), the output image seems to be in the landscape mode. I checked the width and height of imageBuffer inside imageFromSampleBuffer: of the sample code, and I got 640px and 480px respectively. Does anyone know why this's the case?

Thanks!

答:
You can try this:</p>

```<code>private func startLiveVideo() {

    let captureSession = AVCaptureSession()
    captureSession.sessionPreset = .photo
    let captureDevice = AVCaptureDevice.default(for: .video)

    let input = try! AVCaptureDeviceInput(device: captureDevice!)
    let output = AVCaptureVideoDataOutput()
    captureSession.addInput(input)
    captureSession.addOutput(output)

    output.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
    output.connection(with: .video)?.videoOrientation = .portrait

    let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    previewLayer.frame = view.bounds
    view.layer.addSublayer(previewLayer)

    captureSession.startRunning()
}
</code>```

Body:
You can try this:

private func startLiveVideo() {

    let captureSession = AVCaptureSession()
    captureSession.sessionPreset = .photo
    let captureDevice = AVCaptureDevice.default(for: .video)

    let input = try! AVCaptureDeviceInput(device: captureDevice!)
    let output = AVCaptureVideoDataOutput()
    captureSession.addInput(input)
    captureSession.addOutput(output)

    output.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
    output.connection(with: .video)?.videoOrientation = .portrait

    let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    previewLayer.frame = view.bounds
    view.layer.addSublayer(previewLayer)

    captureSession.startRunning()
}


问:
What are JavaScript Objects and Properties?
Can anyone explain objects and properties to me in Javascript in layman's terms? The Javascript MDN documentation is confusing me.

I am trying to solve a problem in a Javascript tutorial about objects and properties The question is below and my attempt at the code, I think I followed the MDN as far as I can grasp it. Any help would be appreciated!

Question: Add the value of the property argument as a key on the object argument.
The value of the new property should be set to null.
Return object after adding the new property.

Input Example:

```<code>{}, 'hello'
{ x: 5 }, 'y'
</code>```

Output Example:

```<code>{ hello: null }
{ x: 5, y: null }
</code>```

note: the property name is NOT 'property'.  The name is the value of the argument called property (a string).

My code:
//NOTE: the function addProperty(object, property) was already in the console and I have to write the solution inside of it.

```<code>function addProperty(object, property) {
  // code here
  let result = addProperty({x: 5}, 'y');
  obj[property] = null;
  return obj;
}

addProperty(x, 'y');
</code>```

答:
Layman's explanation:

An object is a collection of properties.  You can give a name to the object to keep things organized.  For example, lets create a person object.

var person = {};

The object has no properties right now.  To further describe the person we can add properties to the object.

```<code>person.Name = 'Zim';
person.Age = 29;
person.Gender = 'Male';
person.Weight = 80;
</code>```

Now this object has some properties to help describe it.  A different way to write the same thing:

var person = { Name: 'Zim', Age: 29, Gender: 'Male', Weight: 80 };

If we had to create a program that displays a list of people, storing all of our information inside objects would help keep things organized.

Object properties are sometimes referred to as keys.

Adding properties to objects:

You can add a property to an object using brackets, just like you had in your addProperty function.  If you just need it to add a property, set that property to null and return the result it would look something like this:

```<code>function addProperty(object, property) {
  // code here
  object[property] = null;
  return object;
}
</code>```

This would let us create a properies on our object from above by calling

```<code>addProperty(person, 'Occupation');
addProperty(person, 'Income');
addProperty(person, 'Height');
</code>```

Body:
Can anyone explain objects and properties to me in Javascript in layman's terms? The Javascript MDN documentation is confusing me.

I am trying to solve a problem in a Javascript tutorial about objects and properties The question is below and my attempt at the code, I think I followed the MDN as far as I can grasp it. Any help would be appreciated!

Question: Add the value of the property argument as a key on the object argument.
The value of the new property should be set to null.
Return object after adding the new property.

Input Example:

{}, 'hello'
{ x: 5 }, 'y'

Output Example:

{ hello: null }
{ x: 5, y: null }

note: the property name is NOT 'property'.  The name is the value of the argument called property (a string).

My code:
//NOTE: the function addProperty(object, property) was already in the console and I have to write the solution inside of it.

function addProperty(object, property) {
  // code here
  let result = addProperty({x: 5}, 'y');
  obj[property] = null;
  return obj;
}

addProperty(x, 'y');

Body:
Layman's explanation:

An object is a collection of properties.  You can give a name to the object to keep things organized.  For example, lets create a person object.

var person = {};

The object has no properties right now.  To further describe the person we can add properties to the object.

person.Name = 'Zim';
person.Age = 29;
person.Gender = 'Male';
person.Weight = 80;

Now this object has some properties to help describe it.  A different way to write the same thing:

var person = { Name: 'Zim', Age: 29, Gender: 'Male', Weight: 80 };

If we had to create a program that displays a list of people, storing all of our information inside objects would help keep things organized.

Object properties are sometimes referred to as keys.

Adding properties to objects:

You can add a property to an object using brackets, just like you had in your addProperty function.  If you just need it to add a property, set that property to null and return the result it would look something like this:

function addProperty(object, property) {
  // code here
  object[property] = null;
  return object;
}

This would let us create a properies on our object from above by calling

addProperty(person, 'Occupation');
addProperty(person, 'Income');
addProperty(person, 'Height');


问:
IntelliSense in Razor files (.cshtml) stopped working
Intellisense does not work in razor files:

In my web.conifg file (in the Views folder) is apparently correct:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
    </configSections>

    <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <namespaces>
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
                <add namespace="System.Web.Mvc.Html" />
                <add namespace="System.Web.Routing" />
                <add namespace="System.Web.Optimization" />

                <add namespace="MvcSiteMapProvider.Web.Html" />
                <add namespace="MvcSiteMapProvider.Web.Html.Models" />

                <add namespace="DevTrends.MvcDonutCaching" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>

    <appSettings>
        <add key="webpages:Enabled" value="false" />
    </appSettings>

    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
            <remove name="BlockViewHandler" />
            <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
        </handlers>
    </system.webServer>
</configuration>
</code>```

答: I had a similar situation, and then realized that the razor view wasn't included in my project. As soon as I included it in the project (right click the view file and select Include in Project), Intellisense showed up.  </p>

Body:
Intellisense does not work in razor files:

In my web.conifg file (in the Views folder) is apparently correct:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

        </sectionGroup>
    </configSections>

    <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <namespaces>
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
                <add namespace="System.Web.Mvc.Html" />
                <add namespace="System.Web.Routing" />
                <add namespace="System.Web.Optimization" />

                <add namespace="MvcSiteMapProvider.Web.Html" />
                <add namespace="MvcSiteMapProvider.Web.Html.Models" />

                <add namespace="DevTrends.MvcDonutCaching" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>

    <appSettings>
        <add key="webpages:Enabled" value="false" />
    </appSettings>

    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
            <remove name="BlockViewHandler" />
            <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
        </handlers>
    </system.webServer>
</configuration>


问:
Package that deals with cgns format?
How to read cgns file contain mesh in python?

I found one package Pymesh but this package only deal with (read/write 2D and 3D mesh in .obj, .ply, .stl, .mesh).

Does anyone knows any package?

答: PyCGNS libraries for CGNS end-users and Python application developpers. Here is link - http://pycgns.sourceforge.net/</p>

Title: Package that deals with cgns format?


问:
RegEx to capture sub group that uses the same parent tags
I'm having a bit of trouble capturing multiple groups due to the fact that the groups use the same parent tags.

The block of data looks like this (I've split the lines for readability, the actual data has no line breaks)

```<code><w:p w:rsidR="100"><w:r><w:p w:rsidR="250"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>
<w:p w:rsidR="500"><w:r><w:p><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>
<w:p w:rsidR="150"><w:r><w:p w:rsidR="51"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>
<w:p><w:r><w:p w:rsidR="2"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>
<w:p w:hi="150"><w:r><w:p w:hi="5"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>
</code>```

The original regex dies due to the fact that the sub tag ends in the same root ending tag (due to the lazy lookahead - which is what we want because the blob of data is more than one):

```<code>/(<w:p .*?>|<w:p>)(.*?)<\/w:p>/
</code>```

So it never captures the the data beyond: "Text Group 2...".

Bracket usage will not work since the sub tag is also dynamic i.e. (<w:p .*?>|<w:p>)

Negative lookahead group should do the trick here, but I must have something mixed up?  This yields no valid result.

```<code>/(<w:p .*?>|<w:p>)(.*?(?!(<w:p .*?>|<w:p>).*?<\/w:p>))<\/w:p>/
</code>```

Using a non capturing group did get the lazy quantier to the end however it doesn't (obviously) capture the first portion:

```<code>(<w:p .*?>|<w:p>)((?:((<w:p .*?>|<w:p>).*?<\/w:p>)).*?)<\/w:p>
</code>```

The desired output is for the 2nd capturing group to contain all of the following:

```<code><w:r><w:p w:rsidR="250"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r>
</code>```

Note this is not the same as RegEx match open tags except XHTML self-contained tags, the tags are identified here and are a constant.

答:
I was able to solve this by using the branch reset group ?| which allowed me to combine the sub pattern + wildcard while using the lazy operator to find the tail.

Example:

```<code><w:p[^>]*>((?|(<w:p[^>]*>.*?<\/w:p>)|(.))*?)<\/w:p>
</code>```

Body:
I'm having a bit of trouble capturing multiple groups due to the fact that the groups use the same parent tags.

The block of data looks like this (I've split the lines for readability, the actual data has no line breaks)

<w:p w:rsidR="100"><w:r><w:p w:rsidR="250"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>
<w:p w:rsidR="500"><w:r><w:p><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>
<w:p w:rsidR="150"><w:r><w:p w:rsidR="51"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>
<w:p><w:r><w:p w:rsidR="2"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>
<w:p w:hi="150"><w:r><w:p w:hi="5"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r></w:p>

The original regex dies due to the fact that the sub tag ends in the same root ending tag (due to the lazy lookahead - which is what we want because the blob of data is more than one):

/(<w:p .*?>|<w:p>)(.*?)<\/w:p>/

So it never captures the the data beyond: "Text Group 2...".

Bracket usage will not work since the sub tag is also dynamic i.e. (<w:p .*?>|<w:p>)

Negative lookahead group should do the trick here, but I must have something mixed up?  This yields no valid result.

/(<w:p .*?>|<w:p>)(.*?(?!(<w:p .*?>|<w:p>).*?<\/w:p>))<\/w:p>/

Using a non capturing group did get the lazy quantier to the end however it doesn't (obviously) capture the first portion:

(<w:p .*?>|<w:p>)((?:((<w:p .*?>|<w:p>).*?<\/w:p>)).*?)<\/w:p>

The desired output is for the 2nd capturing group to contain all of the following:

<w:r><w:p w:rsidR="250"><w:r><w:t>Phrase 1</w:t></w:r></w:p></w:r><w:r><w:t>Phrase 2</w:t></w:r>

Note this is not the same as RegEx match open tags except XHTML self-contained tags, the tags are identified here and are a constant.

Body:
I was able to solve this by using the branch reset group ?| which allowed me to combine the sub pattern + wildcard while using the lazy operator to find the tail.

Example:

<w:p[^>]*>((?|(<w:p[^>]*>.*?<\/w:p>)|(.))*?)<\/w:p>