问:
Late Binding & Type Issues In VB
I'm trying to run my code which was originally created using Visual Studio through another application where late bindings are disallowed and this option cannot be altered unfortunately. I am very new to programming in general and struggling to get my head around the issue. Here is the code im using in the invoke code stage:

```<code>Dim objIEShell As Object = CreateObject("Shell.Application")
Dim objIEShellWindows As Object = objIEShell.Windows
Dim objIEWin As Object
For Each objIEWin In objIEShellWindows
    If InStr(objIEWin.LocationURL,"google")>0 Then
        objIEWin.Quit
        objIEWin = Nothing
    End If
Next
</code>```

The code simply closes all instances of Internet Explorer with "google" in the URL. This is the error message I get when trying to compile it:

```<code>Message: Error compiling code
error BC30574: Option Strict On disallows late binding. At line 2
error BC32023: Expression is of type 'Object', which is not a collection type. At line 4
</code>```

From the research I've done so far I realise the first error message on line 2 is to do with the type difference between objIEShell and the Windows method. I think I have to convert objIEShell like this, CType(objIEShell,?), but I don't know the type of the .Windows method or how to find this out. Also any insight on how the fix the second error would be greatly appreciated as I'm not sure where to start with that one either.

答:
This dates back to the wonky days when Microsoft still had plans to make Explorer behave like a web browser.  Makes it pretty hard to arrive at the correct code, it is a combination of two separate COM components that don't have much to do with each other.

You need to first add two references to those components so the compiler understands the names.  Use Project > Add Reference > COM tab and tick "Microsoft Internet Controls" and "Microsoft Shell Controls and Automation".  That adds the Shell32 and SHDocVw namespaces.

Now you can write the code early-bound like this:

```<code>    Dim objIEShell = New Shell32.Shell
    Dim objIEShellWindows = CType(objIEShell.Windows, SHDocVw.IShellWindows)
    Dim objIEWin As SHDocVw.WebBrowser
    For Each objIEWin In objIEShellWindows
        If InStr(objIEWin.LocationURL, "google") > 0 Then
            objIEWin.Quit()
        End If
    Next
</code>```

The CType() expression is probably the most unintuitive one, the Shell.Windows property is of type Object to break the dependency between those two components.  The cast is the necessary voodoo to keep the compiler happy.

Title: Late Binding & Type Issues In VB

Body:
I'm trying to run my code which was originally created using Visual Studio through another application where late bindings are disallowed and this option cannot be altered unfortunately. I am very new to programming in general and struggling to get my head around the issue. Here is the code im using in the invoke code stage:

Dim objIEShell As Object = CreateObject("Shell.Application")
Dim objIEShellWindows As Object = objIEShell.Windows
Dim objIEWin As Object
For Each objIEWin In objIEShellWindows
    If InStr(objIEWin.LocationURL,"google")>0 Then
        objIEWin.Quit
        objIEWin = Nothing
    End If
Next

The code simply closes all instances of Internet Explorer with "google" in the URL. This is the error message I get when trying to compile it:

Message: Error compiling code
error BC30574: Option Strict On disallows late binding. At line 2
error BC32023: Expression is of type 'Object', which is not a collection type. At line 4

From the research I've done so far I realise the first error message on line 2 is to do with the type difference between objIEShell and the Windows method. I think I have to convert objIEShell like this, CType(objIEShell,?), but I don't know the type of the .Windows method or how to find this out. Also any insight on how the fix the second error would be greatly appreciated as I'm not sure where to start with that one either.

Body:
This dates back to the wonky days when Microsoft still had plans to make Explorer behave like a web browser.  Makes it pretty hard to arrive at the correct code, it is a combination of two separate COM components that don't have much to do with each other.

You need to first add two references to those components so the compiler understands the names.  Use Project > Add Reference > COM tab and tick "Microsoft Internet Controls" and "Microsoft Shell Controls and Automation".  That adds the Shell32 and SHDocVw namespaces.

Now you can write the code early-bound like this:

    Dim objIEShell = New Shell32.Shell
    Dim objIEShellWindows = CType(objIEShell.Windows, SHDocVw.IShellWindows)
    Dim objIEWin As SHDocVw.WebBrowser
    For Each objIEWin In objIEShellWindows
        If InStr(objIEWin.LocationURL, "google") > 0 Then
            objIEWin.Quit()
        End If
    Next

The CType() expression is probably the most unintuitive one, the Shell.Windows property is of type Object to break the dependency between those two components.  The cast is the necessary voodoo to keep the compiler happy.


来源: stackexchange

问:
NSAttributedString, change the font overall BUT keep all other attributes?
Say I have an NSMutableAttributedString .

The string has a varied mix of formatting throughout:

Here is an example:

This string is hell to change in iOS, it really sucks.

However, the font per se is not the font you want.

I want to:

for each and every character, change that character to a specific font (say, Avenir)

BUT,

for each and every character, keep the mix of other attributions (bold, italic, colors, etc etc) which was previously in place on that character.

How the hell do you do this?

Note:

if you trivially add an attribute "Avenir" over the whole range: it simply deletes all the other attribute ranges, you lose all formatting. Unfortunately, attributes are not, in fact "additive".

答:
Here is a much simpler implementation that keeps all attributes in place, including all font attributes except it allows you to change the font face.

Note that this only makes use of the font face (name) of the passed in font. The size is kept from the existing font. If you want to also change all of the existing font sizes to the new size, change f.pointSize to font.pointSize.

```<code>extension NSMutableAttributedString {
    func replaceFont(with font: UIFont) {
        beginEditing()
        self.enumerateAttribute(.font, in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
            if let f = value as? UIFont {
                let ufd = f.fontDescriptor.withFamily(font.familyName).withSymbolicTraits(f.fontDescriptor.symbolicTraits)!
                let newFont = UIFont(descriptor: ufd, size: f.pointSize)
                removeAttribute(.font, range: range)
                addAttribute(.font, value: newFont, range: range)
            }
        }
        endEditing()
    }
}
</code>```

And to use it:

```<code>let someMutableAttributedString = ... // some attributed string with some font face you want to change
someMutableAttributedString.replaceFont(with: UIFont.systemFont(ofSize: 12))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is a much simpler implementation that keeps all attributes in place, including all font attributes except it allows you to change the font face.

Note that this only makes use of the font face (name) of the passed in font. The size is kept from the existing font. If you want to also change all of the existing font sizes to the new size, change f.pointSize to font.pointSize.

extension NSMutableAttributedString {
    func replaceFont(with font: UIFont) {
        beginEditing()
        self.enumerateAttribute(.font, in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
            if let f = value as? UIFont {
                let ufd = f.fontDescriptor.withFamily(font.familyName).withSymbolicTraits(f.fontDescriptor.symbolicTraits)!
                let newFont = UIFont(descriptor: ufd, size: f.pointSize)
                removeAttribute(.font, range: range)
                addAttribute(.font, value: newFont, range: range)
            }
        }
        endEditing()
    }
}

And to use it:

let someMutableAttributedString = ... // some attributed string with some font face you want to change
someMutableAttributedString.replaceFont(with: UIFont.systemFont(ofSize: 12))

ContentLicense: CC BY-SA 3.0


问:
Xamarin forms Oauth2 Wunderlist API
I'm trying to make an app (for school) using Wunderlist. However, I have no clue how to authenticate users for the API. So I want to make a Xamarin.forms project, and there a login screen will appear, in the screen users can enter their username and password to authenticate, or if that is not possible, when the app loads, they redirect to the login page of wunderlist to authenticate and then return authenticated to the app to be able to use the app. Or if that isn't possible, I want to hard-code an authentication in it.

The problem is, I have no idea how I should implement this, I have no clue how Oauth2 works and how to use it in Xamarin. Could someone please help me?

答:
Rule of the thumb, don't create your own. This is what I used in one of our projects. A YouTube tutorial of a Microsoft MVP. https://www.youtube.com/watch?v=Mg4qvVBXfrI

Hope this helps.

Title: Xamarin forms Oauth2 Wunderlist API


问:
How do I make ordered list using javascript?
Lets say I have this

```<code><ol>
  <li>V1 One</li>
  <li>V1 Two</li>
  <li>V1 Three</li>
  <li>V1 Four</li>
</ol>`
</code>```

I want to make an ordered list using .js instead of using LI tags.
I was thinking the js. code could replace first V1 and call it 1. , replace second V1 and call it two and so on, in other words counting how many V1s there are and replacing them with ordered list.

Or maybe something like this

```<code><ol>
  <li>i++ V1 One</li>
  <li>i++ V1 Two</li>
  <li>i++ V1 Three</li>
  <li>i++ V1 Four</li>
</ol>
</code>```

Where i++ will be increased every time starting from 1

Yes, I know LI provide ordered list!

答:
You can have an empty div, and use javascript to enter the innerHTML inside the div

```<code>function listdown(){
  var startlist = "<ol>";
  var endlist = "</ol>";
  *use a for loop to enter the <LI>, this way, you can do much more with each item*
  document.getElementById("emptydiv").innerHTML = startlist + LI list + endlist;
}
</code>```

EDIT

Nonetheless, JQuery is still the best option

ContentLicense: CC BY-SA 2.5

Body:
Lets say I have this

V1 One

V1 Two

V1 Three

V1 Four

