问:
Asp.Net Core: Access custom AuthorizeAttribute property in AuthorizeHandler
As I am working on Asp.Net core Authorization part, I needed a new property in AuthorizeAttribute which I want to utilize as a extra permission value. So, I have extended the AuthorizeAttribute in my own custom Authorize attribute. See below:

```<code>public class RoleAuthorizeAttribute : Microsoft.AspNetCore.Authorization.AuthorizeAttribute
    {
        public string Permission { get; private set; }

        public RoleAuthorizeAttribute(string policy, string permission) : base(policy)
        {
            this.Permission = permission;
        }
    }
</code>```

Then, I've created an AuthorizationHandler to check for the requirement as below:

```<code>public class RolePermissionAccessRequirement : AuthorizationHandler<RolePermissionDb>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolePermissionDb requirement)
        {
            // check here..
            context.Succeed(requirement);

            return Task.FromResult(0);
        }
    }
</code>```

All respective service collection mapping I have already done, just omitted here.

Now, I want my attribute to use like this on controller action level:

```<code>[RoleAuthorize("DefaultPolicy", "CustomPermission")]
public IActionResult List()
{
}
</code>```

Would anybody suggest me how would I access the permission property value given on the top of Action method in the handler RolePermissionAccessRequirement ??

I want to perform some sort of access rule based on custom permission value given in the Authorize attribute on top of Action method.

Thanks in advance!

答:
To parametrize a custom Authorize attribute, create an authorization filter implementing IAsyncAuthorizationFilter. Then wrap the filter in a TypeFilterAttribute-derived attribute. This attribute can accept parameters and pass it to the authorization filter's constructor.

Usage example:

```<code>[AuthorizePermission(Permission.Foo, Permission.Bar)]
public IActionResult Index()
{
    return View();
}
</code>```

Implementation:

```<code>public class AuthorizePermissionAttribute : TypeFilterAttribute
{
    public AuthorizePermissionAttribute(params Permission[] permissions)
        : base(typeof(PermissionFilter))
    {
        Arguments = new[] { new PermissionRequirement(permissions) };
        Order = Int32.MinValue;
    }
}

public class PermissionFilter : Attribute, IAsyncAuthorizationFilter
{
    private readonly IAuthorizationService _authService;
    private readonly PermissionRequirement _requirement;

    public PermissionFilter(
        IAuthorizationService authService,
        PermissionRequirement requirement)
    {
        //you can inject dependencies via DI
        _authService = authService;

        //the requirement contains permissions you set in attribute above
        //for example: Permission.Foo, Permission.Bar
        _requirement = requirement;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        bool ok = await _authService.AuthorizeAsync(
            context.HttpContext.User, null, _requirement);

        if (!ok) context.Result = new ChallengeResult();
    }
}
</code>```

In addition, register a PermissionHandler in DI to handle PermissionRequirement with permission list:

```<code>public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
</code>```

Look at this this GitHub project for a complete example.

Body:
As I am working on Asp.Net core Authorization part, I needed a new property in AuthorizeAttribute which I want to utilize as a extra permission value. So, I have extended the AuthorizeAttribute in my own custom Authorize attribute. See below:

public class RoleAuthorizeAttribute : Microsoft.AspNetCore.Authorization.AuthorizeAttribute
    {
        public string Permission { get; private set; }

        public RoleAuthorizeAttribute(string policy, string permission) : base(policy)
        {
            this.Permission = permission;
        }
    }

Then, I've created an AuthorizationHandler to check for the requirement as below:

public class RolePermissionAccessRequirement : AuthorizationHandler<RolePermissionDb>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolePermissionDb requirement)
        {
            // check here..
            context.Succeed(requirement);

            return Task.FromResult(0);
        }
    }

All respective service collection mapping I have already done, just omitted here.

Now, I want my attribute to use like this on controller action level:

[RoleAuthorize("DefaultPolicy", "CustomPermission")]
public IActionResult List()
{
}

Would anybody suggest me how would I access the permission property value given on the top of Action method in the handler RolePermissionAccessRequirement ??

I want to perform some sort of access rule based on custom permission value given in the Authorize attribute on top of Action method.

Thanks in advance!

Body:
To parametrize a custom Authorize attribute, create an authorization filter implementing IAsyncAuthorizationFilter. Then wrap the filter in a TypeFilterAttribute-derived attribute. This attribute can accept parameters and pass it to the authorization filter's constructor.

Usage example:

[AuthorizePermission(Permission.Foo, Permission.Bar)]
public IActionResult Index()
{
    return View();
}

Implementation:

public class AuthorizePermissionAttribute : TypeFilterAttribute
{
    public AuthorizePermissionAttribute(params Permission[] permissions)
        : base(typeof(PermissionFilter))
    {
        Arguments = new[] { new PermissionRequirement(permissions) };
        Order = Int32.MinValue;
    }
}

public class PermissionFilter : Attribute, IAsyncAuthorizationFilter
{
    private readonly IAuthorizationService _authService;
    private readonly PermissionRequirement _requirement;

    public PermissionFilter(
        IAuthorizationService authService,
        PermissionRequirement requirement)
    {
        //you can inject dependencies via DI
        _authService = authService;

        //the requirement contains permissions you set in attribute above
        //for example: Permission.Foo, Permission.Bar
        _requirement = requirement;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        bool ok = await _authService.AuthorizeAsync(
            context.HttpContext.User, null, _requirement);

        if (!ok) context.Result = new ChallengeResult();
    }
}

In addition, register a PermissionHandler in DI to handle PermissionRequirement with permission list:

public class PermissionHandler : AuthorizationHandler<PermissionRequirement>

Look at this this GitHub project for a complete example.


来源: stackexchange

问:
JSoup won't get the right date range for Google Search results
I've lurked on here for a while, but I officially joined today because I'm having a huge problem with JSoup. I'm creating a program in which I need to gather the small titles and descriptions that Google News gives when you search for a certain topic.

When I use this code:

(x.getURL() gives a google search page in news, from a certain date to another certain date)

```<code>    URLBuilder x = new URLBuilder(q, from.getMmddyyyy(), to.getMmddyyyy());

    String p = x.getURL();
    System.out.println(p);
    doc = Jsoup.connect(p).userAgent("Mozilla").get();
    System.out.println(doc);

    Elements links = doc.select("h3[class=_hJs");
    for (Element link : links) {
        Elements titles = link.select("a[class=l _PMs]");
        String title = titles.text();

        Elements bodies = link.select("div[class=st]");
        String body = bodies.text();

        System.out.println("Title: "+title);
        System.out.println("Body: "+body+"\n");
    }
</code>```

The code works well, but the only problem is instead of giving me titles and bodies from the time I wanted, it gives me the html if you were to google my query right now in news. For example, my URL builder would give the URL (and also the URL that's printed in the output):

https://google.com/search?q=Apple+&tbm=nws&num=100&tbs=cdr%3A1%2Ccd_min%3A01%2F19%2F2016%2Ccd_max%3A01%2F23%2F2016

Which if you follow gives you a google search results for "Apple" with 100 results per page, from News, from the dates 1/19/2016 to 1/23/2016 only. However, when in the next line I print out the HTML doc, it gives the HTML from a google search results for "Apple" with 100 results per page, from News, but from the current date.

What's happening here? I've tried everything, but why won't JSoup give the HTML from that specific page??? I've tried all different types of .userAgents including not using that altogether but nothing with that has worked.

Seriously, if you even have an inkling of an idea for a solution please share it with me. I'll try anything, this thing has been killing me.

答:
When you try to connect with Jsoup it shows the latest news. I don't know why it is happening, but you can reach that page with date range in browser. So you can use selenium to crawl that page here is how you can do it;

```<code>WebDriver driver = null;
    DesiredCapabilities cap = DesiredCapabilities.chrome();
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:\\Users\\PER\\Desktop\\phantomjs-2.1.1-windows\\bin\\chrome.exe");
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "accept-encoding", "gzip, deflate, sdch, br");
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "Accept-Language", "en-US;q=0.6,en;q=0.4");
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");

    driver = new ChromeDriver(cap);
    driver.navigate().to("https://google.com/search?q=Apple+&tbm=nws&num=100&tbs=cdr%3A1%2Ccd_min%3A01%2F19%2F2016%2Ccd_max%3A01%2F23%2F2016");;

    String doc = driver.getPageSource();
    Document document = Jsoup.parse(doc);
    System.out.println(doc);

    Elements links = document.select("h3[class=_hJs");
    for (Element link : links) {
        Elements titles = link.select("a[class=l _PMs]");
        String title = titles.text();

        Elements bodies = link.select("div[class=st]");
        String body = bodies.text();

        System.out.println("Title: "+title);
        System.out.println("Body: "+body+"\n");
    }
</code>```

also you need to import these;

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've lurked on here for a while, but I officially joined today because I'm having a huge problem with JSoup. I'm creating a program in which I need to gather the small titles and descriptions that Google News gives when you search for a certain topic.

When I use this code:

(x.getURL() gives a google search page in news, from a certain date to another certain date)

    URLBuilder x = new URLBuilder(q, from.getMmddyyyy(), to.getMmddyyyy());

    String p = x.getURL();
    System.out.println(p);
    doc = Jsoup.connect(p).userAgent("Mozilla").get();
    System.out.println(doc);

    Elements links = doc.select("h3[class=_hJs");
    for (Element link : links) {
        Elements titles = link.select("a[class=l _PMs]");
        String title = titles.text();

        Elements bodies = link.select("div[class=st]");
        String body = bodies.text();

        System.out.println("Title: "+title);
        System.out.println("Body: "+body+"\n");
    }

The code works well, but the only problem is instead of giving me titles and bodies from the time I wanted, it gives me the html if you were to google my query right now in news. For example, my URL builder would give the URL (and also the URL that's printed in the output):

https://google.com/search?q=Apple+&tbm=nws&num=100&tbs=cdr%3A1%2Ccd_min%3A01%2F19%2F2016%2Ccd_max%3A01%2F23%2F2016

Which if you follow gives you a google search results for "Apple" with 100 results per page, from News, from the dates 1/19/2016 to 1/23/2016 only. However, when in the next line I print out the HTML doc, it gives the HTML from a google search results for "Apple" with 100 results per page, from News, but from the current date.

What's happening here? I've tried everything, but why won't JSoup give the HTML from that specific page??? I've tried all different types of .userAgents including not using that altogether but nothing with that has worked.

Seriously, if you even have an inkling of an idea for a solution please share it with me. I'll try anything, this thing has been killing me.

Body:
When you try to connect with Jsoup it shows the latest news. I don't know why it is happening, but you can reach that page with date range in browser. So you can use selenium to crawl that page here is how you can do it;

WebDriver driver = null;
    DesiredCapabilities cap = DesiredCapabilities.chrome();
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:\\Users\\PER\\Desktop\\phantomjs-2.1.1-windows\\bin\\chrome.exe");
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "accept-encoding", "gzip, deflate, sdch, br");
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "Accept-Language", "en-US;q=0.6,en;q=0.4");
    cap.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");

    driver = new ChromeDriver(cap);
    driver.navigate().to("https://google.com/search?q=Apple+&tbm=nws&num=100&tbs=cdr%3A1%2Ccd_min%3A01%2F19%2F2016%2Ccd_max%3A01%2F23%2F2016");;

    String doc = driver.getPageSource();
    Document document = Jsoup.parse(doc);
    System.out.println(doc);

    Elements links = document.select("h3[class=_hJs");
    for (Element link : links) {
        Elements titles = link.select("a[class=l _PMs]");
        String title = titles.text();

        Elements bodies = link.select("div[class=st]");
        String body = bodies.text();

        System.out.println("Title: "+title);
        System.out.println("Body: "+body+"\n");
    }