`

I want to make an ordered list using .js instead of using LI tags.
I was thinking the js. code could replace first V1 and call it 1. , replace second V1 and call it two and so on, in other words counting how many V1s there are and replacing them with ordered list.

Or maybe something like this

i++ V1 One

i++ V1 Two

i++ V1 Three

i++ V1 Four

Where i++ will be increased every time starting from 1

Yes, I know LI provide ordered list!

Body:
You can have an empty div, and use javascript to enter the innerHTML inside the div

function listdown(){
  var startlist = "<ol>";
  var endlist = "</ol>";
  *use a for loop to enter the <LI>, this way, you can do much more with each item*
  document.getElementById("emptydiv").innerHTML = startlist + LI list + endlist;
}

EDIT

Nonetheless, JQuery is still the best option


问:
Unable to access WebAPI using Controller and Action name using MVC5
I have an WebAPI,

```<code> public class SystemHealtController : ApiController
    {
        [HttpGet]
        public IHttpActionResult UpdateUsageDetail(string cpuUsage, string memoryUsage, string diskUsage)
        {

              // Do Stuff

            return Ok();
        }
</code>```

RouteConfig also have default settings,

```<code> public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Job", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
</code>```

But when I navigate to API URL, http://localhost:64384/API/SystemHealt/UpdateUsageDetail?cpuUsage=2&memoryUsage=4&diskUsage=76 , get following error:

HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

The only thing I suspect is, before creating Controller, I Installed

```<code>Microsoft.AspNet.WebApi
</code>```

and then uninstalled as well suspecting that could be the issue. But after uninstall also there were no errors.

答:
By default, the web api routing is registered in the WebApiConfig class with
the route pattern api/{controller}/{id}

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

You can see that there is no action method name. the methods are accessed by the verb (POST or GET, the type of call you are making). So typically you will create  GET methods (to read data) and a POST method to post data to (for creating /updating data). When you want to use these endpoints, you will use the same url, but the Http method will be different (GET and POST)

So you should be accessing it like

```<code>yourSiteBaseUrl/api/SystemHealt?cpuUsage=2&memoryUsage=4&diskUsage=76
</code>```

This should work, assuming you have Web api enabled in the app. If you are manually adding the web api functionality to an existing mvc project, Follow the steps mentioned in this post to do so.

By default, the route registration in RouteConfig is used for MVC controllers.

Body:
I have an WebAPI,

 public class SystemHealtController : ApiController
    {
        [HttpGet]
        public IHttpActionResult UpdateUsageDetail(string cpuUsage, string memoryUsage, string diskUsage)
        {

              // Do Stuff

            return Ok();
        }

RouteConfig also have default settings,

 public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Job", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

But when I navigate to API URL, http://localhost:64384/API/SystemHealt/UpdateUsageDetail?cpuUsage=2&memoryUsage=4&diskUsage=76 , get following error:

HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

The only thing I suspect is, before creating Controller, I Installed

Microsoft.AspNet.WebApi

and then uninstalled as well suspecting that could be the issue. But after uninstall also there were no errors.

Body:
By default, the web api routing is registered in the WebApiConfig class with
the route pattern api/{controller}/{id}

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

You can see that there is no action method name. the methods are accessed by the verb (POST or GET, the type of call you are making). So typically you will create  GET methods (to read data) and a POST method to post data to (for creating /updating data). When you want to use these endpoints, you will use the same url, but the Http method will be different (GET and POST)

So you should be accessing it like

yourSiteBaseUrl/api/SystemHealt?cpuUsage=2&memoryUsage=4&diskUsage=76

This should work, assuming you have Web api enabled in the app. If you are manually adding the web api functionality to an existing mvc project, Follow the steps mentioned in this post to do so.

By default, the route registration in RouteConfig is used for MVC controllers.


问:
Create Empty Form In Jdeveloper 12c
I am using J Developer 12 c. I want to create form but without any data fetched in.I want user to enter detail in form for submission.I have tried all online solution but they are for J Developer 11.I am not able to fetch an empty form.

When I run my form it automatically fetch record from the table.I have tried use create insert but i want form to be automatically fetched with new record every time page is run.

答:
Add a CreateInsert action in your task flow on the way into you page. This will clear the fields for data entry. Look here.

You need to understand the difference between commit and submit. You want to submit the pages - clicking a submit button - and then the page is processed and the EO/VOs are updated in memory.

The Commit operation writes the in-memory changes to the datasource (database). So, you can submit pages 1-3 then using the same data control the fields will be populated with the entered data on page 4. Now the user can commit the changes. The Commit action is located in the operations for the AppModule-DataControl.

This is the power of the ADF Data Control. Changes to fields are cached in memory and are available to any page and then those changes can be committed when you choose. Note, the Task Flow can control the transaction itself.

Sounds like you need to learn the basics of ADF. I suggest this book and this set of resources I maintain for my students and these.

And, if you will be doing a lot of ADF development, it is well worth your time to take our ADF course.

(It also seems you are unaware of how stack overflow works. When you get an response that answers you question, you up-vote the answer, so it encourages those of us taking our time to answer you question for free to continue doing so. Please note that I answered your original question and Shay reinforced that answer.
And I have now answered your second question, and provided links to resources to help you go further.

Title: Create Empty Form In Jdeveloper 12c


问:
How to get a value of __LINE__ of another function (before calling that function)?
For the currently existing test framework I need to pass (during the first-most call) to the function a line number of a fragment inside of that function. Something like this:

```<code>#include <stdio.h>
void func(int line_num)
{
#define LINE_NUM  (__LINE__ + 1)
  if(line_num == __LINE__) // Check the passed arg against the current line.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(LINE_NUM); // Pass to the func the line number inside of that func.
  return 0;
}
</code>```

(this is a minimalistic version of a more complex functionality).

As is the sample code prints "FAIL".

If I pass an absolute value 5, e.g. func(5) then it prints "OK". I don't like the absolute value 5 because if I add one more line in front of the func definition then the absolute value will need a correction.

Instead of #define LINE_NUM  (__LINE__ + 1) I also tried the following:

1.

```<code>#define VALUE_OF(x) x
#define LINE_NUM    (VALUE_OF(__LINE__) + 1)
</code>```

2.

```<code>#define VAL(a,x)    a##x
#define LOG_LINE()    ( VAL( /*Nothing*/,__LINE__) + 1)
</code>```

3.

```<code>#define VALUE_OF2(x) x
#define VALUE_OF(x)     VALUE_OF2(x)
#define LINE_NUM  (VALUE_OF(__LINE__) + 1)
</code>```

I'm using:

```<code>gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
</code>```

In my sample code the value that func() gets is 14 (the call site line number + 1).

答:
You cannot get the preprocessor to expand __LINE__ in a macro definition. That's not the way the preprocessor works.

But you can create global constants.

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

static const int func_line_num = __LINE__ + 3;
void func(int line_num)
{
  if(line_num == __LINE__) // Check the passed arg against the current line.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(func_line_num); // Pass to the func the line number inside of that func.
  return 0;
}
</code>```

If you don't like static const int, for whatever reason, you could use an enum:

```<code>enum { FUNC_LINE_NUM = __LINE__ + 3 };
</code>```

Unfortunately, whether you use a global constant or an enum, you have to put the definition at file scope, which might make it somewhat distant from the use point. However, it is not immediately apparent why the precise line number of the test needs to be used, rather than (for example) the first line of the function or even any integer guaranteed to be unique:

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

// As long as all uses of __LINE__ are on different lines, the
// resulting values will be different, at least within this file.
enum { FUNC_LINE_NUM = __LINE__ };

void func(int line_num)
{
  if(line_num == FILE_LINE_NUM) // Check the passed arg against the appropriate constant.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(func_line_num); // Pass to the func the line number inside of that func.
  return 0;
}
</code>```

Body:
For the currently existing test framework I need to pass (during the first-most call) to the function a line number of a fragment inside of that function. Something like this:

#include <stdio.h>
void func(int line_num)
{
#define LINE_NUM  (__LINE__ + 1)
  if(line_num == __LINE__) // Check the passed arg against the current line.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(LINE_NUM); // Pass to the func the line number inside of that func.
  return 0;
}

(this is a minimalistic version of a more complex functionality).

As is the sample code prints "FAIL".

If I pass an absolute value 5, e.g. func(5) then it prints "OK". I don't like the absolute value 5 because if I add one more line in front of the func definition then the absolute value will need a correction.

Instead of #define LINE_NUM  (__LINE__ + 1) I also tried the following:

1.

#define VALUE_OF(x) x
#define LINE_NUM    (VALUE_OF(__LINE__) + 1)

2.

#define VAL(a,x)    a##x
#define LOG_LINE()    ( VAL( /*Nothing*/,__LINE__) + 1)

3.

#define VALUE_OF2(x) x
#define VALUE_OF(x)     VALUE_OF2(x)
#define LINE_NUM  (VALUE_OF(__LINE__) + 1)

I'm using:

gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

In my sample code the value that func() gets is 14 (the call site line number + 1).

Body:
You cannot get the preprocessor to expand __LINE__ in a macro definition. That's not the way the preprocessor works.

But you can create global constants.

#include <stdio.h>

static const int func_line_num = __LINE__ + 3;
void func(int line_num)
{
  if(line_num == __LINE__) // Check the passed arg against the current line.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(func_line_num); // Pass to the func the line number inside of that func.
  return 0;
}

If you don't like static const int, for whatever reason, you could use an enum:

enum { FUNC_LINE_NUM = __LINE__ + 3 };

Unfortunately, whether you use a global constant or an enum, you have to put the definition at file scope, which might make it somewhat distant from the use point. However, it is not immediately apparent why the precise line number of the test needs to be used, rather than (for example) the first line of the function or even any integer guaranteed to be unique:

#include <stdio.h>

// As long as all uses of __LINE__ are on different lines, the
// resulting values will be different, at least within this file.
enum { FUNC_LINE_NUM = __LINE__ };

void func(int line_num)
{
  if(line_num == FILE_LINE_NUM) // Check the passed arg against the appropriate constant.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(func_line_num); // Pass to the func the line number inside of that func.
  return 0;
}


问:
Include previous element on wrapAll()
I'm trying to target h3 and include it on my wrap all.
This is my current code to target it.

$('.perk:first-child').prev().addClass("perk").text("success");

Here is my code:

jQuery(document).ready(function($) {
  $('.perk:first-child').prev().addClass("perk").text("success");
  $(".perk").wrapAll("
");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.new {
  background-color: pink;
  width: 50%;
  float: right;
}

.selected {
  background-color: red;
  width: 50%;
}</code>```

Perk Rule

Test1

Test2

Test3

Selected Perks
```

答:
$(".perk:first-child") isn't selecting the first .perk DIV. Since
 is before it, it can't be the first child of whatever element contains them both. This selector means element that has class perk and is also the first child, it doesn't mean the first child with class perk.

If you want to select the
 that precedes the first .perk, just select all .perk and then use .prev('h3').

jQuery(document).ready(function($) {
  $('.perk').prev('h3').addClass("perk").text("success");
  $(".perk").wrapAll("
");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.new {
  background-color: pink;
  width: 50%;
  float: right;
}

.selected {
  background-color: red;
  width: 50%;
}</code>```

Perk Rule

Test1

Test2

Test3

Selected Perks
```

Title: Include previous element on wrapAll()

Body:
I'm trying to target h3 and include it on my wrap all.
This is my current code to target it.

$('.perk:first-child').prev().addClass("perk").text("success");

Here is my code:

jQuery(document).ready(function($) {
  $('.perk:first-child').prev().addClass("perk").text("success");
  $(".perk").wrapAll("
");
});

.new {
  background-color: pink;
  width: 50%;
  float: right;
}

.selected {
  background-color: red;
  width: 50%;
}

Perk Rule

Test1

Test2

Test3

Selected Perks

Body:
$(".perk:first-child") isn't selecting the first .perk DIV. Since <h3> is before it, it can't be the first child of whatever element contains them both. This selector means element that has class perk and is also the first child, it doesn't mean the first child with class perk.

If you want to select the <h3> that precedes the first .perk, just select all .perk and then use .prev('h3').

jQuery(document).ready(function($) {
  $('.perk').prev('h3').addClass("perk").text("success");
  $(".perk").wrapAll("<div class='new' />");
});

.new {
  background-color: pink;
  width: 50%;
  float: right;
}

.selected {
  background-color: red;
  width: 50%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Perk Rule</h3>
<div class="perk">Test1</div>
<div class="perk">Test2</div>
<div class="perk">Test3</div>
<div class="selected">Selected Perks</div>


问:
iPhone not connected. Xcode will continue when iPhone is connected
I have my iPhone connected to Xcode. It used to work just fine recently. I see it in the Devices and Simulators section, but when I try to compile my app, it says:

D's iPhone 6S is not connected. Xcode will continue when D's iPhone 6S is connected.

In the Devices and Simulators I see it as disconnected.

I tried restarting the phone, turning it's wifi on and off. It's connected to the same wifi network, I tried restarting Xcode, nothing. I run Xcode 9, Beta 6 at the moment. Does anyone has similar issue and hopefully know how to solve it?

答:
I'm using Xcode 9.1 and suddenly had this issue.After reading other answers a realized it is a Xcode bug via wifi debug.My solution was to connect the iphone with a USB, then go to the Add Additional Simulators,then come to the interface below,uncheck "connect via network".
Problem sovled,and back to debug via a USB.


问:
Round float in Python
I have a problem with float in Python...

I have this in a variable:

```<code>i = 9.600000000000001
</code>```

And I would transform in this:

```<code>i = 9.60000
</code>```

with five numbers after the decimal point and rounded.

答:
You can use the second parameter in the round() function.

```<code>i = 9.600000000000001
i = round(i, 5)
print("%.5f" % i)
</code>```

will return 9.60000.

Title: Round float in Python

Body:
I have a problem with float in Python...

I have this in a variable:

i = 9.600000000000001

And I would transform in this:

i = 9.60000

with five numbers after the decimal point and rounded.

Body:
You can use the second parameter in the round() function.

i = 9.600000000000001
i = round(i, 5)
print("%.5f" % i)

will return 9.60000.


问:
error: 'listOfColors' was not declared in this scope
I'm new to C++ and I don't understand why I'm getting a not declared error on this:

```<code>int main(){
    string listOfColors[5] = {"red","blue","green","yellow","magenta"};
    for(int i = 0;i < sizeof listofColors;i++){
        cout << listofColors[i] << "\n";
    }
    return 0;
}
</code>```

This is my first utilization of an array so far, so I may just not be declaring it correctly. I also had the array declaration before the main function beforehand.

答: You declared your variable as listOfColors (capital "O"), and then you use it as listofColors in your for loop. All you need to do is to capitalize the "O" when using your variable.

Body:
I'm new to C++ and I don't understand why I'm getting a not declared error on this:

int main(){
    string listOfColors[5] = {"red","blue","green","yellow","magenta"};
    for(int i = 0;i < sizeof listofColors;i++){
        cout << listofColors[i] << "\n";
    }
    return 0;
}

This is my first utilization of an array so far, so I may just not be declaring it correctly. I also had the array declaration before the main function beforehand.


问:
Make a grid column span the entire row
Imagine we have two CSS grid containers with a dynamic columns count based on width:

```<code>display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
</code>```

The grid works perfectly, but what if we need to have another grid to have the first column to be same as in another grid with the code shown above, but it's another column to span through more cells - depending on how many cells are in the current row?

To better understand the issue, there are images:

On a narrower wrapper:

We would need to apply something like grid-column: span ALL (if something like that exists), with meaning that ALL = till the end of the current row.

It is really important that "First" column should always align with the "1" column.

The code to run the example is here:

.grid div {
  /* Not important fancy styles */
  height: 40px;
  text-align: center;
  padding-top: 20px;
}

.grid {
  width: 350px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  background-color: silver;
}

.grid-second {
  background-color: red;
}

.grid-another {
  background-color: purple;
  border: 1px solid gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="grid-first">
    First
  </div>
  <div class="grid-second">
    Second (Want till end)
  </div>
</div>
<!-- Another same grid -->
<div class="grid">
  <div class="grid-another">
    1
  </div>
  <div class="grid-another">
    2
  </div>
  <div class="grid-another">
    3
  </div>
  <div class="grid-another">
    4
  </div>
</div></code>```

PS: Please do not post solutions using a media query. I am interested in any (even a little hacky) solution, which will work without usage of media queries.

答:
Here are two interesting sections in the CSS Grid specification:

7.1. The Explicit Grid

Numeric indexes in the grid-placement properties count from the edges
  of the explicit grid. Positive indexes count from the start side,
  while negative indexes count from the end side.

also here...

8.3. Line-based Placement: the grid-row-start, grid-column-start,  grid-row-end, and grid-column-end properties

If a negative integer is given, it instead counts in reverse, starting
  from the end edge of the explicit grid.

In other words, when dealing with an explicit grid, which means a grid defined by these properties:

grid-template-rows

grid-template-columns

grid-template-areas

grid (which is the shorthand for the three properties above, among others)

... you can make a grid area span all columns by setting this rule:

```<code>grid-column: 1 / -1;
</code>```

That tells the grid area to span from the first column line to the last column line, which I believe meets your stated objective:

"We would need to apply something like grid-column: span ALL (if something like that exists), with meaning that ALL = till the end of current row."

jsFiddle demo

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  background-color: silver;
}

.grid-second {
  grid-column: 2 / -1;
  background-color: red;
}

/* Not important fancy styles */

.grid div {
  height: 40px;
  text-align: center;
  padding-top: 20px;
}

.grid-another {
  background-color: purple;
  border: 1px solid gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="grid-first">First</div>
  <div class="grid-second">Second (Want till end)</div>
</div>
<!-- Another same grid -->
<div class="grid">
  <div class="grid-another">1</div>
  <div class="grid-another">2</div>
  <div class="grid-another">3</div>
  <div class="grid-another">4</div>
  <div class="grid-another">1</div>
  <div class="grid-another">2</div>
  <div class="grid-another">3</div>
  <div class="grid-another">4</div>
  <div class="grid-another">1</div>
  <div class="grid-another">2</div>
  <div class="grid-another">3</div>
  <div class="grid-another">4</div>
</div></code>```

Title: Make a grid column span the entire row

Body:
Imagine we have two CSS grid containers with a dynamic columns count based on width:

display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));

The grid works perfectly, but what if we need to have another grid to have the first column to be same as in another grid with the code shown above, but it's another column to span through more cells - depending on how many cells are in the current row?

To better understand the issue, there are images:

On a narrower wrapper:

We would need to apply something like grid-column: span ALL (if something like that exists), with meaning that ALL = till the end of the current row.

It is really important that "First" column should always align with the "1" column.

The code to run the example is here:

.grid div {
  /* Not important fancy styles */
  height: 40px;
  text-align: center;
  padding-top: 20px;
}

.grid {
  width: 350px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  background-color: silver;
}

.grid-second {
  background-color: red;
}

.grid-another {
  background-color: purple;
  border: 1px solid gray;
}

    First

    Second (Want till end)

    1

    2

    3

    4

PS: Please do not post solutions using a media query. I am interested in any (even a little hacky) solution, which will work without usage of media queries.

Body:
Here are two interesting sections in the CSS Grid specification:

7.1. The Explicit Grid

Numeric indexes in the grid-placement properties count from the edges
  of the explicit grid. Positive indexes count from the start side,
  while negative indexes count from the end side.

also here...

8.3. Line-based Placement: the grid-row-start, grid-column-start,  grid-row-end, and grid-column-end properties

If a negative integer is given, it instead counts in reverse, starting
  from the end edge of the explicit grid.

In other words, when dealing with an explicit grid, which means a grid defined by these properties:

grid-template-rows

grid-template-columns

grid-template-areas

grid (which is the shorthand for the three properties above, among others)

... you can make a grid area span all columns by setting this rule:

grid-column: 1 / -1;

That tells the grid area to span from the first column line to the last column line, which I believe meets your stated objective:

"We would need to apply something like grid-column: span ALL (if something like that exists), with meaning that ALL = till the end of current row."

jsFiddle demo

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  background-color: silver;
}

.grid-second {
  grid-column: 2 / -1;
  background-color: red;
}

/* Not important fancy styles */

.grid div {
  height: 40px;
  text-align: center;
  padding-top: 20px;
}

.grid-another {
  background-color: purple;
  border: 1px solid gray;
}

<div class="grid">
  <div class="grid-first">First</div>
  <div class="grid-second">Second (Want till end)</div>
</div>
<!-- Another same grid -->
<div class="grid">
  <div class="grid-another">1</div>
  <div class="grid-another">2</div>
  <div class="grid-another">3</div>
  <div class="grid-another">4</div>
  <div class="grid-another">1</div>
  <div class="grid-another">2</div>
  <div class="grid-another">3</div>
  <div class="grid-another">4</div>
  <div class="grid-another">1</div>
  <div class="grid-another">2</div>
  <div class="grid-another">3</div>
  <div class="grid-another">4</div>
</div>


问:
Ionic build android, Error: spawn EACCES
If I follow this steps to create a new app:

```<code>Rubens-MacBook-Pro:~ rlopez$ npm install -g cordova ionic
Rubens-MacBook-Pro:~ rlopez$ ionic start myApp tabs
Rubens-MacBook-Pro:~ rlopez$ cd myApp
Rubens-MacBook-Pro:myApp rlopez$  ionic platform add android@6.2.2 //6.1.x has a bug
Rubens-MacBook-Pro:myApp rlopez$  ionic build android
</code>```

I get this output:

```<code>> ionic-hello-world@ ionic:build /Users/rlopez/Proyectos/sfp-concursaPy
> ionic-app-scripts build

[15:13:28]  ionic-app-scripts 1.1.4
[15:13:28]  build dev started ...
[15:13:28]  clean started ...
[15:13:28]  clean finished in 3 ms
[15:13:28]  copy started ...
[15:13:28]  transpile started ...
[15:13:31]  transpile finished in 2.96 s
[15:13:31]  preprocess started ...
[15:13:31]  preprocess finished in less than 1 ms
[15:13:31]  webpack started ...
[15:13:31]  copy finished in 3.17 s
[15:13:41]  webpack finished in 9.26 s
[15:13:41]  sass started ...
[15:13:41]  sass finished in 897 ms
[15:13:41]  postprocess started ...
[15:13:41]  postprocess finished in 1 ms
[15:13:41]  lint started ...
[15:13:41]  build dev finished in 13.15 s
[15:13:43]  lint finished in 2.04 s
ANDROID_HOME=/Users/rlopez/Library/Android/sdk

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home

Error: spawn EACCES
</code>```

Running ionic info gives the following:

```<code>Your system information:

Cordova CLI: 6.5.0
Ionic Framework Version: 3.1.1
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
Ionic App Scripts Version: 1.3.6
ios-deploy version: 1.8.5
ios-sim version: 5.0.13
OS: OS X El Capitan
Node Version: v6.10.1
Xcode version: Xcode 7.3.1 Build version 7D1014
</code>```

What am I doign wrong? Is this a bug in Ionic?

[Edit]

Running ionic build android --verbose gives the following output:

```<code>Running command: "/Applications/Android Studio 2.4
Preview.app/Contents/gradle/gradle-3.4.1/bin/gradle" -p
/Users/rlopez/myApp/platforms/android wrapper -b
/Users/rlopez/myApp/platforms/android/wrapper.gradle

Error: spawn EACCES
    at exports._errnoException (util.js:1018:11)
    at ChildProcess.spawn (internal/child_process.js:319:11)
    at Object.exports.spawn (child_process.js:378:9)
    at exports.spawn(/Users/rlopez/myApp/platforms/android/cordova/node_modules/cordova-common/src/superspawn.js:134:31)
    at GradleBuilder.runGradleWrapper(/Users/rlopez/myApp/platforms/android/cordova/lib/builders/GradleBuilder.js:78:14)
    at /Users/rlopez/myApp/platforms/android/cordova/lib/builders/GradleBuilder.js:178:21
    at _fulfilled (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:854:54)
    at self.promiseDispatch.done (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:883:30)
    at Promise.promise.promiseDispatch (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:816:13)
    at /Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:570:49
</code>```

答:
For those who gets similar error after updating Android Studio to version 3.x, you can run the following command to fix it:

sudo chmod 755 /Applications/Android\ Studio.app/Contents/gradle/gradle-4.1/bin/gradle

Hopefully it helps!

Body:
If I follow this steps to create a new app:

Rubens-MacBook-Pro:~ rlopez$ npm install -g cordova ionic
Rubens-MacBook-Pro:~ rlopez$ ionic start myApp tabs
Rubens-MacBook-Pro:~ rlopez$ cd myApp
Rubens-MacBook-Pro:myApp rlopez$  ionic platform add android@6.2.2 //6.1.x has a bug
Rubens-MacBook-Pro:myApp rlopez$  ionic build android

I get this output:

> ionic-hello-world@ ionic:build /Users/rlopez/Proyectos/sfp-concursaPy
> ionic-app-scripts build

[15:13:28]  ionic-app-scripts 1.1.4
[15:13:28]  build dev started ...
[15:13:28]  clean started ...
[15:13:28]  clean finished in 3 ms
[15:13:28]  copy started ...
[15:13:28]  transpile started ...
[15:13:31]  transpile finished in 2.96 s
[15:13:31]  preprocess started ...
[15:13:31]  preprocess finished in less than 1 ms
[15:13:31]  webpack started ...
[15:13:31]  copy finished in 3.17 s
[15:13:41]  webpack finished in 9.26 s
[15:13:41]  sass started ...
[15:13:41]  sass finished in 897 ms
[15:13:41]  postprocess started ...
[15:13:41]  postprocess finished in 1 ms
[15:13:41]  lint started ...
[15:13:41]  build dev finished in 13.15 s
[15:13:43]  lint finished in 2.04 s
ANDROID_HOME=/Users/rlopez/Library/Android/sdk

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home

Error: spawn EACCES

Running ionic info gives the following:

Your system information:

Cordova CLI: 6.5.0
Ionic Framework Version: 3.1.1
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
Ionic App Scripts Version: 1.3.6
ios-deploy version: 1.8.5
ios-sim version: 5.0.13
OS: OS X El Capitan
Node Version: v6.10.1
Xcode version: Xcode 7.3.1 Build version 7D1014

What am I doign wrong? Is this a bug in Ionic?

[Edit]

Running ionic build android --verbose gives the following output:

Running command: "/Applications/Android Studio 2.4
Preview.app/Contents/gradle/gradle-3.4.1/bin/gradle" -p
/Users/rlopez/myApp/platforms/android wrapper -b
/Users/rlopez/myApp/platforms/android/wrapper.gradle

Error: spawn EACCES
    at exports._errnoException (util.js:1018:11)
    at ChildProcess.spawn (internal/child_process.js:319:11)
    at Object.exports.spawn (child_process.js:378:9)
    at exports.spawn(/Users/rlopez/myApp/platforms/android/cordova/node_modules/cordova-common/src/superspawn.js:134:31)
    at GradleBuilder.runGradleWrapper(/Users/rlopez/myApp/platforms/android/cordova/lib/builders/GradleBuilder.js:78:14)
    at /Users/rlopez/myApp/platforms/android/cordova/lib/builders/GradleBuilder.js:178:21
    at _fulfilled (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:854:54)
    at self.promiseDispatch.done (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:883:30)
    at Promise.promise.promiseDispatch (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:816:13)
    at /Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:570:49


问:
Swift - Forming an array from a JSON Response
I am new to the world of JSON. I just got started with JSON in Swift.

Right now, I have the following function:

```<code>func forShow() {
    // Using ACORN API to fetch the course codes

    guard let url[enter image description here][1]Online = URL(string: "https://timetable.iit.artsci.utoronto.ca/api/20179/courses?code=CSC") else { return }
    let session = URLSession.shared
    session.dataTask(with: urlOnline) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            print(data)
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                print(json)
            } catch {
                print(error)
            }
        }
        }.resume()
}
</code>```

I get a response with all courses having 'CSC' in their code String. I want to form an array with all complete course codes based on the response. I will paste response for one course here:

So, I want to access all the course codes seen in the image. It's "CSC104H1-F-20179" I want to to be able to access.

答:
Treat your JSON like a dictionary. You have all the course names at the top level, so fortunately you don't have to dig deep in the hierarchy.

So, where you have:

let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
print(json)

Change to:

if let arrayOfCourses = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String: Any]] {
    for (course, _) in arrayOfCourses {
        print(course)
    }
}

Body:
I am new to the world of JSON. I just got started with JSON in Swift.

Right now, I have the following function:

func forShow() {
    // Using ACORN API to fetch the course codes

    guard let url[enter image description here][1]Online = URL(string: "https://timetable.iit.artsci.utoronto.ca/api/20179/courses?code=CSC") else { return }
    let session = URLSession.shared
    session.dataTask(with: urlOnline) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            print(data)
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                print(json)
            } catch {
                print(error)
            }
        }
        }.resume()
}

I get a response with all courses having 'CSC' in their code String. I want to form an array with all complete course codes based on the response. I will paste response for one course here:

So, I want to access all the course codes seen in the image. It's "CSC104H1-F-20179" I want to to be able to access.


问:
summing list inside list by position in python
I have a list that looks like this and I would like to sum up the values at each position so as produce a list with only three values

```<code>print x
[[0, 0, -1], [0, 0, -1], [0, 0, 0], [1, 0, 0], [0, 0, 1]]
</code>```

For example, x[0][1] should be summed with the value in x[1][1], x[2][1], x[3][1], x[4][1]. Likewise x[0][2] should be summed with x[1][2], x[2][2], etc.

the output should look like this

```<code>print output
[1, 0, -1]
</code>```

答:
Using numpy:

```<code>np.sum(x, axis=0)
</code>```

Using native list:

```<code>[sum(y) for y in zip(*x)]
</code>```

Body:
I have a list that looks like this and I would like to sum up the values at each position so as produce a list with only three values

print x
[[0, 0, -1], [0, 0, -1], [0, 0, 0], [1, 0, 0], [0, 0, 1]]

For example, x[0][1] should be summed with the value in x[1][1], x[2][1], x[3][1], x[4][1]. Likewise x[0][2] should be summed with x[1][2], x[2][2], etc.

the output should look like this

print output
[1, 0, -1]

Body:
Using numpy:

np.sum(x, axis=0)

Using native list:

[sum(y) for y in zip(*x)]


问:
DevExpress vs infragistics Suites - looking to possibly switch
We are currently an Infragistics NetAdvantage Select customer and have been for a few years.  Their controls are ok but not what I would call great but the time invested in learning them to date is the main reason we stick with them. We use both ASP.NET and Winnform controls.

As we are due to renew, we are considering DevExpress as an option as they seem to offer much of the same functionality.

For anyone that has made this move fro mInfragistics to DevExpress, how have you found it?  A step forward or back? Pros and Cons to doing so?

答: This is probably too late, but as I found this post while asking the same question I thought I would add my comment with respect to Telerik. I have previously used Infragistics, which I found OK, but I thought the performance wasn't great.  Recently I worked a contract with a company who were using Telerik for Winforms and what we discovered was that there were a number of bugs in their controls.  There support was great and they were quick to respond to questions or comments, but unfortunately most of the time when we raised a question on why something wasn't working, the answer was that it was a bug in their control.  also their documentation states explicitly that their controls are not intended to be inherited, so while building your own custom control off the top of their control seems to work in most cases, it isn't recommended.</p>


问:
How to toggle a button to an active state using vanilla JS?
I have a list of 20 buttons on a page. When I click on a button I want it to switch to an "active" state. In this active state it will be a different color. I would like to do this using only vanilla javascript and css.

I have the following code to create the buttons:

```<code>var button;
createButtons();