also you need to import these;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;


问:
Using while loop to repeat a function that generates random numbers
I am having trouble when using a while loop to repeat a function.

I am not an American student so please be understanding of my English.
I have no clue of what is going wrong and hope I can get some help.
I am aware that I can append the random number in the function and return it.

The question is:

There is a dice with 5 sides and each side says a , b , c , d ,e. If I get a d or an e, I throw again and I log this until I get an a,b or a c. ex) if I throw the dice 5times I can get: d, e, d, d, a or something like this. In my program, I want to simulate this process. I want it so that the function randomnumbers can generate random numbers from 0~4. I want the main program to loop the process of getting random numbers via this function(mandatory). Then, I want the main program to retrieve these values and use it to determine what these numbers mean(0=a, 1=b, 2=c, 3=d, 4=e) on the dice and append them to a separate list. Finally I want to print the values in the list where I logged the values I got.

I specifically have to do the following:

The function should only return one random number, not a list

The main program should be responsible for making a list and printing the value retrieved from the function.

```<code>def randomnumbers():
    r = 0
    import random
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while randomnumbers()>=3:
    List.append(abc[randomnumbers()])

for i in List:
    print i
</code>```

答:
```<code>import random
def randomnumbers():
    r = 0
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while True:
    nb = randomnumbers()
    if nb >=3:
     List.append(abc[nb])
    elif not List:
        continue
    else:
        break

for i in List:
    print i
</code>```

Body:
I am having trouble when using a while loop to repeat a function.

I am not an American student so please be understanding of my English.
I have no clue of what is going wrong and hope I can get some help.
I am aware that I can append the random number in the function and return it.

The question is:

There is a dice with 5 sides and each side says a , b , c , d ,e. If I get a d or an e, I throw again and I log this until I get an a,b or a c. ex) if I throw the dice 5times I can get: d, e, d, d, a or something like this. In my program, I want to simulate this process. I want it so that the function randomnumbers can generate random numbers from 0~4. I want the main program to loop the process of getting random numbers via this function(mandatory). Then, I want the main program to retrieve these values and use it to determine what these numbers mean(0=a, 1=b, 2=c, 3=d, 4=e) on the dice and append them to a separate list. Finally I want to print the values in the list where I logged the values I got.

I specifically have to do the following:

The function should only return one random number, not a list

The main program should be responsible for making a list and printing the value retrieved from the function.

def randomnumbers():
    r = 0
    import random
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while randomnumbers()>=3:
    List.append(abc[randomnumbers()])

for i in List:
    print i


问:
How to detect when a custom tableview cell goes off the screen?
In my app I have a custom tableViewCell,

I also have a View Controller with a tableView, where I display custom tableViewCells.

Is there a method (ViewController method or TableViewCell method) which fires when tableViewCell goes off the screen, I need to make some Core Data updates in it for my cell.

(I need to know the method, because I need to update Core Data value of Timer() in my tableViewCell when it goes off the screen.)

答:
following tableview delegate used to detect cell end displaying :: tableView:didEndDisplayingCell:forRowAtIndexPath:

```<code>func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath)
</code>```

above method fire when cell removed from tableview or cell ending its diplaying.

Body:
following tableview delegate used to detect cell end displaying :: tableView:didEndDisplayingCell:forRowAtIndexPath:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath)

above method fire when cell removed from tableview or cell ending its diplaying.


问:
Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress
How do I fix the error below?

Your PHP installation appears to be missing the MySQL extension which is required by WordPress.

I use my NAS with a telnet connection.

I installed FFP 0.7

My php.ini is in: ffp/etc/php.ini and I uncommented everything I thought to be of use.

Below is a portion of my php.ini file;

```<code>;If you wish to have an extension loaded automatically, use the following
; syntax:
;
;   extension=modulename.extension
;
; For example, on Windows:
;
extension=msql.dll
;
; ... or under UNIX:
;
extension=msql.so
;
; ... or with a path:
;
extension=/ffp/lib/extensions/no-debug-non-zts-20100525/mysql.so
;

extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll
extension=pdo.so
extension=pdo_sqlite.so
extension=sqlite.so
extension=pdo_mysql.so
</code>```

The outstanding issue is that when I run in phpinfo(), I see the module MySQLi activated but not MySQL.

MySQL is working as expected just as PHP and Lighttpd web server.

I equally have phpmyadmin working.

It's on a Zyxel NSA310.

Also, when mysqld is started, it creates a shortcut from my root to: ffp/opt/mysql.. and every time I restart my NAS the shortcut is deleted.

Does anyone might know a trick for this?

答:
I had same issue as mentioned " Your PHP installation appears to be missing the MySQL extension which is required by WordPress" in resellerclub hosting.

I went through this thread and came to know that php version should be greater than > 5.6 so that wordpress will automatically gets converted to mysqli

Then logged into my cpanel searched for php in cpanel to check for the version, luckly was able to find that my version of php was 5.2 and changed that to 5.6  by making sure mysqli is tick marked in the option window and saved it is working fine now.

ContentLicense: CC BY-SA 4.0

Body:
How do I fix the error below?

Your PHP installation appears to be missing the MySQL extension which is required by WordPress.

I use my NAS with a telnet connection.

I installed FFP 0.7

My php.ini is in: ffp/etc/php.ini and I uncommented everything I thought to be of use.

Below is a portion of my php.ini file;

;If you wish to have an extension loaded automatically, use the following
; syntax:
;
;   extension=modulename.extension
;
; For example, on Windows:
;
extension=msql.dll
;
; ... or under UNIX:
;
extension=msql.so
;
; ... or with a path:
;
extension=/ffp/lib/extensions/no-debug-non-zts-20100525/mysql.so
;

extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll
extension=pdo.so
extension=pdo_sqlite.so
extension=sqlite.so
extension=pdo_mysql.so

The outstanding issue is that when I run in phpinfo(), I see the module MySQLi activated but not MySQL.

MySQL is working as expected just as PHP and Lighttpd web server.

I equally have phpmyadmin working.

It's on a Zyxel NSA310.

Also, when mysqld is started, it creates a shortcut from my root to: ffp/opt/mysql.. and every time I restart my NAS the shortcut is deleted.

Does anyone might know a trick for this?


问:
How can I change my cURL call to recognise more than 1 parameter?
I want to make the following curl call to get an access token:

```<code>curl -k -XPOST --user "{user}" {url}/access_token -d 'grant_type=authorization_code&code={code}&redirect_uri={uri}'
</code>```

However, I get the following error statement:

```<code>'code' is not recognized as ane internal or external command, operable program or batch file.
'redirect_uri' is not recognized as ane internal or external command, operable program or batch file.
</code>```

When I check the trace, I see that the body only contains this: 'grant_type=authorization_code

What can I do to make sure all the parameters get passed?

答:
It seems that the &-character is interpreted as "execute as background job". Try escaping each &-character with a backslash - like \&

Alternatively you could write your content into a file and reference this file via the parameter -d @file
The @-character is important for curl to know that file is a file name.

Body:
I want to make the following curl call to get an access token:

curl -k -XPOST --user "{user}" {url}/access_token -d 'grant_type=authorization_code&code={code}&redirect_uri={uri}'

However, I get the following error statement:

'code' is not recognized as ane internal or external command, operable program or batch file.
'redirect_uri' is not recognized as ane internal or external command, operable program or batch file.

When I check the trace, I see that the body only contains this: 'grant_type=authorization_code

What can I do to make sure all the parameters get passed?


问:
Android App - returning Null Pointer Exception on Eclair
I am having an issue with an Android app I am writing.  It crashes on Eclair due to a NullPointerException but runs fine on Froyo and Gingerbread.  Can anyone tell me how to rewrite this to avoid the Null Pointer Exception?  Thanks in advance.

Edit
I added the stack trace and logcat, I might have read it wrong originally, looks like it could be my TabWidget?

logcat references this line in my Home class:

```<code>tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Snow", res.getDrawable(R.drawable.weather2)).setContent(new Intent(this,FirstTab.class)));
</code>```

Logcat