function createButtons() {
  for (i = 0; i < 20; i++) {
    //creates a new button
    button = document.createElement('Button');

    //sets correct button number and button text
    var index = i + 1;
    var text = document.createTextNode('Button ' + index);
    button.appendChild(text);
    button.className += "button";
    button.className += " default-button";
    document.body.appendChild(button);
  }
}
</code>```

答:
CSS alternative without JavaScript:

input[type=checkbox] { display: none; }
input[type=checkbox] + label { background-color: cyan; }
input[type=checkbox]:checked + label { background-color: red; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=checkbox id=t1><label for=t1> Toggle 1 </label><br>
<input type=checkbox id=t2><label for=t2> Toggle 2 </label><br>
<input type=checkbox id=t3><label for=t3> Toggle 3 </label><br>
<input type=checkbox id=t4><label for=t4> Toggle 4 </label><br>
<input type=checkbox id=t5><label for=t5> Toggle 5 </label><br></code>```

Body:
I have a list of 20 buttons on a page. When I click on a button I want it to switch to an "active" state. In this active state it will be a different color. I would like to do this using only vanilla javascript and css.

I have the following code to create the buttons:

var button;
createButtons();

function createButtons() {
  for (i = 0; i < 20; i++) {
    //creates a new button
    button = document.createElement('Button');

    //sets correct button number and button text
    var index = i + 1;
    var text = document.createTextNode('Button ' + index);
    button.appendChild(text);
    button.className += "button";
    button.className += " default-button";
    document.body.appendChild(button);
  }
}

Body:
CSS alternative without JavaScript:

input[type=checkbox] { display: none; }
input[type=checkbox] + label { background-color: cyan; }
input[type=checkbox]:checked + label { background-color: red; }

<input type=checkbox id=t1><label for=t1> Toggle 1 </label><br>
<input type=checkbox id=t2><label for=t2> Toggle 2 </label><br>
<input type=checkbox id=t3><label for=t3> Toggle 3 </label><br>
<input type=checkbox id=t4><label for=t4> Toggle 4 </label><br>
<input type=checkbox id=t5><label for=t5> Toggle 5 </label><br>


问:
Possibility of adding libraries to android architecture
I got some doubts regarding the Android OS.

My question is, there are certain libraries and framework specified in the Android Architecture. So is there any possibility to add any other libraries based on my requirements? If yes, how do you do it?

答:
If Android SDK is used to develop applications, it is not possible to build libraries.

Although Android library projects can be created but they are compile time in nature. Meaning that libraries are packaged with the APK. If library project is used in multiple applications, each APK will have library classes packaged within it.

More about library projects.


问:
How to extract the class name out of List< Func< Int32 > >
How do I get the name out of the list?

e.g

```<code>static void Main()
{
    var methods = new List<Func<int>>();
    methods.Add(() => new ThisCss().useThis(0));

    // Output ThisCss here from methods
    // i.e Console.WriteLine(methods[0].ClassName).. or something like that

}

class ThisCss
{
    public int useThis(int num)
    {
       return 0;
    }
}
</code>```

So just to clarify I want to get the name of the class out of the 0 index of the list of functions. So in this case it would be 'ThisCss'.

答:
Func<...> is a delegate and all delegate instances derive from System.Delegate which has the Method property that returns a System.Reflection.MethodInfo which contains meta information about the actual CLR method being called including its containing type/class (there are no free-functions in the CLR, all functions are methods).

Try this:

```<code>foreach( Func<Int32> f in methods ) {
    MethodInfo mi = f.Method;
    String typeName = mi.DeclaringType.FullName;
    Console.WriteLine( typeName + "." + mi.Name );
}
</code>```

Note that if you reference an anonymous function or Lambda-function then the real DeclaringType will be a C#-compiler generated type with an unpredictable or unexpected name (which you can see using a CIL disassembly tool like Ildasm, ILSpy, or RedGate Reflector.

Body:
How do I get the name out of the list?

e.g

static void Main()
{
    var methods = new List<Func<int>>();
    methods.Add(() => new ThisCss().useThis(0));

    // Output ThisCss here from methods
    // i.e Console.WriteLine(methods[0].ClassName).. or something like that

}

class ThisCss
{
    public int useThis(int num)
    {
       return 0;
    }
}

So just to clarify I want to get the name of the class out of the 0 index of the list of functions. So in this case it would be 'ThisCss'.

Body:
Func<...> is a delegate and all delegate instances derive from System.Delegate which has the Method property that returns a System.Reflection.MethodInfo which contains meta information about the actual CLR method being called including its containing type/class (there are no free-functions in the CLR, all functions are methods).

Try this:

foreach( Func<Int32> f in methods ) {
    MethodInfo mi = f.Method;
    String typeName = mi.DeclaringType.FullName;
    Console.WriteLine( typeName + "." + mi.Name );
}

Note that if you reference an anonymous function or Lambda-function then the real DeclaringType will be a C#-compiler generated type with an unpredictable or unexpected name (which you can see using a CIL disassembly tool like Ildasm, ILSpy, or RedGate Reflector.


答:
I would use Julien's answer as it is more readable but to give you an alternative, you can use map and zip functions.</p>

```<code>list(map(sum, zip(*x)))
</code>```

Title: summing list inside list by position in python

Body:
I would use Julien's answer as it is more readable but to give you an alternative, you can use map and zip functions.

list(map(sum, zip(*x)))


问:
fitbitScraper does not log in
I used to be able to use the fitbitScraper package to access the intra-day setps count and heart rate data for our study. Recently though, the "login" function of the package has stopped working. I receive the following error message after my each attempt to log in:

```<code>login("myemail@gmail.com", "mypassword", rememberMe = TRUE)
</code>```

Error in login("myemail@gmail.com", "mypassword", rememberMe = TRUE) :
  login failed

I wonder if anyone has experienced this problem and knows a fix to it.

I have tried re-installing the package, even updating R to its latest version but none of them has helped.

答:
Fitbit recently updated their API and no longer allows for using web scraping methods. Best to use the direct Fitbit API and the personal app setting to access your own data.

More information can be found here.

Title: fitbitScraper does not log in

Body:
I used to be able to use the fitbitScraper package to access the intra-day setps count and heart rate data for our study. Recently though, the "login" function of the package has stopped working. I receive the following error message after my each attempt to log in:

login("myemail@gmail.com", "mypassword", rememberMe = TRUE)

Error in login("myemail@gmail.com", "mypassword", rememberMe = TRUE) :
  login failed

I wonder if anyone has experienced this problem and knows a fix to it.

I have tried re-installing the package, even updating R to its latest version but none of them has helped.