```<code>ERROR/AndroidRuntime(314): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wilcoxis.android.kirkwood/com.wilcoxis.android.Home}: java.lang.NullPointerException
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
ERROR/AndroidRuntime(314):     at android.os.Handler.dispatchMessage(Handler.java:99)
ERROR/AndroidRuntime(314):     at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.main(ActivityThread.java:4363)
ERROR/AndroidRuntime(314):     at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(314):     at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/AndroidRuntime(314):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
ERROR/AndroidRuntime(314):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
ERROR/AndroidRuntime(314):     at dalvik.system.NativeStart.main(Native Method)
ERROR/AndroidRuntime(314): Caused by: java.lang.NullPointerException
ERROR/AndroidRuntime(314):     at android.widget.TabWidget.onFocusChange(TabWidget.java:351)
ERROR/AndroidRuntime(314):     at android.view.View.onFocusChanged(View.java:2622)
ERROR/AndroidRuntime(314):     at android.view.View.handleFocusGainInternal(View.java:2445)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.handleFocusGainInternal(ViewGroup.java:404)
ERROR/AndroidRuntime(314):     at android.view.View.requestFocus(View.java:3562)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:976)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1021)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:977)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1021)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:980)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1021)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:977)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1021)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:980)
ERROR/AndroidRuntime(314):     at android.view.View.requestFocus(View.java:3513)
ERROR/AndroidRuntime(314):     at android.view.View.requestFocus(View.java:3491)
ERROR/AndroidRuntime(314):     at android.widget.TabHost.setCurrentTab(TabHost.java:334)
ERROR/AndroidRuntime(314):     at android.widget.TabHost.addTab(TabHost.java:213)
ERROR/AndroidRuntime(314):     at com.wilcoxis.android.Home.onCreate(Home.java:83)
ERROR/AndroidRuntime(314):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
ERROR/AndroidRuntime(314):     ... 11 more
</code>```

Stack Trace

```<code>DalvikVM[localhost:8610]
    Thread [<3> main] (Suspended (exception NullPointerException))
        TabWidget.onFocusChange(View, boolean) line: 351
        TabWidget(View).onFocusChanged(boolean, int, Rect) line: 2622
        TabWidget(View).handleFocusGainInternal(int, Rect) line: 2445
        TabWidget(ViewGroup).handleFocusGainInternal(int, Rect) line: 404
        TabWidget(View).requestFocus(int, Rect) line: 3562
        TabWidget(ViewGroup).requestFocus(int, Rect) line: 976
        LinearLayout(ViewGroup).onRequestFocusInDescendants(int, Rect) line: 1021
        LinearLayout(ViewGroup).requestFocus(int, Rect) line: 977
        TabHost(ViewGroup).onRequestFocusInDescendants(int, Rect) line: 1021
        TabHost(ViewGroup).requestFocus(int, Rect) line: 980
        FrameLayout(ViewGroup).onRequestFocusInDescendants(int, Rect) line: 1021
        FrameLayout(ViewGroup).requestFocus(int, Rect) line: 977
        PhoneWindow$DecorView(ViewGroup).onRequestFocusInDescendants(int, Rect) line: 1021
        PhoneWindow$DecorView(ViewGroup).requestFocus(int, Rect) line: 980
        PhoneWindow$DecorView(View).requestFocus(int) line: 3513
        PhoneWindow$DecorView(View).requestFocus() line: 3491
        TabHost.setCurrentTab(int) line: 334
        TabHost.addTab(TabHost$TabSpec) line: 213
        Home.onCreate(Bundle) line: 83
        Instrumentation.callActivityOnCreate(Activity, Bundle) line: 1047
        ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2459
        ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2512
        ActivityThread.access$2200(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 119
        ActivityThread$H.handleMessage(Message) line: 1863
        ActivityThread$H(Handler).dispatchMessage(Message) line: 99
        Looper.loop() line: 123
        ActivityThread.main(String[]) line: 4363
        Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
        Method.invoke(Object, Object...) line: 521
        ZygoteInit$MethodAndArgsCaller.run() line: 860
        ZygoteInit.main(String[]) line: 618
        NativeStart.main(String[]) line: not available [native method]
    Thread [<13> Binder Thread #2] (Running)
    Thread [<11> Binder Thread #1] (Running)
</code>```

答: You're not handling the case where you get an empty string back from the service.  Actually, you're not handling any cases of failure.  Check that you're getting valid data back, and don't operate on reference variables (like your string array) that could potentially be null</p>

Body:
I am having an issue with an Android app I am writing.  It crashes on Eclair due to a NullPointerException but runs fine on Froyo and Gingerbread.  Can anyone tell me how to rewrite this to avoid the Null Pointer Exception?  Thanks in advance.

Edit
I added the stack trace and logcat, I might have read it wrong originally, looks like it could be my TabWidget?

logcat references this line in my Home class:

tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Snow", res.getDrawable(R.drawable.weather2)).setContent(new Intent(this,FirstTab.class)));

Logcat

ERROR/AndroidRuntime(314): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wilcoxis.android.kirkwood/com.wilcoxis.android.Home}: java.lang.NullPointerException
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
ERROR/AndroidRuntime(314):     at android.os.Handler.dispatchMessage(Handler.java:99)
ERROR/AndroidRuntime(314):     at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.main(ActivityThread.java:4363)
ERROR/AndroidRuntime(314):     at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(314):     at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/AndroidRuntime(314):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
ERROR/AndroidRuntime(314):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
ERROR/AndroidRuntime(314):     at dalvik.system.NativeStart.main(Native Method)
ERROR/AndroidRuntime(314): Caused by: java.lang.NullPointerException
ERROR/AndroidRuntime(314):     at android.widget.TabWidget.onFocusChange(TabWidget.java:351)
ERROR/AndroidRuntime(314):     at android.view.View.onFocusChanged(View.java:2622)
ERROR/AndroidRuntime(314):     at android.view.View.handleFocusGainInternal(View.java:2445)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.handleFocusGainInternal(ViewGroup.java:404)
ERROR/AndroidRuntime(314):     at android.view.View.requestFocus(View.java:3562)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:976)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1021)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:977)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1021)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:980)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1021)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:977)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1021)
ERROR/AndroidRuntime(314):     at android.view.ViewGroup.requestFocus(ViewGroup.java:980)
ERROR/AndroidRuntime(314):     at android.view.View.requestFocus(View.java:3513)
ERROR/AndroidRuntime(314):     at android.view.View.requestFocus(View.java:3491)
ERROR/AndroidRuntime(314):     at android.widget.TabHost.setCurrentTab(TabHost.java:334)
ERROR/AndroidRuntime(314):     at android.widget.TabHost.addTab(TabHost.java:213)
ERROR/AndroidRuntime(314):     at com.wilcoxis.android.Home.onCreate(Home.java:83)
ERROR/AndroidRuntime(314):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
ERROR/AndroidRuntime(314):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
ERROR/AndroidRuntime(314):     ... 11 more

Stack Trace