问:
20s of PAGEIOLATCH_SH on Azure SQL Database with execution plan of 0.06 subtree cost
(Azure support is giving vague answers, so I'm turning to Stack Overflow with hope! :))

Situation

User complains of timeout errors on a query. I run the same query twice (same parameters) from MSMS. First run takes looong (23s or sometimes 50s), second, third, etc. runs take <1s. Execution Plans are identical and have a subtree cost of 0.0671..

The difference I do notice is a WaitStats section in the first Execution Plan with the following values:

```<code>WaitCount: 2751
WaitTimeMS: 6
WaitType: MEMORY_ALLOCATION_EXT

WaitCount: 2751
WaitTimeMS: 6
WaitType: IO_QUEUE_LIMIT

WaitCount: 669
WaitTimeMS: 20360
WaitType: PAGEIOLATCH_SH
</code>```

Azure SQL DTU is averaging around 5% max.

Azure Support says it's probably the Execution Plan compilation time. I doubt that since clearing the Proc Cache does not reintroduce the long waits after the first run.

The execution plan "leafs" are Index Seek (NonClustedred), Key Lookup (Clustered) and RID Lookup (Heap). The RID Lookup being 39% (of the 0.0671). A single row is returned (i.e. TOP 1).

3 tables are in the query with CROSS APPLY. The biggest one has 8 million rows and contains a ~40KB VARBINARY column (not referenced nor returned anywhere in the query).

Query

```<code>DECLARE @p0 VARCHAR(50); SET @p0 = '<GUID1>'

SELECT TOP 1 p.Id, p.DateCreatedUtc, p.PreviousOwnerId
FROM (
    -- last project save
    SELECT ps.Id AS psId, p.*
    FROM Projects p
    CROSS APPLY (
      SELECT TOP 1 *
      FROM ProjectSaves
      WHERE ProjectId = p.Id
      ORDER BY LastModifiedUtc DESC
    ) AS ps
    WHERE p.OwnerId = @p0
) p
CROSS APPLY (
    SELECT TOP 1 *
    FROM ProjectSavePhotos
    WHERE ProjectSaveId = p.psId AND (name LIKE 'uploads%')
) ps
WHERE P.IsDeleted = 0 AND p.Id NOT IN ('<GUID2>')
ORDER BY p.DateCreatedUtc DESC
</code>```

p.OwnerId is indexed and Azure automatically created two more indexes:

on OwnerId and Id and

on IsDeleted, OwnerId and Id

ps.ProjectId is indexed and includes LastModifiedUtc

psp.ProjectSaveId is indexed and includes name

Question

How can I diagnose the root cause of the 20s PAGEIOLATCH_SH? Could it be the mere presence of the VARBINARY column? If so, how can I confirm that?

References read

https://www.sqlshack.com/handling-excessive-sql-server-pageiolatch_sh-wait-types/

https://sqlperformance.com/2014/06/io-subsystem/knee-jerk-waits-pageiolatch-sh

答:
What you are seeing is the effect of SQL Azure Database shrinking memory allocation after the database has not been used for some time or the database tier has been scaled. The behavior is exactly as you mention, the first execution or first few executions run with poor performance until memory allocation goes back to normal. You won't see that on a database continuously used.

That behavior on memory allocation creates those waits you are seeing during the first executions of the query, and you don't see that behavior with Microsoft SQL Server. For things like these I commonly say that Azure SQL Database and SQL Server are not the same, they are different in many ways.

Body:
(Azure support is giving vague answers, so I'm turning to Stack Overflow with hope! :))

Situation

User complains of timeout errors on a query. I run the same query twice (same parameters) from MSMS. First run takes looong (23s or sometimes 50s), second, third, etc. runs take <1s. Execution Plans are identical and have a subtree cost of 0.0671..

The difference I do notice is a WaitStats section in the first Execution Plan with the following values:

WaitCount: 2751
WaitTimeMS: 6
WaitType: MEMORY_ALLOCATION_EXT

WaitCount: 2751
WaitTimeMS: 6
WaitType: IO_QUEUE_LIMIT

WaitCount: 669
WaitTimeMS: 20360
WaitType: PAGEIOLATCH_SH

Azure SQL DTU is averaging around 5% max.

Azure Support says it's probably the Execution Plan compilation time. I doubt that since clearing the Proc Cache does not reintroduce the long waits after the first run.

The execution plan "leafs" are Index Seek (NonClustedred), Key Lookup (Clustered) and RID Lookup (Heap). The RID Lookup being 39% (of the 0.0671). A single row is returned (i.e. TOP 1).

3 tables are in the query with CROSS APPLY. The biggest one has 8 million rows and contains a ~40KB VARBINARY column (not referenced nor returned anywhere in the query).

Query

DECLARE @p0 VARCHAR(50); SET @p0 = '<GUID1>'

SELECT TOP 1 p.Id, p.DateCreatedUtc, p.PreviousOwnerId
FROM (
    -- last project save
    SELECT ps.Id AS psId, p.*
    FROM Projects p
    CROSS APPLY (
      SELECT TOP 1 *
      FROM ProjectSaves
      WHERE ProjectId = p.Id
      ORDER BY LastModifiedUtc DESC
    ) AS ps
    WHERE p.OwnerId = @p0
) p
CROSS APPLY (
    SELECT TOP 1 *
    FROM ProjectSavePhotos
    WHERE ProjectSaveId = p.psId AND (name LIKE 'uploads%')
) ps
WHERE P.IsDeleted = 0 AND p.Id NOT IN ('<GUID2>')
ORDER BY p.DateCreatedUtc DESC

p.OwnerId is indexed and Azure automatically created two more indexes:

on OwnerId and Id and

on IsDeleted, OwnerId and Id

ps.ProjectId is indexed and includes LastModifiedUtc

psp.ProjectSaveId is indexed and includes name

Question

How can I diagnose the root cause of the 20s PAGEIOLATCH_SH? Could it be the mere presence of the VARBINARY column? If so, how can I confirm that?

References read

https://www.sqlshack.com/handling-excessive-sql-server-pageiolatch_sh-wait-types/

https://sqlperformance.com/2014/06/io-subsystem/knee-jerk-waits-pageiolatch-sh


问:
In C++, is it possible to reference data-structure portions like stl list in C++?
```<code>list<int> a;
list<int> &b = a;
</code>```

Where each element added in a will be added in b, and any element deleted in a will also be deleted in b.

I would like to know, is it possible to refer to just portions of structures?

Something like this:

```
GeneralList : [___A,___B,___C]

________A :[_______&B,__&C]

________B :[__&A,_______&C]

________C :[______________]
```

GeneralList = The list that contains all elements (A,B,C,D)

A = It is a list that just refers to GeneralList[B],GeneralList[C].

B = It is a list that just refers to GeneralList[A],GeneralList[C].

C = An empty list.

the code would be

```<code>list<char> GeneralList;
GeneralList.push_back('A');
GeneralList.push_back('B');
GeneralList.push_back('C');
list<char> &A = {GeneralList['B'],GeneralList['C']};
list<char> &B = {GeneralList['A'],GeneralList['C']};
</code>```

but I have syntax error

The objective is to be able to eliminate an element from the GeneralList and, because it is referenced in the other lists, the time to eliminate will be only 1 step.

I tried to use structures, like union, reference_wrapper but I can not understand them.
The reasons for using this pattern is that it should be ensured that when one element changes the other list are automatically updated.

The goal is to be able to call just one delete. So I dont need to delete in the other lists, and the complexity will be greater. GeneralList is a list of dependencies of a company, and A, B, C are modules of the same, when deleting an element of GeneralList I am saying that this module is already installed and as already installed I do not need to install it in other parts.

答:
You are describing a view, which could be defined as an entity with a container-like interface, that actually looks at (and in some cases, can modify) content of another container.

Up to C++14 there are no views in the standard library. The standard containers all contain their own objects. In C++17 there will be string_view and array_view, however they only support viewing a contiguous subset of the target container.  You will still need to roll your own implementation of the view that you describe in your question.

Body:
list<int> a;
list<int> &b = a;

Where each element added in a will be added in b, and any element deleted in a will also be deleted in b.

I would like to know, is it possible to refer to just portions of structures?

Something like this:

GeneralList : [___A,___B,___C]

________A :[_______&B,__&C]

________B :[__&A,_______&C]

________C :[______________]

GeneralList = The list that contains all elements (A,B,C,D)

A = It is a list that just refers to GeneralList[B],GeneralList[C].

B = It is a list that just refers to GeneralList[A],GeneralList[C].

C = An empty list.

the code would be

list<char> GeneralList;
GeneralList.push_back('A');
GeneralList.push_back('B');
GeneralList.push_back('C');
list<char> &A = {GeneralList['B'],GeneralList['C']};
list<char> &B = {GeneralList['A'],GeneralList['C']};

but I have syntax error

The objective is to be able to eliminate an element from the GeneralList and, because it is referenced in the other lists, the time to eliminate will be only 1 step.

I tried to use structures, like union, reference_wrapper but I can not understand them.
The reasons for using this pattern is that it should be ensured that when one element changes the other list are automatically updated.

The goal is to be able to call just one delete. So I dont need to delete in the other lists, and the complexity will be greater. GeneralList is a list of dependencies of a company, and A, B, C are modules of the same, when deleting an element of GeneralList I am saying that this module is already installed and as already installed I do not need to install it in other parts.


问:
MVCBuildViews not working correctly
So I edited my csproj file on an MVC 3 RTM application to set the following property:

```<code><MvcBuildViews>true</MvcBuildViews>
</code>```

This should cause my views to be complied during build and force a build error if my view is broken. This is the only change I made, however, when I try to build the application, I get the following error:

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.

The project compiles and runs successfully if I change back to  false,

The following are the build tasks configured in the csproj file (these were never manually edited, they were added by Visual Studio 2010)

```<code><Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target> -->
<Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
  <AspNetCompiler VirtualPath="temp" PhysicalPath="$(WebProjectOutputDir)" />
</Target>
</code>```

Am I missing something here? How do I get MVC 3 / Visual Studio 2010 configured correctly to validate my views at build time?

答: When you get this error do you have another web.config file in your obj folder? If you are using MSDeploy this might help: MSDN Blog: The Aspnet  Compiler Build Task in Visual Studio 2010 ASP.Net MVC 2 Projects, if not, maybe another web.config is being generated by some tool you are running.</p>

Title: MVCBuildViews not working correctly

Body:
So I edited my csproj file on an MVC 3 RTM application to set the following property:

<MvcBuildViews>true</MvcBuildViews>

This should cause my views to be complied during build and force a build error if my view is broken. This is the only change I made, however, when I try to build the application, I get the following error:

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.

The project compiles and runs successfully if I change back to  false,

The following are the build tasks configured in the csproj file (these were never manually edited, they were added by Visual Studio 2010)

<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target> -->
<Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
  <AspNetCompiler VirtualPath="temp" PhysicalPath="$(WebProjectOutputDir)" />
</Target>

Am I missing something here? How do I get MVC 3 / Visual Studio 2010 configured correctly to validate my views at build time?


问:
Google Drive API Unable to Write Folder
I have pieced this together from Google documentation I am trying to write a test folder to the Google Drive APP but I am getting this error:

```<code>An error occurred: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission"
   }
  ],
  "code": 403,
  "message": "Insufficient Permission"
 }
}
</code>```

Searching online it seems that this is due to the scopes? Which is why I've added so many below:

```<code>require_once 'vendor/autoload.php';

date_default_timezone_set('Europe/London');

define('APPLICATION_NAME', 'Pauls Google Drive');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret_paul.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
        Google_Service_Drive::DRIVE,
        Google_Service_Drive::DRIVE_FILE,
        Google_Service_Drive::DRIVE_APPDATA,
        Google_Service_Drive::DRIVE_READONLY,
        Google_Service_Drive::DRIVE_METADATA,
        Google_Service_Drive::DRIVE_METADATA_READONLY
    )
));

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfig(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');

    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

        // Store the credentials to disk.
        if(!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($accessToken));
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
    }
    return str_replace('~', realpath($homeDirectory), $path);
}

function getFolderExistsCreate($service, $folderName, $folderDesc) {
    // List all user files (and folders) at Drive root
    $files = $service->files->listFiles();
    $found = false;
    // Go through each one to see if there is already a folder with the specified name
    foreach ($files['items'] as $item) {
        if ($item['title'] == $folderName) {
            $found = true;
            return $item['id'];
            break;
        }
    }
    // If not, create one
    if ($found == false) {
        $folder = new Google_Service_Drive_DriveFile();
        //Setup the folder to create
        $folder->setName($folderName);
        if(!empty($folderDesc))
            $folder->setDescription($folderDesc);
        $folder->setMimeType('application/vnd.google-apps.folder');
        //Create the Folder
        try {
            $createdFile = $service->files->create($folder, array(
                'mimeType' => 'application/vnd.google-apps.folder',
            ));
            // Return the created folder's id
            return $createdFile->id;
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

getFolderExistsCreate( $service, 'Test', 'This is a test folder' );
</code>```

getFolderExistsCreate is the method actually creating the folder, which is just over half way down the code. Please help!! :) I have been able to return a list of files from the drive without error, so I am happy that the credentials and connection are OK.

答:
How about the following confirmations?

Confirm that Drive API is enabled, again.

You said that you added scopes. So please remove the file of ~/.credentials/drive-php-quickstart.json once. And then, run your script and create drive-php-quickstart.json again. By this, the added scopes is reflected to the access token and refresh token.

If these were not useful for you, I'm sorry.

Title: Google Drive API Unable to Write Folder

Body:
I have pieced this together from Google documentation I am trying to write a test folder to the Google Drive APP but I am getting this error:

An error occurred: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission"
   }
  ],
  "code": 403,
  "message": "Insufficient Permission"
 }
}

Searching online it seems that this is due to the scopes? Which is why I've added so many below:

require_once 'vendor/autoload.php';

date_default_timezone_set('Europe/London');

define('APPLICATION_NAME', 'Pauls Google Drive');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret_paul.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
        Google_Service_Drive::DRIVE,
        Google_Service_Drive::DRIVE_FILE,
        Google_Service_Drive::DRIVE_APPDATA,
        Google_Service_Drive::DRIVE_READONLY,
        Google_Service_Drive::DRIVE_METADATA,
        Google_Service_Drive::DRIVE_METADATA_READONLY
    )
));

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfig(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');

    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

        // Store the credentials to disk.
        if(!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($accessToken));
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
    }
    return str_replace('~', realpath($homeDirectory), $path);
}

function getFolderExistsCreate($service, $folderName, $folderDesc) {
    // List all user files (and folders) at Drive root
    $files = $service->files->listFiles();
    $found = false;
    // Go through each one to see if there is already a folder with the specified name
    foreach ($files['items'] as $item) {
        if ($item['title'] == $folderName) {
            $found = true;
            return $item['id'];
            break;
        }
    }
    // If not, create one
    if ($found == false) {
        $folder = new Google_Service_Drive_DriveFile();
        //Setup the folder to create
        $folder->setName($folderName);
        if(!empty($folderDesc))
            $folder->setDescription($folderDesc);
        $folder->setMimeType('application/vnd.google-apps.folder');
        //Create the Folder
        try {
            $createdFile = $service->files->create($folder, array(
                'mimeType' => 'application/vnd.google-apps.folder',
            ));
            // Return the created folder's id
            return $createdFile->id;
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

getFolderExistsCreate( $service, 'Test', 'This is a test folder' );

getFolderExistsCreate is the method actually creating the folder, which is just over half way down the code. Please help!! :) I have been able to return a list of files from the drive without error, so I am happy that the credentials and connection are OK.


问:
How to create two JVMs on one machine by different addresses
I want to simulate java rmi on my computer and for that I need two separate JVM which are running on one version of eclipse , please tell me how can I do that and how to set unique address for each of the JVMs</p>

答:
I want to simulate java rmi on my computer and for that I need two separate JVM

No you don't.

which are running on one version of eclipse,

You don't need that either.

please tell me how can I do that and how to set unique address for each of the JVMs

Or that. It doesn't matter in the least about the client IP address, and the server IP address is simply 127.0.0.1 for purposes of the Registry.

Just run the server program and then the client program. I do this in a single IDE all the time.

Everything you have been told about needing a separate physical or virtual machine is BS.


答:
You are trying to break down a function call into an expression tree.

You cannot do this to a plain old Func, but you can do this to a System.Linq.Expressions.Expression.

```<code>using System;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Reflection;

public class ThisCss
{
    public int useThis(int num)
    {
        return 0;
    }
}

public class Program
{
    public static Type ExtractClassType(Expression<Func<int>> methodCall)
    {
        if (methodCall.Body.NodeType == ExpressionType.Call)
        {
            MethodCallExpression memberExpression = (System.Linq.Expressions.MethodCallExpression)methodCall.Body;
            MethodInfo memberInfo = memberExpression.Method;
            return memberInfo.DeclaringType;
        }
        else
        {
            throw new InvalidOperationException("Unable to extract a method call from this expression");
        }
    }

    public static void Main()
    {
        var methods = new List<Expression<Func<int>>>();
        methods.Add(() => new ThisCss().useThis(0));

        var type = ExtractClassType(methods[0]);

        Console.WriteLine("{0}", type);
    }
}
</code>```

Title: How to extract the class name out of List< Func< Int32 > >

Body:
You are trying to break down a function call into an expression tree.

You cannot do this to a plain old Func, but you can do this to a System.Linq.Expressions.Expression.

using System;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Reflection;

public class ThisCss
{
    public int useThis(int num)
    {
        return 0;
    }
}

public class Program
{
    public static Type ExtractClassType(Expression<Func<int>> methodCall)
    {
        if (methodCall.Body.NodeType == ExpressionType.Call)
        {
            MethodCallExpression memberExpression = (System.Linq.Expressions.MethodCallExpression)methodCall.Body;
            MethodInfo memberInfo = memberExpression.Method;
            return memberInfo.DeclaringType;
        }
        else
        {
            throw new InvalidOperationException("Unable to extract a method call from this expression");
        }
    }

    public static void Main()
    {
        var methods = new List<Expression<Func<int>>>();
        methods.Add(() => new ThisCss().useThis(0));

        var type = ExtractClassType(methods[0]);

        Console.WriteLine("{0}", type);
    }
}


问:
Rails 3: how to reverse ERB "<%=" default behaviour so I can inject HTML?
My question relates to this one, but I am trying to reverse the default Rails 3 behavior of "<%=" so that I can inject HTML.

In my scenario, I have an old Rails 2 plug that generates HTML. My view will then need to inject this HTML in the page.

When this plugin creates HTML like this stored in a variable html_to_show:

```<code><p class="notice"><span></span>Sorry about this, but we have a problem...</p><p class="error"><span></span>Cannot go to next step</p>
</code>```

and in the view I try to show the contents of html_to_show like this:

```<code><%= html_to_show %>
</code>```

... what I get in my browser is this:

```<code><p class="notice"><span></span>Sorry about this, but we have a problem...</p><p class="error"><span></span>Cannot go to next step</p>
</code>```

How can I get Rails 3 to inject the contents of html_to_show exactly as it is, without any sanitization?

答:
```<code><%= raw html_to_show %>
</code>```

That should do it.

Body:
My question relates to this one, but I am trying to reverse the default Rails 3 behavior of "<%=" so that I can inject HTML.

In my scenario, I have an old Rails 2 plug that generates HTML. My view will then need to inject this HTML in the page.

When this plugin creates HTML like this stored in a variable html_to_show:

Sorry about this, but we have a problem...

Cannot go to next step

and in the view I try to show the contents of html_to_show like this:

<%= html_to_show %>

... what I get in my browser is this:

Sorry about this, but we have a problem...

Cannot go to next step

How can I get Rails 3 to inject the contents of html_to_show exactly as it is, without any sanitization?

Body:
<%= raw html_to_show %>

That should do it.


问:
Is it possible to build a RESTful server in Unity?
I am working on researching and building a sample game. I want Clients to call REST APIs to the Unity REST server. Then, the server will run some functions according to the REST APIs. For example, when a Client wants to move some object in the  game, a Client can simply call REST API to the unity server and then the server will run functions in order to move that object.

From my understanding, Unity can be a REST client where we can send GET and POST to the existing REST server by using UnityWebRequest in Unity.Network. However, I would like to know if is it possible to build a REST server within Unity? Or is there any third-party package to support this?

If possible, please kindly give me some suggestions.

答:
So from my understanding, you want to build your REST Server inside unity.

OWIN/Katana Project is only support for .net 4.0 after searching from internet, but unity just support .net 3.5 at the moment, but of course there's experiment feature in unity that allow us to use net 4.6 (this is still experimental feature)

besides of OWIN, there's SignalIR Client that targeted for Net 2.0
which i found here https://github.com/NVentimiglia/SignalR-Unity3d

So this way you have the ability to make REST API Server in Unity.
But why would you make this in unity?

If you want to call the REST API from unity, you already have that ability by using WWW class, that make web request from unity, with get or even post method.
and this allow you to receive text, image, even byte data from that request.

For Example
if you have your REST written with OWIN in some self hosted owin.
and you want to move your player based on what server want.

you can call the api, and then receive some information of three floating point stored as JSON object, that you can then read or cast to vector3.

maybe the reason why you want to build the REST in unity is you need the UnityEngine Feature for doing something.

so, yes unity can be REST client by using WWW or UnityWebRequest.
but can unity be the server is still questionable for me.

This some example of calling my api from unity

```<code>IEnumerator GetUserInfo (int id)
{
    //the Form Post
    WWWForm form = new WWWForm();
    form.AddField("frameCount", Time.frameCount.ToString());
    //the GET
    WWW www = new WWW ("http://myapi.com:33/user/" + id, form)

    //the request
    yield return wwww;

    if (!string.IsNullOrEmpty(www.error)) {
        print(www.error);
    }
    else {
        print("Get reply : " + www.text);
    }
}
</code>```

CMIIW

Body:
So from my understanding, you want to build your REST Server inside unity.

OWIN/Katana Project is only support for .net 4.0 after searching from internet, but unity just support .net 3.5 at the moment, but of course there's experiment feature in unity that allow us to use net 4.6 (this is still experimental feature)

besides of OWIN, there's SignalIR Client that targeted for Net 2.0
which i found here https://github.com/NVentimiglia/SignalR-Unity3d

So this way you have the ability to make REST API Server in Unity.
But why would you make this in unity?

If you want to call the REST API from unity, you already have that ability by using WWW class, that make web request from unity, with get or even post method.
and this allow you to receive text, image, even byte data from that request.

For Example
if you have your REST written with OWIN in some self hosted owin.
and you want to move your player based on what server want.

you can call the api, and then receive some information of three floating point stored as JSON object, that you can then read or cast to vector3.

maybe the reason why you want to build the REST in unity is you need the UnityEngine Feature for doing something.

so, yes unity can be REST client by using WWW or UnityWebRequest.
but can unity be the server is still questionable for me.

This some example of calling my api from unity

IEnumerator GetUserInfo (int id)
{
    //the Form Post
    WWWForm form = new WWWForm();
    form.AddField("frameCount", Time.frameCount.ToString());
    //the GET
    WWW www = new WWW ("http://myapi.com:33/user/" + id, form)

    //the request
    yield return wwww;

    if (!string.IsNullOrEmpty(www.error)) {
        print(www.error);
    }
    else {
        print("Get reply : " + www.text);
    }
}

CMIIW


问:
Round float in Python
I have a problem with float in Python...

I have this in a variable:

```<code>i = 9.600000000000001
</code>```

And I would transform in this:

```<code>i = 9.60000
</code>```

with five numbers after the decimal point and rounded.

Title: Round float in Python

Body:
I have a problem with float in Python...

I have this in a variable:

i = 9.600000000000001

And I would transform in this:

i = 9.60000

with five numbers after the decimal point and rounded.

Body:
>>> format(9.60000001,'.5f')
'9.60000'
>>>


问:
Django : migration success but not creating new table
I've been using django migration to handle database. recently, I split session into two, one is for reading and the other one is for writing. After done this, I made new migration file that adding new table and run it. It was successful,

```<code>Operations to perform:
Apply all migrations: food
Running migrations:
Applying food.0107_auto_20171116_0849... OK
</code>```

However, when I checked mysql database using shell, there was no new table. I deleted django migrations history and attempted few times more but the result was same. It says migration applied but there was no new table. This is my migration file

```<code># -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-16 08:49
from __future__ import unicode_literals

from django.db import migrations, models
import uuid

class Migration(migrations.Migration):

    dependencies = [
        ('bubi', '0106_auto_20171110_1452'),
    ]

    operations = [
        migrations.CreateModel(
           name='FoodHistory',
              fields=[
                  ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
                  ('date', models.DateField(verbose_name='updated date')),
        ],
        options={
            'verbose_name': 'food updated date',
            'verbose_name_plural': 'food updated date',
        },
    ),
]
</code>```

I wonder if splited session may affects to do migrations. thanks!

EDIT

I added my local_settings.py

```<code>DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
},
'read': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
},
'write': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
}
}
</code>```

答:
If you use multiple DBs in Django, When migrating, you need to check the Database Router that you coded.

Check for "allow_migrate" method in your database router class.

This is official Django documentation about this issue.

https://docs.djangoproject.com/ko/1.11/topics/db/multi-db/#allow_migrate

Body:
I've been using django migration to handle database. recently, I split session into two, one is for reading and the other one is for writing. After done this, I made new migration file that adding new table and run it. It was successful,

Operations to perform:
Apply all migrations: food
Running migrations:
Applying food.0107_auto_20171116_0849... OK

However, when I checked mysql database using shell, there was no new table. I deleted django migrations history and attempted few times more but the result was same. It says migration applied but there was no new table. This is my migration file

# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-16 08:49
from __future__ import unicode_literals

from django.db import migrations, models
import uuid

class Migration(migrations.Migration):

    dependencies = [
        ('bubi', '0106_auto_20171110_1452'),
    ]

    operations = [
        migrations.CreateModel(
           name='FoodHistory',
              fields=[
                  ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
                  ('date', models.DateField(verbose_name='updated date')),
        ],
        options={
            'verbose_name': 'food updated date',
            'verbose_name_plural': 'food updated date',
        },
    ),
]

I wonder if splited session may affects to do migrations. thanks!

EDIT

I added my local_settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
},
'read': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
},
'write': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
}
}