DalvikVM[localhost:8610]
    Thread [<3> main] (Suspended (exception NullPointerException))
        TabWidget.onFocusChange(View, boolean) line: 351
        TabWidget(View).onFocusChanged(boolean, int, Rect) line: 2622
        TabWidget(View).handleFocusGainInternal(int, Rect) line: 2445
        TabWidget(ViewGroup).handleFocusGainInternal(int, Rect) line: 404
        TabWidget(View).requestFocus(int, Rect) line: 3562
        TabWidget(ViewGroup).requestFocus(int, Rect) line: 976
        LinearLayout(ViewGroup).onRequestFocusInDescendants(int, Rect) line: 1021
        LinearLayout(ViewGroup).requestFocus(int, Rect) line: 977
        TabHost(ViewGroup).onRequestFocusInDescendants(int, Rect) line: 1021
        TabHost(ViewGroup).requestFocus(int, Rect) line: 980
        FrameLayout(ViewGroup).onRequestFocusInDescendants(int, Rect) line: 1021
        FrameLayout(ViewGroup).requestFocus(int, Rect) line: 977
        PhoneWindow$DecorView(ViewGroup).onRequestFocusInDescendants(int, Rect) line: 1021
        PhoneWindow$DecorView(ViewGroup).requestFocus(int, Rect) line: 980
        PhoneWindow$DecorView(View).requestFocus(int) line: 3513
        PhoneWindow$DecorView(View).requestFocus() line: 3491
        TabHost.setCurrentTab(int) line: 334
        TabHost.addTab(TabHost$TabSpec) line: 213
        Home.onCreate(Bundle) line: 83
        Instrumentation.callActivityOnCreate(Activity, Bundle) line: 1047
        ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2459
        ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2512
        ActivityThread.access$2200(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 119
        ActivityThread$H.handleMessage(Message) line: 1863
        ActivityThread$H(Handler).dispatchMessage(Message) line: 99
        Looper.loop() line: 123
        ActivityThread.main(String[]) line: 4363
        Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
        Method.invoke(Object, Object...) line: 521
        ZygoteInit$MethodAndArgsCaller.run() line: 860
        ZygoteInit.main(String[]) line: 618
        NativeStart.main(String[]) line: not available [native method]
    Thread [<13> Binder Thread #2] (Running)
    Thread [<11> Binder Thread #1] (Running)

ContentLicense: CC BY-SA 2.5


问:
asp.net core with angular 4 and Kendo UI
I setup Angular 2 app with ASP.NET Core Web Application Visual Studio 2017

https://www.youtube.com/watch?v=ISXzctm5-D4

and it was working, but I added Kendo UI to my app, and now I get this error.

答:
```<code>1. Add kendo ui on angular
    npm login --registry=https://registry.npm.telerik.com/ --scope=@progress

2. npm install --save @progress/kendo-angular-buttons @progress/kendo-angular-l10n @angular/animations

3. src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { ButtonsModule } from '@progress/kendo-angular-buttons';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,

        // Register the modules
        BrowserAnimationsModule,
        ButtonsModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

4. src/app/app.component.html:
<h1>{{title}}</h1>

<button kendoButton (click)="onButtonClick()" [primary]="true">My Kendo UI Button</button>

5. app.component.ts:

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    title = 'Hello World!';

    onButtonClick() {
        this.title = 'Hello from Kendo UI!';
    }`enter code here`
}
</code>```


问:
Issue in converting received ajax data
Ajax is used to retrieve data from server.

Data is displayed successfully on alert as

```<code>data: {"status": "Active","broadcastmsg": "msg"}
</code>```

But in html i.e.

 it is displayed as undefined.

Looks like a minor issue , though I have been trying to solve this since last 24 hours and nothing seems to be working. Please suggest what's going wrong.

Client.php

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<body>
<script>
    function myFunction(val) {

            $.post("test.php",
            {
              d_id: 1,
              date: val
            },
            function(hstatus){
                alert(hstatus);
                myJSON = JSON.stringify(hstatus);
                localStorage.setItem("testJSON", myJSON);

                //Retrieving data:
                text = localStorage.getItem("testJSON");
                obj = JSON.parse(text);
                document.getElementById("demo").innerHTML = obj.status;
            });
        }

    </script>
        <p id="demo"></p>
        <div id="future_date" style="display:block;" class="col-xs-12">
            <input type="date" name="txt" value="" onchange="myFunction(this.value)">
        </div>

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

EDIT

if we pass hstatus = {"status": "Active","broadcastmsg": "msg"} manually it's showing result.

Thus issue is in converting from

data: {"status": "Active","broadcastmsg": "msg"}

to

{"status": "Active","broadcastmsg": "msg"}

答:
What I suspect is the format of string which is coming from server.

if your alert is giving this output:
data: {"status": "Active","broadcastmsg": "msg"}
Then JSON.parse won't be able to parse it. Since it's not an object or any type. This will give a syntax error.

Following is the right format of string which you should send from server then everything JSON.parse will work fine.
{"data": {"status": "Active","broadcastmsg": "msg"}}

So solution for this which I can guess is:
hstatus parameter of success callback is of plainObject
So try following:

```<code>myJSON = JSON.stringify(hstatus.data);
</code>```

Let me know in case it doesnt work, will dig more.

Title: Issue in converting received ajax data

Body:
Ajax is used to retrieve data from server.

Data is displayed successfully on alert as

data: {"status": "Active","broadcastmsg": "msg"}

But in html i.e.

 it is displayed as undefined.

Looks like a minor issue , though I have been trying to solve this since last 24 hours and nothing seems to be working. Please suggest what's going wrong.

Client.php

<!DOCTYPE html>

            <input type="date" name="txt" value="" onchange="myFunction(this.value)">

EDIT

if we pass hstatus = {"status": "Active","broadcastmsg": "msg"} manually it's showing result.

Thus issue is in converting from

data: {"status": "Active","broadcastmsg": "msg"}

to

{"status": "Active","broadcastmsg": "msg"}

Body:
What I suspect is the format of string which is coming from server.

if your alert is giving this output:
data: {"status": "Active","broadcastmsg": "msg"}
Then JSON.parse won't be able to parse it. Since it's not an object or any type. This will give a syntax error.

Following is the right format of string which you should send from server then everything JSON.parse will work fine.
{"data": {"status": "Active","broadcastmsg": "msg"}}

So solution for this which I can guess is:
hstatus parameter of success callback is of plainObject
So try following:

myJSON = JSON.stringify(hstatus.data);

Let me know in case it doesnt work, will dig more.


问:
How to format automatically generated WebGrid date columns
I see there are a lot of answers exaplaining how to format a DateTime WebGrid column individually, but is it possible to set a WebGrid to automtically format all columns of type DateTime?

I ask because my WebGrid automatically pulls the data from my classes, so I never actually access webgrid.Column, due to the fact that I am using (an attempt at) a generic WebGrid view:

```<code>@model IEnumerable<MVCQCPage.Helpers.IGriddable>

@{
    var grid = new WebGrid(new List<object>());
    var linkPrefix = string.Empty;
    var selectable = false;

    if (Model.Count() > 0)
    {
        string[] columnNames = { };

        var firstItem = Model.First();

        linkPrefix = firstItem.RowLinkPrefix;
        columnNames = firstItem.ColumnHeaders;
        selectable = firstItem.Selectable;

        grid = new WebGrid(Model,
            rowsPerPage: 100,
            columnNames: columnNames);
    }
}
<div id="grid">
    @grid.GetHtml(
            tableStyle: "table",
            alternatingRowStyle: "alternate",
            headerStyle: "header"
        )
</div>
</code>```

Where IGriddable looks like this:

```<code>public interface IGriddable
{
    string RowLinkPrefix { get; }
    string[] ColumnHeaders { get; }
    bool Selectable { get; }
}
</code>```

So that each class that implements it might contain something like this:

```<code>public string[] ColumnHeaders { get; } = new string[] { "SampleNo", "QCDate", "StatusClerk", "StatusSupervisor" };
public string RowLinkPrefix { get { return $"/receiving/{Pallet.Grv.GRVNo}/{Pallet.PalletSeq}/"; } }
public bool Selectable { get; } = true;
</code>```

I tried adding a Displayformatto the QCDate property, but this does not help.

Any help or advice is much appreciated, thanks!

答:
I managed to work around this by amending my properties like this:

```<code>public DateTime QCDate { get; set; }
public string Date { get { return QCDate.ToString("dd/MM/yyyy"); } }
</code>```

And changing ColumnHeaders to

```<code>public string[] ColumnHeaders { get; } = new string[] { "SampleNo", "Date", "StatusClerk", "StatusSupervisor" };
</code>```

So that when this item is displayed in a grid it will now show the short date string that I needed.

Body:
I see there are a lot of answers exaplaining how to format a DateTime WebGrid column individually, but is it possible to set a WebGrid to automtically format all columns of type DateTime?

I ask because my WebGrid automatically pulls the data from my classes, so I never actually access webgrid.Column, due to the fact that I am using (an attempt at) a generic WebGrid view:

@model IEnumerable<MVCQCPage.Helpers.IGriddable>

@{
    var grid = new WebGrid(new List<object>());
    var linkPrefix = string.Empty;
    var selectable = false;

    if (Model.Count() > 0)
    {
        string[] columnNames = { };

        var firstItem = Model.First();

        linkPrefix = firstItem.RowLinkPrefix;
        columnNames = firstItem.ColumnHeaders;
        selectable = firstItem.Selectable;

        grid = new WebGrid(Model,
            rowsPerPage: 100,
            columnNames: columnNames);
    }
}

    @grid.GetHtml(
            tableStyle: "table",
            alternatingRowStyle: "alternate",
            headerStyle: "header"
        )

Where IGriddable looks like this:

public interface IGriddable
{
    string RowLinkPrefix { get; }
    string[] ColumnHeaders { get; }
    bool Selectable { get; }
}

So that each class that implements it might contain something like this:

public string[] ColumnHeaders { get; } = new string[] { "SampleNo", "QCDate", "StatusClerk", "StatusSupervisor" };
public string RowLinkPrefix { get { return $"/receiving/{Pallet.Grv.GRVNo}/{Pallet.PalletSeq}/"; } }
public bool Selectable { get; } = true;

I tried adding a Displayformatto the QCDate property, but this does not help.

Any help or advice is much appreciated, thanks!

Body:
I managed to work around this by amending my properties like this:

public DateTime QCDate { get; set; }
public string Date { get { return QCDate.ToString("dd/MM/yyyy"); } }

And changing ColumnHeaders to

public string[] ColumnHeaders { get; } = new string[] { "SampleNo", "Date", "StatusClerk", "StatusSupervisor" };

So that when this item is displayed in a grid it will now show the short date string that I needed.


问:
Why String addition using + allows moved to new address in java?
I have got some information that string addition using + allows moved to new memory address in java but  in case for int  it is not happening why?

means

```<code>String a="fi-rstname";
a=a+" "+lastname;
</code>```

a+" "+lastname moves to the new address instead of address of a

but for

```<code> int a=22;
a=a+2323;
</code>```

a+2323; vale does not move to the new address for addition why?

答:
String is immutable in Java. You can't change the content of immutable field after initialization. That is the reason, you create a new memory case.

You can get more information in this post : String is immutable. What exactly is the meaning? that explain well why String is immutable.

Body:
I have got some information that string addition using + allows moved to new memory address in java but  in case for int  it is not happening why?

means

String a="fi-rstname";
a=a+" "+lastname;

a+" "+lastname moves to the new address instead of address of a

but for

 int a=22;
a=a+2323;

a+2323; vale does not move to the new address for addition why?


问:
writing multiple returns to a file in python
I need to write the returns of each function in to a text file. I have used the code below. However, when I have multiple functions, this process of using file1.write() consumes a lot of time and lines. Is there any smarter method to write the outputs?

```<code>def function1():
    #some operation
    return "Status 1" + "\n\n"

def function2():
    #some operation
    return "Status 2" + "\n\n"

def function3():
    #some operation
    return "Status 1" + "\n\n"

if __name__ == '__main__':

    file1 = open("test.txt","w")

    output1 = function1()
    file1.write(output1)

    output2 = function2()
    file1.write(output2)

    output3 = function3()
    file1.write(output3)

    file1.close()
</code>```

I have modified the code since many are confused with my question.

答:
It looks like you're trying not to repeat yourself so much.  You can take advantage of the fact that functions are "first class objects" in order to iterate over them.  Also, you can take advantage of the features of the functools module to reuse the basic structure of nearly identical functions.  The following code will produce identical output to your example with far less repetition of code:

```<code>import functools

def base_func(func_id):
    return 'status of {}\n\n'.format(func_id)

functions = [functools.partial(base_func, i+1) for i in range(3)]

if __name__ == '__main__':
    with open('test.txt','w') as file1:
        for func in functions:
            file1.write(func())
</code>```

However, it will almost certainly not run execute any faster, but given your example I'd hardly thing computing performance should  be of great concern.

Body:
I need to write the returns of each function in to a text file. I have used the code below. However, when I have multiple functions, this process of using file1.write() consumes a lot of time and lines. Is there any smarter method to write the outputs?

def function1():
    #some operation
    return "Status 1" + "\n\n"

def function2():
    #some operation
    return "Status 2" + "\n\n"

def function3():
    #some operation
    return "Status 1" + "\n\n"

if __name__ == '__main__':

    file1 = open("test.txt","w")

    output1 = function1()
    file1.write(output1)

    output2 = function2()
    file1.write(output2)

    output3 = function3()
    file1.write(output3)

    file1.close()

I have modified the code since many are confused with my question.

Body:
It looks like you're trying not to repeat yourself so much.  You can take advantage of the fact that functions are "first class objects" in order to iterate over them.  Also, you can take advantage of the features of the functools module to reuse the basic structure of nearly identical functions.  The following code will produce identical output to your example with far less repetition of code:

import functools

def base_func(func_id):
    return 'status of {}\n\n'.format(func_id)

functions = [functools.partial(base_func, i+1) for i in range(3)]

if __name__ == '__main__':
    with open('test.txt','w') as file1:
        for func in functions:
            file1.write(func())

However, it will almost certainly not run execute any faster, but given your example I'd hardly thing computing performance should  be of great concern.


问:
load list depend on category in knockout
trying to make a small application
there is the category ( places, coffee Shops, Clubs)

how to load the list of respective category in the knockout.

how to load the list of tags (only once) and which is clickable and load the tag list when click

here is my code
JS

```<code>var points = [
    {
        tag: "places",
        name: "Dubai Marina",
    }, {
        tag: "places",
        name: "Burj Khalifa",
    }, {
        tag: "Coffee",
        name: "StarBucks",
    }, {
        tag: "Coffee",
        name: "Costa",
    }, {
        tag: "Club",
        name: "Beach Club",
    }, {
        tag: "Club",
        name: "Cheers Club",
    }
];

var View = function (data) {
    this.name = ko.observable(data.name);
};

var ViewModel = function () {
    var self = this;
    this.pointsList = ko.observableArray([]);

    points.forEach(function (e) {
        self.pointsList.push(new View(e));
        console.log(e)
    });

    self.activeTag = function (a) {
        console.log(a);
    }
}
ko.applyBindings(new ViewModel());
</code>```

** HTML**

```<code><ul class="list-inline" data-bind="foreach:points">
        <li data-bind="text:tag, click: activeTag"></li>
    </ul>

    <ul data-bind="foreach:points">
        <li data-bind="text: name"></li>
    </ul>
</code>```

Or is there any better solution?

答:
so there is really nice website here http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html that has all the functions you need.

I used the link and used the following
1. flatten the array (just get the names)
2. getting just the unique values in the array (unique names)
3. did a foreach on the unique names. then on click. I changed my search criteria for a filtered array.  you can run the whole thing below. just click run snippet.

function point(tag, name) {
  var self = this;
  this.tag = ko.observable(tag);
  this.name = ko.observable(name)
}

function viewModel() {
  var self = this;
  this.points = ko.observableArray('');
  this.selectedPoint = ko.observable('');

  this.setSelected = function(item) {
    self.selectedPoint(item);
  }

  this.justtags = ko.computed(function() {
    var tags = ko.utils.arrayMap(this.points(), function(item) {
      return item.tag();
    });
    return tags.sort();
  }, this);

  this.uniquetags = ko.dependentObservable(function() {
    return ko.utils.arrayGetDistinctValues(self.justtags()).sort();
  }, this);

  this.filteredNames = ko.computed(function() {
    var filter = self.selectedPoint()
    if (!filter) {
    } else {
      return ko.utils.arrayFilter(this.points(), function(item) {
        if (item.tag() === filter) {
          return item
        };
      });
    }
  }, this);

}

var data = [{
  tag: "places",
  name: "Dubai Marina",
}, {
  tag: "places",
  name: "Burj Khalifa",
}, {
  tag: "Coffee",
  name: "StarBucks",
}, {
  tag: "Coffee",
  name: "Costa",
}, {
  tag: "Club",
  name: "Beach Club",
}, {
  tag: "Club",
  name: "Cheers Club",
}];

var vm = new viewModel();
$(document).ready(function() {
  ko.applyBindings(vm);
  $.each(data, function(i, item) {
    vm.points.push(new point(item.tag, item.name));
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="list-inline" data-bind="foreach:uniquetags">
  <li data-bind="text:$data, click: $parent.setSelected"></li>
</ul>

<ul class="list-inline" data-bind="foreach:filteredNames">
  <li data-bind="text:name"></li>
</ul></code>```

Body:
trying to make a small application
there is the category ( places, coffee Shops, Clubs)

how to load the list of respective category in the knockout.

how to load the list of tags (only once) and which is clickable and load the tag list when click

here is my code
JS

var points = [
    {
        tag: "places",
        name: "Dubai Marina",
    }, {
        tag: "places",
        name: "Burj Khalifa",
    }, {
        tag: "Coffee",
        name: "StarBucks",
    }, {
        tag: "Coffee",
        name: "Costa",
    }, {
        tag: "Club",
        name: "Beach Club",
    }, {
        tag: "Club",
        name: "Cheers Club",
    }
];

var View = function (data) {
    this.name = ko.observable(data.name);
};

var ViewModel = function () {
    var self = this;
    this.pointsList = ko.observableArray([]);

    points.forEach(function (e) {
        self.pointsList.push(new View(e));
        console.log(e)
    });

    self.activeTag = function (a) {
        console.log(a);
    }
}
ko.applyBindings(new ViewModel());

** HTML**

Or is there any better solution?

Body:
so there is really nice website here http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html that has all the functions you need.

I used the link and used the following
1. flatten the array (just get the names)
2. getting just the unique values in the array (unique names)
3. did a foreach on the unique names. then on click. I changed my search criteria for a filtered array.  you can run the whole thing below. just click run snippet.

function point(tag, name) {
  var self = this;
  this.tag = ko.observable(tag);
  this.name = ko.observable(name)
}

function viewModel() {
  var self = this;
  this.points = ko.observableArray('');
  this.selectedPoint = ko.observable('');

  this.setSelected = function(item) {
    self.selectedPoint(item);
  }

  this.justtags = ko.computed(function() {
    var tags = ko.utils.arrayMap(this.points(), function(item) {
      return item.tag();
    });
    return tags.sort();
  }, this);

  this.uniquetags = ko.dependentObservable(function() {
    return ko.utils.arrayGetDistinctValues(self.justtags()).sort();
  }, this);

  this.filteredNames = ko.computed(function() {
    var filter = self.selectedPoint()
    if (!filter) {
    } else {
      return ko.utils.arrayFilter(this.points(), function(item) {
        if (item.tag() === filter) {
          return item
        };
      });
    }
  }, this);

}

var data = [{
  tag: "places",
  name: "Dubai Marina",
}, {
  tag: "places",
  name: "Burj Khalifa",
}, {
  tag: "Coffee",
  name: "StarBucks",
}, {
  tag: "Coffee",
  name: "Costa",
}, {
  tag: "Club",
  name: "Beach Club",
}, {
  tag: "Club",
  name: "Cheers Club",
}];

var vm = new viewModel();
$(document).ready(function() {
  ko.applyBindings(vm);
  $.each(data, function(i, item) {
    vm.points.push(new point(item.tag, item.name));
  })
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="list-inline" data-bind="foreach:uniquetags">
  <li data-bind="text:$data, click: $parent.setSelected"></li>
</ul>

<ul class="list-inline" data-bind="foreach:filteredNames">
  <li data-bind="text:name"></li>
</ul>


问:
Unable to case COM object of type
I'm getting a strange error when I'm trying to do a foreach through shapes on a page using Word interop

My code is as follows

```<code>    foreach (word.Shapes p in pages[3].Application.ActiveDocument.Shapes )
    {
        p.SelectAll();
    }
</code>```

The exception I get for some reason is this and I've no idea what I should do to fix this.

{"Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Word.Shapes'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{0002099F-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."}

答: Shapes is the collection type, but in order to iterate the shapes, you have to use Shape as type for each object.

Title: Unable to case COM object of type

Body:
I'm getting a strange error when I'm trying to do a foreach through shapes on a page using Word interop

My code is as follows

    foreach (word.Shapes p in pages[3].Application.ActiveDocument.Shapes )
    {
        p.SelectAll();
    }

The exception I get for some reason is this and I've no idea what I should do to fix this.

{"Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Word.Shapes'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{0002099F-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."}


问:
Cannot resolve function-like macro inside conditional compilation block
Consider the following - I want to check with #if #endif whether a
token is defined somewhere in the code.
I am using a CONCAT(input) macro that should glue the constant and changing parts of the token that I want to check.

Unfortunately, the approach presented below causes a compilation error:

error: missing binary operator before token "("

I have found the expressions that can be put inside a #if #endif block:

https://gcc.gnu.org/onlinedocs/cpp/If.html#If

And apparently it states that:

Macros. All macros in the expression are expanded before actual computation of the expression’s value begins.

It turns out that (CONCAT(test)) should be resolved, but it is not.

Is there any workaround allowing to resolve concatenated token names correctly in a conditional compilation block?

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

#define CONCAT(input) string##input
#define stringtest 1

int main(void)
{
    #if defined(CONCAT(test)) && (CONCAT(test)==1)
        printf("OK");
    #else
        printf("NOT");
    #endif

    return 0;
}
</code>```

答:
If you use just: #if CONCAT(test) == 1 it will work and is enought.
The statement #if defined(CONCAT(test)) does not work because CONCAT(test) will be evaluated to stringtest which will be evaluated to 1, and you can't use defined on a numerical constant.

A different situation came to my mind - what if I want to check whether the token is eg. != 1 Then if it is not defined anywhere, the condition will evaluate to true. So there would be no difference between token not defined and token being different than 1.

You could handle == 0 equal to not defined. So you could use: #if CONCAT(test) != 0 && CONCAT(test) != 1 where CONCAT(test) != 0 means defined(CONCAT(test)). That is the only alternative, because you can't get macro expansion work in a #ifdef or #if defined() statement, see this question which is very similar to yours.

The gcc documentation says:

Conditionals written like this:
      #if defined BUFSIZE && BUFSIZE >= 1024

can generally be simplified to just #if BUFSIZE >= 1024, since if BUFSIZE is not defined, it will be interpreted as having the value zero.

Also it can be helpful if you check macro expansion by using gcc -E yourSource.cpp.

gcc --help:

-E Preprocess only; do not compile, assemble or link

Body:
Consider the following - I want to check with #if #endif whether a
token is defined somewhere in the code.
I am using a CONCAT(input) macro that should glue the constant and changing parts of the token that I want to check.

Unfortunately, the approach presented below causes a compilation error:

error: missing binary operator before token "("

I have found the expressions that can be put inside a #if #endif block:

https://gcc.gnu.org/onlinedocs/cpp/If.html#If

And apparently it states that:

Macros. All macros in the expression are expanded before actual computation of the expression’s value begins.

It turns out that (CONCAT(test)) should be resolved, but it is not.

Is there any workaround allowing to resolve concatenated token names correctly in a conditional compilation block?

#include <stdio.h>

#define CONCAT(input) string##input
#define stringtest 1

int main(void)
{
    #if defined(CONCAT(test)) && (CONCAT(test)==1)
        printf("OK");
    #else
        printf("NOT");
    #endif

    return 0;
}


问:
C++ Question about default constructor
What does it mean to call a class like this:

```<code>class Example
{
 public:
  Example(void);
  ~Example(void);
}

int main(void)
{
 Example ex(); // <<<<<< what is it called to call it like this?

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

Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that would be bad?

Thanks for all answers.

答: This declares a function prototype for a function named ex, returning an Example! You are not declaring and initializing a variable here.

OwnerDisplayName: Daniel

Title: C++ Question about default constructor

Body:
What does it mean to call a class like this:

class Example
{
 public:
  Example(void);
  ~Example(void);
}

int main(void)
{
 Example ex(); // <<<<<< what is it called to call it like this?

 return(0);
}

Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that would be bad?

Thanks for all answers.

LastEditorDisplayName: codelogic

OwnerDisplayName: Konrad Rudolph


问:
Toast "sending message to a Handler on a dead thread"
I'm trying to display a simple message via Toast, and am getting a RunTime Exception "sending message to a Handler on a dead thread". The class that is trying to show the Toast message extends IntentService. The class (C2DMReceiver) actually comes from the ChromeToPhone example for C2DM. Here is the method:

```<code>/**
 * Called when a cloud message has been received.
 */
@Override
public void onMessage(Context context, Intent intent) {
    Log.i(LOG_TAG, "A message notification has occured with the cloud.");

        Log.i(LOG_TAG, "Showing toast message of the broadcast...");
        Toast toast = Toast.makeText(context, "Some text", Toast.LENGTH_LONG);
        toast.show();

        Log.i(LOG_TAG, "Sending notification of the broadcast...");
        LauncherUtils.generateNotification(this, "this is where the text would go.", "Broadcast", intent);

    }
}
</code>```

I assumed since the class extends IntentService that it would be possible to request a simple Toast message from here in this manner. Isn't this correct?

答: You must display a toast from the main thread or it will not display to the screen.  The handler executes from the thread it was created in.  If you create your handler in onCreate of your intentservice it should work as intended when you send your message.</p>

Body:
I'm trying to display a simple message via Toast, and am getting a RunTime Exception "sending message to a Handler on a dead thread". The class that is trying to show the Toast message extends IntentService. The class (C2DMReceiver) actually comes from the ChromeToPhone example for C2DM. Here is the method:

/**
 * Called when a cloud message has been received.
 */
@Override
public void onMessage(Context context, Intent intent) {
    Log.i(LOG_TAG, "A message notification has occured with the cloud.");

        Log.i(LOG_TAG, "Showing toast message of the broadcast...");
        Toast toast = Toast.makeText(context, "Some text", Toast.LENGTH_LONG);
        toast.show();

        Log.i(LOG_TAG, "Sending notification of the broadcast...");
        LauncherUtils.generateNotification(this, "this is where the text would go.", "Broadcast", intent);

    }
}

I assumed since the class extends IntentService that it would be possible to request a simple Toast message from here in this manner. Isn't this correct?


问:
Spring Security oauth2 with jwt, revocation of refresh token
I currently have an implementation of spring security with oauth2 running on spring boot. It is working as expected, and I have set the validity of access tokens to 10 minutes and refresh tokens to 30 days.

However, I would like to be able to invalidate the refresh token if a user has lost a device and wants that client to be logged out.

My token store looks as following:

```<code>@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
    final JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAcccessTokenConverter.setSigningKey(this.secret);
    return jwtAcccessTokenConverter;
}

@Bean
public TokenStore tokenStore(){
    return new JwtTokenStore(jwtAccessTokenConverter());
}
</code>```

After looking on the JwtTokenStore class the storeRefreshToken and storeAccessToken methods are blank as expected since the tokens are signed they don't have to be stored.

My plan was to store the generated refresh tokens in a database and then include this as a requirement for the refresh token to be valid.

I've been looking at the JwtTokenStore class and it looks like it can have an optional ApprovalStore.
Is this the right direction to go to solve this problem?

答:
I think the problem is very similar to the one described here. So you might want to look at the accepted answer.

Apart from this, I have two additional ideas I would like to share:

Delete the client

It really depends on how you use client ids. But you could, of course, delete a client - this would make the refresh process fail.

Deactivate the user

From the documentation:

if you inject a UserDetailsService or if one is configured globally
  anyway (e.g. in a GlobalAuthenticationManagerConfigurer) then a
  refresh token grant will contain a check on the user details, to
  ensure that the account is still active

So if you are using a UserDetailsService and your token is associated with a user you could deactivate the user to make the refresh process fail.

Body:
I currently have an implementation of spring security with oauth2 running on spring boot. It is working as expected, and I have set the validity of access tokens to 10 minutes and refresh tokens to 30 days.

However, I would like to be able to invalidate the refresh token if a user has lost a device and wants that client to be logged out.

My token store looks as following:

@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
    final JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAcccessTokenConverter.setSigningKey(this.secret);
    return jwtAcccessTokenConverter;
}

@Bean
public TokenStore tokenStore(){
    return new JwtTokenStore(jwtAccessTokenConverter());
}

After looking on the JwtTokenStore class the storeRefreshToken and storeAccessToken methods are blank as expected since the tokens are signed they don't have to be stored.

My plan was to store the generated refresh tokens in a database and then include this as a requirement for the refresh token to be valid.

I've been looking at the JwtTokenStore class and it looks like it can have an optional ApprovalStore.
Is this the right direction to go to solve this problem?


问:
How to call function if the value changes in any text input with same class?
How to call function if another function changes the value of any text field with class netvalue.</p>

```<code><input name="1" type="text" class="netvalue" readonly>
<input name="2" type="text" class="netvalue" readonly>
<input name="3" type="text" class="netvalue" readonly>

<script>
$(".netvalue").oninput(function(){
       confirm('changed');
});
<script>
</code>```

答:
you have to trigger the change function inside the function that is changing the value of the input.

see below

var input = $(".netvalue"),
    but = $("button")
$(but).on("click",function() {
   $(input).val("1").trigger("change")
})

$(input).on("change",function() {
   alert("changed")
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="1" type="text" class="netvalue" readonly>
<input name="2" type="text" class="netvalue" readonly>
<input name="3" type="text" class="netvalue" readonly>
<button>
clickME
</button></code>```

Body:
How to call function if another function changes the value of any text field with class netvalue.

<input name="1" type="text" class="netvalue" readonly>
<input name="2" type="text" class="netvalue" readonly>
<input name="3" type="text" class="netvalue" readonly>

Body:
you have to trigger the change function inside the function that is changing the value of the input.

see below

var input = $(".netvalue"),
    but = $("button")
$(but).on("click",function() {
   $(input).val("1").trigger("change")
})

$(input).on("change",function() {
   alert("changed")
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="1" type="text" class="netvalue" readonly>
<input name="2" type="text" class="netvalue" readonly>
<input name="3" type="text" class="netvalue" readonly>
<button>
clickME
</button>


问:
How to Page Break HTML Content in HTML Renderer
I have a project where HTML code is converted to a PDF using HTML Renderer. The HTML code contains a single table. The PDF is displayed but the issue is that the contents of the table are cut off at the end. So is there any solution to the problem?

PdfDocument pdf=new PdfDocument();

```<code>            var config = new PdfGenerateConfig()
            {
                MarginBottom = 20,
                MarginLeft = 20,
                MarginRight = 20,
                MarginTop = 20,
            };
            //config.PageOrientation = PageOrientation.Landscape;
            config.ManualPageSize = new PdfSharp.Drawing.XSize(1080, 828);

            pdf = PdfGenerator.GeneratePdf(html, config);

            byte[] fileContents = null;
            using (MemoryStream stream = new MemoryStream())
            {
                pdf.Save(stream, true);
                fileContents = stream.ToArray();
                return new FileStreamResult(new MemoryStream(fileContents.ToArray()), "application/pdf");
            }
</code>```

答:
HTMLRenderer should be able break the table to the next page.

See also:

https://github.com/ArthurHub/HTML-Renderer/pull/41

Make sure you are using the latest version. You may have to add those CSS properties.

Also see this answer:

https://stackoverflow.com/a/37833107/162529

Body:
I have a project where HTML code is converted to a PDF using HTML Renderer. The HTML code contains a single table. The PDF is displayed but the issue is that the contents of the table are cut off at the end. So is there any solution to the problem?

PdfDocument pdf=new PdfDocument();

            var config = new PdfGenerateConfig()
            {
                MarginBottom = 20,
                MarginLeft = 20,
                MarginRight = 20,
                MarginTop = 20,
            };
            //config.PageOrientation = PageOrientation.Landscape;
            config.ManualPageSize = new PdfSharp.Drawing.XSize(1080, 828);

            pdf = PdfGenerator.GeneratePdf(html, config);

            byte[] fileContents = null;
            using (MemoryStream stream = new MemoryStream())
            {
                pdf.Save(stream, true);
                fileContents = stream.ToArray();
                return new FileStreamResult(new MemoryStream(fileContents.ToArray()), "application/pdf");
            }


问:
Get all data in dictionary by using dictionary name
I need all data in a filled dictionary by using dictionary name below is my code

```<code>var data  = mAData.GetType().GetProperty("SEN").GetValue(mAData.SEN);
</code>```

I do not know where i am missing please help.
my finding is the problem is in GetValue() parameter

答:
You are getting the value from the property SEN. That property belongs to mAData, not to mAData.SEN. You need to give the instance to which the property belongs:

```<code>var data  = mAData.GetType().GetProperty("SEN").GetValue(mAData);
</code>```

I hope this code is just for testing purposes, since usually you can just call mAData.SEN (unless it is not accessible due to its protection level).

Body:
I need all data in a filled dictionary by using dictionary name below is my code

var data  = mAData.GetType().GetProperty("SEN").GetValue(mAData.SEN);

I do not know where i am missing please help.
my finding is the problem is in GetValue() parameter

Body:
You are getting the value from the property SEN. That property belongs to mAData, not to mAData.SEN. You need to give the instance to which the property belongs:

var data  = mAData.GetType().GetProperty("SEN").GetValue(mAData);

I hope this code is just for testing purposes, since usually you can just call mAData.SEN (unless it is not accessible due to its protection level).


问:
Using while loop to repeat a function that generates random numbers
I am having trouble when using a while loop to repeat a function.

I am not an American student so please be understanding of my English.
I have no clue of what is going wrong and hope I can get some help.
I am aware that I can append the random number in the function and return it.

The question is:

There is a dice with 5 sides and each side says a , b , c , d ,e. If I get a d or an e, I throw again and I log this until I get an a,b or a c. ex) if I throw the dice 5times I can get: d, e, d, d, a or something like this. In my program, I want to simulate this process. I want it so that the function randomnumbers can generate random numbers from 0~4. I want the main program to loop the process of getting random numbers via this function(mandatory). Then, I want the main program to retrieve these values and use it to determine what these numbers mean(0=a, 1=b, 2=c, 3=d, 4=e) on the dice and append them to a separate list. Finally I want to print the values in the list where I logged the values I got.

I specifically have to do the following:

The function should only return one random number, not a list

The main program should be responsible for making a list and printing the value retrieved from the function.

```<code>def randomnumbers():
    r = 0
    import random
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while randomnumbers()>=3:
    List.append(abc[randomnumbers()])

for i in List:
    print i
</code>```

答:
You are calling your function twice. Try to use:</p>

```<code>import random
def randomnumbers():
    r = 0
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while True:
    rand_number = randomnumbers()
    List.append(abc[rand_number])
    if rand_number <3:
        break

for i in List:
    print (i)
</code>```

Body:
I am having trouble when using a while loop to repeat a function.

I am not an American student so please be understanding of my English.
I have no clue of what is going wrong and hope I can get some help.
I am aware that I can append the random number in the function and return it.

The question is:

There is a dice with 5 sides and each side says a , b , c , d ,e. If I get a d or an e, I throw again and I log this until I get an a,b or a c. ex) if I throw the dice 5times I can get: d, e, d, d, a or something like this. In my program, I want to simulate this process. I want it so that the function randomnumbers can generate random numbers from 0~4. I want the main program to loop the process of getting random numbers via this function(mandatory). Then, I want the main program to retrieve these values and use it to determine what these numbers mean(0=a, 1=b, 2=c, 3=d, 4=e) on the dice and append them to a separate list. Finally I want to print the values in the list where I logged the values I got.

I specifically have to do the following:

The function should only return one random number, not a list

The main program should be responsible for making a list and printing the value retrieved from the function.

def randomnumbers():
    r = 0
    import random
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while randomnumbers()>=3:
    List.append(abc[randomnumbers()])

for i in List:
    print i

Body:
You are calling your function twice. Try to use:

import random
def randomnumbers():
    r = 0
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while True:
    rand_number = randomnumbers()
    List.append(abc[rand_number])
    if rand_number <3:
        break

for i in List:
    print (i)


问:
Symfony2.8 Error Using $this when not in object context using doctrine
I am tryin to call a function from my controller and return the $todolist to my controller. But i get this error, when i leave this function inside the controller it works fine, but i don't want it to be in the controller.

This is my controller

```<code>namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use AppBundle\Entity\Todo;
use AppBundle\Model\TodoModel;

class TodoController extends Controller
{
    /**
    * @Route("/", name="homepage")
    */
    public function ShowList()
    {
        $todolist = TodoModel::getTodolist();

        $html = $this->container->get('templating')->render(
            'todolist/todolist.html.twig',
            array('todolist' => $todolist)
        );

        return new response($html);
    }
}
</code>```

This is my model

```<code>namespace AppBundle\Model;

use AppBundle\Entity\Todo;

class TodoModel
{

     public function getTodolist()
     {
       $repository = $this->getDoctrine()
           ->getRepository('AppBundle:Todo');
       $todolist = $repository->findAll();
       return $todolist;
    }

}
</code>```

答:
Right way to do it is:

```<code>public function ShowList()
{
    $entityManager = $this->get('doctrine.orm.entity_manager');
    $repository = $entityManager->getRepository(Todo::class);
    $todolist = $repository->findAll();

    $html = $this->container->get('templating')->render(
        'todolist/todolist.html.twig',
        array('todolist' => $todolist)
    );

    return new Response($html);
}
</code>```

If you want to do some kind of abstraction with "TODO provider", then better naming for it is TodoProvider instead of TodoModel.

And it should look like:

```<code>namespace AppBundle\Todo;

use Doctrine\ORM\EntityManager;
use AppBundle\Entity\Todo;

class TodoProvider
{
    /**
     * @var EntityManager
     */
    private $entityManager;

    /**
     * TodoProvider constructor.
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * @return Todo[]
     */
    public function getAllTodos()
    {
        return $this->entityManager->getRepository(Todo::class)->findAll();
    }
}
</code>```

Then register TodoProvider as service (http://symfony.com/doc/current/service_container.html) and get in controller with $this->get('my_todo_provider')

Body:
I am tryin to call a function from my controller and return the $todolist to my controller. But i get this error, when i leave this function inside the controller it works fine, but i don't want it to be in the controller.

This is my controller

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use AppBundle\Entity\Todo;
use AppBundle\Model\TodoModel;

class TodoController extends Controller
{
    /**
    * @Route("/", name="homepage")
    */
    public function ShowList()
    {
        $todolist = TodoModel::getTodolist();

        $html = $this->container->get('templating')->render(
            'todolist/todolist.html.twig',
            array('todolist' => $todolist)
        );

        return new response($html);
    }
}

This is my model

namespace AppBundle\Model;

use AppBundle\Entity\Todo;

class TodoModel
{

     public function getTodolist()
     {
       $repository = $this->getDoctrine()
           ->getRepository('AppBundle:Todo');
       $todolist = $repository->findAll();
       return $todolist;
    }

}

Body:
Right way to do it is:

public function ShowList()
{
    $entityManager = $this->get('doctrine.orm.entity_manager');
    $repository = $entityManager->getRepository(Todo::class);
    $todolist = $repository->findAll();

    $html = $this->container->get('templating')->render(
        'todolist/todolist.html.twig',
        array('todolist' => $todolist)
    );

    return new Response($html);
}

If you want to do some kind of abstraction with "TODO provider", then better naming for it is TodoProvider instead of TodoModel.

And it should look like:

namespace AppBundle\Todo;

use Doctrine\ORM\EntityManager;
use AppBundle\Entity\Todo;

class TodoProvider
{
    /**
     * @var EntityManager
     */
    private $entityManager;

    /**
     * TodoProvider constructor.
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * @return Todo[]
     */
    public function getAllTodos()
    {
        return $this->entityManager->getRepository(Todo::class)->findAll();
    }
}

Then register TodoProvider as service (http://symfony.com/doc/current/service_container.html) and get in controller with $this->get('my_todo_provider')


问:
WordPress, adding font sizes to TinyMCE Advanced
I'm using the WordPress plugin Advanced TinyMCE to give my client the ability to change font sizes within the editor. My issue is, it has a predefined set of sizes to choose and I need to add more to this. Is there an easy way to hook onto this plugin to extend it?</p>

答:
got this one from WP explorer- link included for further reading as there's more useful stuff. Bear in mind it was written for 3.9 so definitely worth testing before deploying.

Adding something like this to your functions.php file should do the trick, you can edit the available sizes by adding to the array:

```<code>// Customize mce editor font sizes
if ( ! function_exists( 'wpex_mce_text_sizes' ) ) {
    function wpex_mce_text_sizes( $initArray ){
        $initArray['fontsize_formats'] = "9px 10px 12px 13px 14px 16px 18px 21px 24px 28px 32px 36px";
        return $initArray;
    }
}
add_filter( 'tiny_mce_before_init', 'wpex_mce_text_sizes' );
</code>```

link below for further reading:
WP Explorer Tiny MCE customisations

Body:
got this one from WP explorer- link included for further reading as there's more useful stuff. Bear in mind it was written for 3.9 so definitely worth testing before deploying.

Adding something like this to your functions.php file should do the trick, you can edit the available sizes by adding to the array:

// Customize mce editor font sizes
if ( ! function_exists( 'wpex_mce_text_sizes' ) ) {
    function wpex_mce_text_sizes( $initArray ){
        $initArray['fontsize_formats'] = "9px 10px 12px 13px 14px 16px 18px 21px 24px 28px 32px 36px";
        return $initArray;
    }
}
add_filter( 'tiny_mce_before_init', 'wpex_mce_text_sizes' );

link below for further reading:
WP Explorer Tiny MCE customisations


问:
I need a workaround for Resharper when it says 'Failed to modify Documents'. Does anybody know why it does this and how to get around it?
I have noticed a few times over the past months that sometimes I will use the little yellow lightbulb icon and right click it and select an option for it to fix something for me and then it just highlights what it was going to fix and pops up a message that says "Failed to modify Documents".

Has anybody had this problem?

Do you know how to overcome it?

It is almost as if resharper thinks that the document is read-only or something, even though I can manually edit the document.

答:
Allow me to chime in a bit late :

I solved this error by adding a .gitignore file and trying to commit my changes.

I cannot explain how this solved it, however, this happened to me on a completely new git repository. I've been using Git and VS for a few moth on another repository which has had a .gitignore file from the beguining and neither me nor anyone in my team had this problem before.


问:
PHP- How to display a specific form based on a selection?
I'm new in the word of html and PHP, so I would like to ask a question: in the HTMl code there is a form and inside that there are two options to select: lesson or topic.
I would like to show a form when the user selects "lesson" and another one if the user select "topic".
How can I do it?</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>Create a lesson</title>
</head>
<body>

    <?php

    if($_SERVER["REQUEST_METHOD"] == "POST")
    {

        if($_POST["argumetOrLesson"] == "topic")
        {
            //form to input a topic
        }
        else
        {
            //form to input a lesson

        }

    ?>

    <form method="post" action= "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
    <label for="argumetOrLesson">Topic or Lesson?</label>
    <select id="argumetOrLesson" name="argumetOrLesson">
      <option value="topic">Topic</option>
      <option value="lesson">Lesson</option>
    </select>
    <input type="submit" value="Submit">
  </form>

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

答:
We can use multiple php statements to separate the HTML from the PHP, but still use the PHPs conditional statements.

A nice, quick, and simple way I would do it is:

```<code><?php if($_POST["argumetOrLesson"] == "topic") { ?>
<form>
    ..your topic form html here...
</form>
<?php } else { ?>
<form>
    ..your topic form html here...
</form>
<? } ?>
</code>```

Obviously, space it out a bit and make the code formatting pretty, but it'll do the trick! :)

Body:
I'm new in the word of html and PHP, so I would like to ask a question: in the HTMl code there is a form and inside that there are two options to select: lesson or topic.
I would like to show a form when the user selects "lesson" and another one if the user select "topic".
How can I do it?

<!DOCTYPE html>

    <title>Create a lesson</title>

    <?php

    if($_SERVER["REQUEST_METHOD"] == "POST")
    {

        if($_POST["argumetOrLesson"] == "topic")
        {
            //form to input a topic
        }
        else
        {
            //form to input a lesson

        }

    ?>

    <form method="post" action= "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
    Topic or Lesson?
    <select id="argumetOrLesson" name="argumetOrLesson">
      <option value="topic">Topic</option>
      <option value="lesson">Lesson</option>
    </select>
    <input type="submit" value="Submit">
  </form>

Body:
We can use multiple php statements to separate the HTML from the PHP, but still use the PHPs conditional statements.

A nice, quick, and simple way I would do it is:

<?php if($_POST["argumetOrLesson"] == "topic") { ?>
<form>
    ..your topic form html here...
</form>
<?php } else { ?>
<form>
    ..your topic form html here...
</form>
<? } ?>

Obviously, space it out a bit and make the code formatting pretty, but it'll do the trick! :)


问:
Importing mutiple Excel(xlsx) files into SAS
I have around 70 excel documents in a library and I would like to import all of them into the SAS environment. So, I am wondering is there any macro to do this?</p>

答: Your favorite search engine will find many solutions, such as this one: http://www.sascommunity.org/wiki/Streamlining_Data-Driven_SAS_With_The_%25FOR_Macro</p>


问:
Why String addition using + allows moved to new address in java?
I have got some information that string addition using + allows moved to new memory address in java but  in case for int  it is not happening why?

means

```<code>String a="fi-rstname";
a=a+" "+lastname;
</code>```

a+" "+lastname moves to the new address instead of address of a

but for

```<code> int a=22;
a=a+2323;
</code>```

a+2323; vale does not move to the new address for addition why?

答:
Because String is immutable so each time you make change in string it'll create new object

in int we can make changes because primitive datatype is mutable(changeable).

Body:
I have got some information that string addition using + allows moved to new memory address in java but  in case for int  it is not happening why?

means

String a="fi-rstname";
a=a+" "+lastname;

a+" "+lastname moves to the new address instead of address of a

but for

 int a=22;
a=a+2323;

a+2323; vale does not move to the new address for addition why?


问:
Rails 3 Migration with longtext
I am needing to change a column type from text to longtext in my Rails script, but can't find anything on how to do this.

Has anyone ran across this?

Thanks!
Dennis

答:
The text type handles tinytext, text, mediumtext, and longtext for MySQL, if that's what you're using. Just specify the upper bound using :limit => ...

Example:

```<code>change_column :articles, :body, :text, :limit => 4294967295
</code>```

The default value of limit is 65535, as expected.

```<code>1 to 255 bytes: TINYTEXT
256 to 65535 bytes: TEXT
65536 to 16777215 bytes: MEDIUMTEXT
16777216 to 4294967295 bytes: LONGTEXT
</code>```

The MySQL documentation can be found here.

Title: Rails 3 Migration with longtext

Body:
The text type handles tinytext, text, mediumtext, and longtext for MySQL, if that's what you're using. Just specify the upper bound using :limit => ...

Example:

change_column :articles, :body, :text, :limit => 4294967295

The default value of limit is 65535, as expected.

1 to 255 bytes: TINYTEXT
256 to 65535 bytes: TEXT
65536 to 16777215 bytes: MEDIUMTEXT
16777216 to 4294967295 bytes: LONGTEXT

The MySQL documentation can be found here.


问:
chai expect passing when returned value is undefined
It seems to me that this test should not be passing

chai test

```<code>const chai = require('chai')
const expect = chai.expect;
const chaiHttp = require('chai-http');
const request = chaiHttp.expect;
const config = require('../../app/config');
const worker = require('../../app/worker');

chai.use(chaiHttp);

describe('server response', function () {
    .....

    it('should return 200', function () {
        chai.request(`http://localhost:${config.port}`)
        .get('/')
        .end(function (err, res) {
            expect('as').to.have.status(200);
        });
    });
});
</code>```

Terminal

```<code>> NODE_ENV=test mocha --timeout 20000 --recursive test/ --compilers js:babel-core/register

  server response
    ✓ should return 200

  1 passing (150ms)
</code>```

答:
I think your are missing the done callback. Try like this

```<code>it('should return 200', function (done) {
    chai.request(`http://localhost:${config.port}`)
    .get('/')
    .end(function (err, res) {
        expect('as').to.have.status(200);
        done();
    });
});
</code>```

With this code, the test will only pass if

```<code>expect('as').to.have.status(200);
</code>```

is true (which will always be false with your current example)

Body:
It seems to me that this test should not be passing

chai test

const chai = require('chai')
const expect = chai.expect;
const chaiHttp = require('chai-http');
const request = chaiHttp.expect;
const config = require('../../app/config');
const worker = require('../../app/worker');

chai.use(chaiHttp);

describe('server response', function () {
    .....

    it('should return 200', function () {
        chai.request(`http://localhost:${config.port}`)
        .get('/')
        .end(function (err, res) {
            expect('as').to.have.status(200);
        });
    });
});

Terminal

> NODE_ENV=test mocha --timeout 20000 --recursive test/ --compilers js:babel-core/register

  server response
    ✓ should return 200

  1 passing (150ms)

Body:
I think your are missing the done callback. Try like this

it('should return 200', function (done) {
    chai.request(`http://localhost:${config.port}`)
    .get('/')
    .end(function (err, res) {
        expect('as').to.have.status(200);
        done();
    });
});

With this code, the test will only pass if

expect('as').to.have.status(200);

is true (which will always be false with your current example)


问:
Javascript ES6 Get JSON from URL (no jQuery)
I was wondering if there's any ES6 way of getting json or other data from a url.

jQuery GET and Ajax calls are very common but I don't want to use jQuery in this one.

A typical call would look like this:

```<code>var root = 'http://jsonplaceholder.typicode.com';

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(data);
});
</code>```

or without jQuery something like this:

```<code>function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}
</code>```

My question is...Is there any new ways of doing this ... for example ES6 or is it still the same way?

答:
FETCH API

Example:

```<code>// url (required), options (optional)
fetch('https://davidwalsh.name/some/url', {
    method: 'get'
}).then(function(response) {

}).catch(function(err) {
    // Error :(
});
</code>```

For more information:

https://developer.mozilla.org/en/docs/Web/API/Fetch_API

Body:
I was wondering if there's any ES6 way of getting json or other data from a url.

jQuery GET and Ajax calls are very common but I don't want to use jQuery in this one.

A typical call would look like this:

var root = 'http://jsonplaceholder.typicode.com';

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(data);
});

or without jQuery something like this:

function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}

My question is...Is there any new ways of doing this ... for example ES6 or is it still the same way?

Body:
FETCH API

Example:

// url (required), options (optional)
fetch('https://davidwalsh.name/some/url', {
    method: 'get'
}).then(function(response) {

}).catch(function(err) {
    // Error :(
});

For more information:

https://developer.mozilla.org/en/docs/Web/API/Fetch_API