问:
How to get average, median, mean stats from a file which has numbers in first column?
I have a file in which I have numbers in seconds like below:

```<code>0.01033
0.003797
0.02648
0.007583
0.007491
0.028038
0.012794
0.00524
0.019655
0.019643
0.012969
0.011087
0.044564
</code>```

What is the best way by which I can get "average", "mean", "median", "95th percentile" and "99th percentile" from this file? I have this file in my linux box so I need some linux command by which I can get those stats.

答:
As explained in the previous tool datamash is a very powerful tool!
If you want a full awk solution:

Average: (variables are auto-initialized to zero by awk)

```<code>awk '{ sum += $1; n++ } END { if (n > 0) print sum / n; }'
</code>```

or in the Shebang notation:

```<code>#!/bin/awk

{ sum += $2 }
END { if (NR > 0) print sum / NR }
</code>```

Median:

```<code>#/usr/bin/env awk
{
    count[NR] = $1;
}
END {
    if (NR % 2) {
        print count[(NR + 1) / 2];
    } else {
        print (count[(NR / 2)] + count[(NR / 2) + 1]) / 2.0;
    }
}
</code>```

You need to sort the file before using it:

```<code>sort -n data_file | awk -f median.awk
</code>```

95th Percentile:

```<code>sort file -n | awk 'BEGIN{c=0} length($0){a[c]=$0;c++}END{p5=(c/100*5); p5=p5%1?int(p5)+1:p5; print a[c-p5-1]}'
</code>```

Last but not least you can use Miller
https://github.com/johnkerl/miller/tree/v4.5.0

Body:
I have a file in which I have numbers in seconds like below:

0.01033
0.003797
0.02648
0.007583
0.007491
0.028038
0.012794
0.00524
0.019655
0.019643
0.012969
0.011087
0.044564

What is the best way by which I can get "average", "mean", "median", "95th percentile" and "99th percentile" from this file? I have this file in my linux box so I need some linux command by which I can get those stats.

Body:
As explained in the previous tool datamash is a very powerful tool!
If you want a full awk solution:

Average: (variables are auto-initialized to zero by awk)

awk '{ sum += $1; n++ } END { if (n > 0) print sum / n; }'

or in the Shebang notation:

#!/bin/awk

{ sum += $2 }
END { if (NR > 0) print sum / NR }

Median:

#/usr/bin/env awk
{
    count[NR] = $1;
}
END {
    if (NR % 2) {
        print count[(NR + 1) / 2];
    } else {
        print (count[(NR / 2)] + count[(NR / 2) + 1]) / 2.0;
    }
}

You need to sort the file before using it:

sort -n data_file | awk -f median.awk

95th Percentile:

sort file -n | awk 'BEGIN{c=0} length($0){a[c]=$0;c++}END{p5=(c/100*5); p5=p5%1?int(p5)+1:p5; print a[c-p5-1]}'

Last but not least you can use Miller
https://github.com/johnkerl/miller/tree/v4.5.0


问:
Xcode 8.1 UI Testing twoFingerTap() fails on Google Maps view
Since upgrading to Xcode 8.1 my UI tests that use twoFingerTap() to zoom out on a Google Maps GMSMapView have been failing with

Assertion Failure: Element.swift:135: UI Testing Failure - Unable to find unoccluded area to perform event.

The message preceding that is

Recompute visible frame by excluding frames of occluding elements StatusBar and "the view's identifier"

Anyone have any idea what I should do about that? Tried tapWithNumberOfTaps(1, numberOfTouches: 2) and same thing happens.

NB. The problem is definitely with multi-finger taps only -- doubleTap() and pinchWithScale(2.0, velocity: 1.0) continue to work fine under Xcode 8.1. pinchWithScale(0.5, velocity: -1.0) continues to move origin instead of zooming, which is what it did to GMSMapView in Xcode 7 as well.

答:
Not sure if you already solve your case but It will help if you put Google Map inside another view and then set it's accessibility in storyboard (make sure Accessibility's "Enabled" and "User Interaction Enabled" is checked)

Then you can find it inside otherElements and tap or doubleFingerTap on it.